Skip to content
LogoLogo

@picked/app-kit

@picked/app-kit is the TypeScript library for the server and the pages of a Picked app. It implements the app protocol.

Install

npm install @picked/app-kit

Load the package with import or with require. In TypeScript, set moduleResolution to node16, nodenext or bundler.

Entry points

ImportRuns inContents
@picked/app-kitServer and browserThe manifest, the protocol types and constants, and the key functions.
@picked/app-kit/serverServerThe request handler, the installation client, and the environment reader.
@picked/app-kit/oauthServerThe start and the callback of an OAuth authorization.
@picked/app-kit/nodeNode.jsserve and frameScript.
@picked/app-kit/frameBrowserThe functions for a page in a dashboard slot.
@picked/app-kit/testingTestsA Picked API for tests.

@picked/app-kit/server also gives all the functions, constants and types of @picked/app-kit, but not FrameContext, FrameToHostMessage and HostToFrameMessage. The package also has the command app-kit-copy-frame. See app-kit-copy-frame.

@picked/app-kit

Manifest

parseManifest(value: unknown): { ok: true; manifest: AppManifest } | { ok: false; issues: string[] }
isAppUrl(value: unknown): value is string
ExportDescription
parseManifestChecks a manifest. It returns all the problems that it finds.
isAppUrlReturns true for an https URL, or an http URL on localhost, 127.0.0.1 or [::1].
ConstantValue
APP_SLOT_LOCATIONS['app-home', 'workspace-prepublish-actions', 'workspace-postpublish-actions']
APP_EVENTS['workspace.published']
APP_VALUE_TYPES['string', 'number', 'boolean', 'json']

The types are AppManifest, AppSlot, AppWorkflowTool, AppToolArgument, AppToolOutputField, AppSlotLocation, AppEventName and AppValueType. See App manifest for each field and each validation message. An app declares its manifest in the app section of picked.config.ts, with defineConfig from @picked/config/define. See The app section of picked.config.

Protocol

ConstantValue
SIGNATURE_HEADER'picked-signature'
INSTALLATION_HEADER'picked-installation-id'
APP_ASSERTION_HEADER'picked-app-assertion'
CONTEXT_HEADER'picked-context'
PICKED_KEYS_PATH'/.well-known/picked-app-keys.json'
PICKED_CONFIG_PATH'/.well-known/picked-app-config.json'

PickedAppConfig is the type of the document at PICKED_CONFIG_PATH. See App config of Picked.

verifyBody(keys: PublicKeySet, body: string, header: string | null): Promise<boolean>
verifyMcpRequest(keys: PublicKeySet, headers: Headers, body: string): Promise<InstallationRef | null>
verifySessionToken(keys: PublicKeySet, token: string): Promise<SessionClaims | null>
createAppAssertion(signer: Signer, options: { installationId: string; audience: string }): Promise<string>
signBody(signer: Signer, body: string, timestamp?: number): Promise<string>
FunctionDescription
verifyBodyReturns true when a key of keys signed body, and the time in header is not more than 300 seconds from the current time.
verifyMcpRequestVerifies an MCP request from Picked. It returns the installation from picked-context, or null.
verifySessionTokenVerifies a session token. It returns the fields of the token. It returns null for a token that is not correct or that is after its time of expiry.
createAppAssertionMakes a picked-app-assertion token for the installation. It expires after 60 seconds. audience is the origin of the Picked API.
signBodyMakes a picked-signature value. timestamp is in unix seconds, and is the current time when you do not give it.

The protocol types are InstallationRef, InstallationCreatedEvent, InstallationUpgradedEvent, InstallationDeletedEvent, LifecycleEvent, WorkspacePublishedEvent, AppEvent, ToolCall, ToolResult, SessionClaims and AppAssertionClaims. See App protocol for their fields.

Keys

generateKeyPair(): Promise<{ privateKey: string; publicKey: string; kid: string }>
createSigner(privateKey: string): Promise<Signer>
remoteKeySet(options: { url: string; fetch?: typeof fetch; refreshAfterMs?: number }): PublicKeySet
staticKeySet(keys: readonly PublicKey[]): PublicKeySet
toJwks(keys: readonly PublicKey[]): Jwks
keyIdOf(publicKey: string): Promise<string>
FunctionDescription
generateKeyPairMakes an Ed25519 private key and its public key. The private key is the base64 of its PKCS#8 DER, on one line. The public key is the base64url of its 32 raw bytes.
createSignerMakes a Signer from the base64 of a PKCS#8 DER private key, or from a PKCS#8 PEM. A PKCS#8 PEM can have \n in place of line breaks. It throws The value is not an Ed25519 private key in PKCS#8.
remoteKeySetA key set from a JSON Web Key Set URL. It reads the URL at the first use. For an unknown key ID, it reads the URL again after refreshAfterMs. The default is 60000.
staticKeySetA key set that holds the given keys.
toJwksWrites keys as a JSON Web Key Set.
keyIdOfReturns the key ID: the first 16 characters of the base64url of the SHA-256 of the public key.
interface PublicKey {
  kid: string
  publicKey: string // base64url of the 32 raw bytes
}
 
interface Signer extends PublicKey {
  sign: (message: string) => Promise<string> // base64url signature
}
 
interface PublicKeySet {
  get: (kid: string) => Promise<CryptoKey | null>
}

The package also gives the lower-level functions that these functions use: toBase64url, fromBase64url, importPublicKey, verifySignature, signJwt, verifyJwt, signerFor, deriveSecretKey, signMcpRequest, createSessionToken, verifyAppAssertion and unverifiedAssertionSubject.

@picked/app-kit/server

createAppHandler

createAppHandler(options: AppHandlerOptions): (request: Request) => Promise<Response>

createAppHandler returns a fetch handler for the endpoint of the manifest.

OptionTypeDefaultDescription
pickedKeysPublicKeySetrequiredThe public keys of Picked. Each signed request must verify with them.
basePathstring''The path that endpoint points to, for example /picked. The handler removes it from the path before it finds the route.
onInstall(event: InstallationCreatedEvent) => Promise<void> | voidnoneRuns for installation.created.
onUpgrade(event: InstallationUpgradedEvent) => Promise<void> | voidnoneRuns for installation.upgraded.
onUninstall(event: InstallationDeletedEvent) => Promise<void> | voidnoneRuns for installation.deleted.
onEvent(event: AppEvent) => Promise<void> | voidnoneRuns for each event that the manifest lists in events.
toolsRecord<string, (call: ToolCall) => Promise<Record<string, unknown>>>noneThe body of each workflow tool, by the name in the manifest. The function returns the output.
mcp{ path: string; handle: (request: Request, installation: InstallationRef) => Promise<Response> }nonepath is the path of mcp.url of the manifest, for example /mcp. The handler compares it with the full path of the request, with basePath. handle answers each MCP request after the handler verifies it.
manifestAppManifestnoneThe manifest. The handler answers GET /manifest.json with it.
fallback(request: Request) => Promise<Response> | ResponsenoneAnswers each other request, for example the pages of the app.
RequestAnswer
POST /lifecycleRuns onInstall, onUpgrade or onUninstall, then answers 200 with { "ok": true }. When the function throws an error, the handler throws it.
POST /eventsRuns onEvent, then answers 200 with { "ok": true }.
POST /tools/<name>Runs tools[name], then answers 200 with { "output": … }. When the function throws an error, it answers 422 with { "error": { "message": … } }.
POST /tools/<name> for an unknown tool404 with { "error": { "message": "Unknown tool <name>" } }. The body that is not a tool call gets the same answer.
Any method on the mcp option's pathVerifies the request, then calls mcp.handle.
A signed request that does not verify401 with { "error": "invalid_signature" }.
GET /manifest.json, with manifest200 with the manifest.
Each other requestfallback. Without fallback, 404 with { "error": "not_found" }.

The handler verifies the picked-signature header of each request to /lifecycle, /events, /tools/<name> and the path of the mcp option. It does not verify a request that goes to fallback. fallback gets the request without changes, with basePath in its path.

import { createAppHandler, readAppEnvironment } from '@picked/app-kit/server'
import { serve } from '@picked/app-kit/node'
 
const port = process.env.APP_PORT ?? '4103'
const { pickedKeys } = readAppEnvironment(process.env, port)
 
const handler = createAppHandler({
  pickedKeys,
  onInstall: (event) => {
    console.log(`Installed on ${event.projectId}; token scopes: ${event.scopes.join(', ')}`)
  },
  tools: {
    score_lead(call) {
      const email = typeof call.arguments.email === 'string' ? call.arguments.email : ''
      return Promise.resolve({ score: email.endsWith('.com') ? 60 : 30, tier: 'warm' })
    },
  },
})
 
serve(handler, Number(port))

Responses

json(body: unknown, status?: number): Response
page(html: string, options: { frameAncestors: string[] }): Response
FunctionDescription
jsonA JSON answer with Content-Type: application/json. status is 200 when you do not give it.
pageAn HTML answer with the headers Content-Security-Policy: frame-ancestors <origins>, Referrer-Policy: strict-origin and X-Content-Type-Options: nosniff. With an empty frameAncestors, the policy is frame-ancestors 'none'.

Session tokens

sessionTokenOf(request: Request): string | null
readSession(request: Request, pickedKeys: PublicKeySet): Promise<SessionClaims | null>
FunctionDescription
sessionTokenOfReturns the token in the Authorization: Bearer <token> header, or null. It does not verify the token.
readSessionVerifies the token in the Authorization: Bearer <token> header. It returns the fields of the token, or null.

A page of the app gets the session token from connect or keepConnected. See Session tokens.

Installation client

installationClientFor(
  ref: Pick<InstallationRef, 'apiUrl' | 'installationId' | 'token' | 'tokenExpiresAt'>,
  options: { privateKey: string; sessionToken?: string | null; fetch?: typeof fetch },
): InstallationClient
 
createInstallationClient(options: InstallationClientOptions): InstallationClient

An installation client calls the GraphQL API at <apiUrl>/api/graphql as one installation. The function installationClientFor makes a client from the installation in a request from Picked. It also makes a client from the fields of a session token.

InstallationClientOptionsTypeDescription
apiUrlstringThe origin of the Picked API, from apiUrl of the request.
installationIdstringThe installation.
privateKeystringThe private key of the app, as the base64 of its PKCS#8 DER, or as PKCS#8 PEM.
tokenstringAn installation token from a request from Picked.
tokenExpiresAtstringThe time at which token expires.
sessionTokenstringThe session token of the person on a page of the app.
fetchtypeof fetchThe fetch function that the client uses. The default is the global fetch.

The client uses token until 60 seconds before it expires. Then it gets a new token with appInstallationTokenCreate, and it sends a picked-app-assertion signed with privateKey. For an installation without offlineAccess, Picked gives a new token only with sessionToken. See Installation tokens.

interface InstallationClient {
  labels: InstallationLabels
  token: () => Promise<string>
  request: <Result, Variables extends Record<string, unknown>>(
    document: TadaDocumentNode<Result, Variables>,
    variables: Variables,
    options?: AdminApiRequestOptions,
  ) => Promise<Result>
}
MemberDescription
labelsThe labels of the installation. See Labels.
tokenReturns a token of the installation. The client sends it in the X-API-Key header.
requestSends a typed GraphQL document with the token. It returns data, with the type of the document.

The client sends each request with createAdminApiClient from @picked/admin-api-client. Make a document with graphql from that package. TadaDocumentNode and AdminApiRequestOptions are types of that package. options.timeoutMs sets the time limit of one request. The default is 30 seconds.

A request throws these errors:

ErrorWhen
AdminApiResponseErrorThe answer has GraphQL errors. The message has the message of each error, one on each line. codes has the code of each error.
AdminApiRateLimitErrorPicked refuses the request with a 429 status 4 times. The client waits about 1 second before it sends each retry.
ErrorThe request fails, it takes more than its time limit, or the answer has an HTTP error and no GraphQL errors.
import { graphql } from '@picked/admin-api-client'
import { installationClientFor } from '@picked/app-kit/server'
 
const RecentLeadsDocument = graphql(`
  query RecentLeads($projectId: ID!, $first: Int!) {
    project(input: { id: $projectId }) {
      leads(first: $first) {
        matchCount
      }
    }
  }
`)
 
const client = installationClientFor(event, { privateKey })
const data = await client.request(RecentLeadsDocument, { projectId: event.projectId, first: 10 })

Labels

interface InstallationLabels {
  list: () => Promise<AppLabel[]>
  get: (namespace: string, key: string) => Promise<AppLabel | undefined>
  set: (
    labels: readonly AppLabelInput[],
    options?: { atomic?: boolean },
  ) => Promise<{ labels: AppLabel[]; skipped: AppLabel[] }>
  delete: (labels: readonly AppLabelIdentifier[]) => Promise<string[]>
}
MemberDescription
listReturns each label of the installation that is not after its time of expiry. The values of secret labels are included.
getReturns one label, or undefined.
setMakes or replaces labels with labelsSet. skipped holds the labels that an onlyIfAbsent write did not change. The default of atomic is false.
deleteRemoves labels with labelsDelete. It returns the IDs of the removed labels.

set and delete throw LabelWriteError when Picked refuses a label.

AppLabelInputTypeDescription
namespacestring1 to 64 lowercase letters, digits, _ or -.
keystring1 to 64 lowercase letters, digits, _ or -.
type'text' | 'number' | 'boolean' | 'json'How to read the value.
valuestringThe value, as a string of the type. Not used with increment.
incrementnumberA number to add to a number label, in place of value.
expiresInnumberSeconds until the label expires, from 1 to 31536000.
onlyIfAbsentbooleanWrites the label only when no label with this namespace and key exists.
secretbooleanKeeps the value secret. Only a token of the installation reads it. Only for text or json, without increment or onlyIfAbsent.
AppLabelIdentifierTypeDescription
namespacestringThe namespace of the label.
keystringThe key of the label.
ifValuestringRemoves the label only when it holds this value.
interface AppLabel {
  namespace: string
  key: string
  type: 'text' | 'number' | 'boolean' | 'json'
  value: string
  secret: boolean
  expiresAt: string | null
  updatedAt: string
}
 
class LabelWriteError extends Error {
  readonly userErrors: readonly { field: string[]; message: string; code: string }[]
}

For the limits of an installation, see How to store data for an installation. For the rules of a label, see Labels.

await client.labels.set([
  { namespace: 'zoho', key: 'client_secret', type: 'text', value: clientSecret, secret: true },
])
const secret = await client.labels.get('zoho', 'client_secret')

installationLinkUrl

installationLinkUrl(link: {
  dashboardOrigin: string
  appId: string
  namespace: string
  key: string
  value: string
}): string

Returns <dashboardOrigin>/apps/<appId>/open?label=<namespace>.<key>&value=<value>. This dashboard URL opens the installation of the app that holds a label with that value. A secret label does not match.

ParameterDescription
dashboardOriginThe origin of the dashboard, for example https://dashboard.picked.app. The function ignores a path.
appIdThe app ID, for example app_k3v9x2m1q8zt. picked app deploy prints it. Each Picked environment has a different app ID.
namespaceThe namespace of a label that is not secret.
keyThe key of that label.
valueThe value of that label.

It throws TypeError in these conditions:

  • appId does not match ^app_[a-z0-9]+$. isAppId(value) returns true when value matches.
  • namespace or key does not match ^[a-z0-9_-]{1,64}$.
  • dashboardOrigin is not a URL.

On the server of the app, use readAppEnvironment. Give its appId and the first of its dashboardOrigins() to installationLinkUrl. When PICKED_APP_ID is not set, appId is null. Before Picked gives the dashboard origins, the list is empty:

import { installationLinkUrl, readAppEnvironment } from '@picked/app-kit/server'
 
const { dashboardOrigins, appId } = readAppEnvironment(process.env, '4103')
const [dashboardOrigin] = await dashboardOrigins()
if (dashboardOrigin !== undefined && appId !== null) {
  const url = installationLinkUrl({
    dashboardOrigin,
    appId,
    namespace: 'vercel',
    key: 'configuration_id',
    value: 'icfg_123',
  })
}

readAppEnvironment

readAppEnvironment(
  env: Record<string, string | undefined>,
  port: string,
  options?: { fetch?: typeof fetch; refreshAfterMs?: number; timeoutMs?: number },
): AppEnvironment
AppEnvironmentTypeValue
privateKeystringPICKED_APP_PRIVATE_KEY.
pickedUrlstringPICKED_API_URL, without a / at the end.
pickedKeysPublicKeySetA remoteKeySet for <pickedUrl>/.well-known/picked-app-keys.json.
publicUrlstringAPP_PUBLIC_URL, without a / at the end.
frameAncestorsstring[]The dashboard origins that PICKED_DASHBOARD_ORIGINS or DASHBOARD_PORT gives, as a list. Empty when the environment gives none.
dashboardOrigins() => Promise<string[]>frameAncestors, or the origins in <pickedUrl>/.well-known/picked-app-config.json when the environment gives none. Give it to page. Its first origin is the dashboard to give installationLinkUrl.
appIdstring | nullPICKED_APP_ID. null when it is not set, or when it is not an app ID.
ParameterValue
portThe port of the app on your computer.
options.fetchThe fetch that reads the public keys and the app config of Picked.
options.refreshAfterMsThe minimum time between two reads of the app config. The default is 5 minutes.
options.timeoutMsThe maximum time of one read of the app config. The default is 5 seconds.

See App environment variables for each variable, the values when a variable is not set, and the errors.

withRewrittenPath

withRewrittenPath(handler: (request: Request) => Promise<Response>): (request: Request) => Promise<Response>

On Vercel, a rewrite from /:path* to /api?__path=/:path* sends each path to one Vercel function. The function withRewrittenPath puts the path from __path back in the URL of the request, then calls handler. A request without __path goes to handler without changes.

{
  "rewrites": [{ "source": "/:path*", "destination": "/api?__path=/:path*" }]
}

api/index.ts:

import { withRewrittenPath } from '@picked/app-kit/server'
import { handler } from '../src/server.js'
 
export default { fetch: withRewrittenPath(handler) }

@picked/app-kit/oauth

These functions run the authorization code flow of OAuth for one installation. The flow completes only in the browser that started it.

startAuthorization(request: Request, options: StartAuthorizationOptions): Promise<Response>
finishAuthorization(request: Request, options: FinishAuthorizationOptions): Promise<Response>
oauthStartPage(): string
oauthCallbackPage(result: { ok: boolean; message: string }): string
 
const OAUTH_START_PATH = '/oauth/start'
const OAUTH_START_READY_MESSAGE = 'picked-app:oauth-start-ready'
const OAUTH_START_MESSAGE = 'picked-app:oauth-start'
const OAUTH_RESULT_MESSAGE = 'picked-app:oauth-result'

Steps of the flow

  1. authorizeInPopup opens a new window at GET /oauth/start, on the origin of the page.
  2. The window sends picked-app:oauth-start-ready to the page that opened it.
  3. The page sends { type: 'picked-app:oauth-start', sessionToken, params } to that window only.
  4. The window sends POST /oauth/start, with Authorization: Bearer <sessionToken> and params as the JSON body.
  5. startAuthorization verifies the session token and sets the OAuth cookie to a new unique value. It answers { "url": "<authorization URL>" }.
  6. The window goes to the authorization URL. The service sends it back to the callback.
  7. finishAuthorization compares the nonce in the state with the cookie. It then calls complete, and answers with the callback page.
  8. The callback page sends picked-app:oauth-result to the page that opened the window, and closes.

Each message goes to the origin of the app only. The window and the page accept a message only from that origin.

startAuthorization

Answers each request to OAUTH_START_PATH.

RequestAnswer
GETThe page of oauthStartPage.
POSTCalls authorize. For a URL, 200 with { "url": "<URL>" } and the OAuth cookie.
POST, refusedThe Response that authorize returns. It sets no cookie.
No session token401 with { "error": { "message": "Sign in again" } }. The token is not valid, or is expired.
Other methods405 with Allow: GET, POST.

The body of POST is the params of the page, as JSON. When the body is not JSON, params is null.

StartAuthorizationOptionsTypeDescription
privateKeystringThe private key of the app. It encrypts the state.
pickedKeysPublicKeySetThe public keys of Picked. They verify the session.
authorize(start: AuthorizationStart) => Promise<string | Response>Returns the authorization URL, or an error answer.
AuthorizationStartTypeDescription
sessionSessionClaimsThe verified session of the person in the dashboard.
sessionTokenstringThe session token. Give it to installationClientFor as sessionToken.
paramsunknownThe params of authorizeInPopup, or null.
state(connection: string) => Promise<string>Returns the state parameter for the installation of the session, with this connection.

An error answer goes to the page as the result. To give the person a message, answer { "error": { "message": "<text>" } }. Otherwise, the message is The app answered <status>.

finishAuthorization

Answers the callback of the service. Serve it at the callback address of your OAuth client.

FinishAuthorizationOptionsTypeDescription
privateKeystringThe private key of the app.
complete(callback: OAuthCallback) => Promise<{ ok: boolean; message: string }>Exchanges the code, and keeps the connection.
OAuthCallbackTypeDescription
stateOAuthStateThe state that startAuthorization made.
urlURLThe address of the callback, with the code or the error of the service.

finishAuthorization does not call complete in these conditions:

  • The state is not set, is not from the app, has changes, or is expired.
  • The request has no OAuth cookie, or the value of the cookie is not the nonce of the state.

Then the callback page shows This connection link has expired or was opened in another browser; start again. The cookie stays. Otherwise, finishAuthorization deletes the cookie, so that the callback completes one time. The callback page shows the ok and message of complete.

State

interface OAuthState {
  installationId: string
  apiUrl: string
  connection: string // which connection, for an app with more than one provider
  sessionToken: string
  exp: number // unix seconds
  nonce: string
}
FieldValue
installationIdThe installation of the session.
apiUrlThe Picked API of the installation.
connectionThe value that authorize gives to state, for example us.
sessionTokenThe session token of the person who started the flow.
expThe time of expiry: 600 seconds after startAuthorization.
nonceThe value of the OAuth cookie that startAuthorization set.

The state is encrypted with AES-GCM, with a key from the private key of the app. The service cannot read or change it.

Origin of the appNameAttributes
http: on localhost, 127.0.0.1 or [::1]picked-oauth-<port>Path=/; HttpOnly; SameSite=Lax
Other origins__Host-picked-oauthPath=/; HttpOnly; SameSite=Lax; Secure

The origin of the app comes from the Host header of the request, and from the X-Forwarded-Proto header that a proxy adds. Without these headers, it comes from the URL of the request. For example, serve behind an https: proxy sets __Host-picked-oauth.

The cookie expires after 600 seconds. It is for the host of /oauth/start only, so the callback must be on the same host. A browser holds one flow for each app at a time. A new start replaces the cookie of an earlier flow, and the earlier flow then fails.

Pages

FunctionDescription
oauthStartPageReturns the HTML that GET /oauth/start answers. Without a page that opened it, it shows Start connecting from the app’s page in Picked.
oauthCallbackPageReturns the HTML of the callback page. When the window has no page that opened it, the window stays open. It shows the message and You can close this window and return to Picked.

startAuthorization and finishAuthorization send their pages with Content-Security-Policy: frame-ancestors 'none', Cache-Control: no-store and Referrer-Policy: no-referrer.

@picked/app-kit/node

serve(handler: (request: Request) => Promise<Response>, port: number): Server
frameScript(): Promise<Response>
FunctionDescription
serveStarts a node:http server on port. It writes the method, the path and the status of each request to the console. When handler throws an error, the answer is 500.
frameScriptAnswers with the browser build of @picked/app-kit/frame, as text/javascript.

Serve frameScript() at a path of the app, for example /app-kit/frame.js. A page of the app then imports connect from that path:

if (pathname === '/app-kit/frame.js') return frameScript()

@picked/app-kit/frame

These functions run in a page that the dashboard shows in a slot. See Messages between the page and the dashboard.

connect

connect(options?: { dashboardOrigin?: string }): Promise<FrameContext>

Sends picked:ready to the dashboard. It returns the FrameContext that the dashboard sends back. connect works only in a page that the dashboard shows in an iframe. In a page that is not in an iframe, it returns an error.

It accepts a message only from the window that contains the iframe (window.parent), and only from dashboardOrigin. Without dashboardOrigin, it uses the origin of document.referrer, or the origin of the page when the referrer is empty. In the iframe, the referrer is the dashboard, because page lets only the dashboard origins show the page.

interface FrameContext {
  installationId: string
  organizationId: string
  organizationSlug: string
  projectId: string
  location: 'app-home' | 'workspace-prepublish-actions' | 'workspace-postpublish-actions'
  appVersion: number
  sessionToken: string
  theme: 'light' | 'dark'
}
<script type="module">
  import { connect, autoResize } from '/app-kit/frame.js'
  const context = await connect()
  autoResize()
  const response = await fetch('/api/leads', {
    headers: { authorization: 'Bearer ' + context.sessionToken },
  })
</script>

keepConnected

keepConnected(options?: { dashboardOrigin?: string }): Promise<FrameConnection>
 
interface FrameConnection {
  context: () => FrameContext
  stop: () => void
}

Calls connect with options, and returns when the dashboard sends the first FrameContext. Then it sends picked:ready again to get a new FrameContext. It sends it 2 minutes before the session token expires, and not more than 4 minutes after the last FrameContext. It reads the time of the expiry from the exp of the token. See Session tokens. When it cannot read exp, it sends picked:ready after 4 minutes.

keepConnected accepts a new FrameContext only from window.parent, and only from the origin that connect accepts.

After each FrameContext, keepConnected waits 1 minute or more before it sends picked:ready again. It compares the time now with the time to send every 15 seconds, and when the page becomes visible or active. For this reason, a computer that starts again after sleep mode gets a new session token in 15 seconds. If the dashboard does not send a FrameContext in 10 seconds, keepConnected sends picked:ready again after 15 seconds. Until a new FrameContext comes, context returns the last one.

FrameConnectionDescription
contextReturns the newest FrameContext from the dashboard.
stopStops the requests for a new FrameContext. context then returns the last one.

Use keepConnected on a page that stays open for longer than the session token. Read connection.context().sessionToken for each request, and for each authorizeInPopup. Then the request does not have an expired session token.

<script type="module">
  import { keepConnected } from '/app-kit/frame.js'
  const connection = await keepConnected()
  const leads = () =>
    fetch('/api/leads', {
      headers: { authorization: 'Bearer ' + connection.context().sessionToken },
    })
</script>

resize and autoResize

resize(height: number): void
autoResize(): () => void
FunctionDescription
resizeSends picked:resize with height, in pixels. It changes the value to the next integer above it.
autoResizeSends the height of the page now, and again after each change to the size of document.body. It returns a function that stops it.

authorizeInPopup

authorizeInPopup(request: { sessionToken: string; params?: unknown; connected?: () => Promise<string | null> }): Promise<{ ok: boolean; message: string }>

Opens a new window at /oauth/start on the origin of the page. When the window sends picked-app:oauth-start-ready, it sends the window sessionToken and params. It accepts messages only from that window, and only from the origin of the page. params goes to authorize on the server. See Steps of the flow. Call authorizeInPopup from a click handler. A browser can stop a new window that the page opens at a different time.

requestDescription
sessionTokenThe session token from keepConnected.
paramsA value for authorize, for example a region. The default is null.
connectedOptional. Reads the connection from your server. It returns the message to show when the connection exists, or null.
ResultWhen
{ ok, message } from the callback pageThe callback page sends picked-app:oauth-result.
{ ok: false, message: 'Allow pop-ups to connect' }The browser stops the new window.
{ ok: false, message: <error message> }POST /oauth/start answers with an error, for example Sign in again.
{ ok: false, message: 'The app answered <status>' }POST /oauth/start answers with an error that has no message, or with no URL.
{ ok: false, message: 'The app could not start connecting' }The window cannot send POST /oauth/start, or cannot read its answer.
{ ok: true, message: <message of connected> }The window closes without a result, and connected then returns a message.
{ ok: false, message: 'The connection window closed. If you finished connecting there, it shows here' }The window closes without a result, and the page is the active window. With connected, it also returns null for 30 seconds.

A service can separate the window from the page with a Cross-Origin-Opener-Policy header. Then the page cannot see the window, and reads it as closed. The person can continue in the window. The callback page stays open, and shows its result.

authorizeInPopup waits until the page is the active window again. Without connected, it then returns the result of a closed window. With connected, it calls connected one time each second, for 30 seconds, and returns when connected returns a message. Read the connection from the server after authorizeInPopup returns.

@picked/app-kit/testing

createFakePicked

createFakePicked(options: {
  appPrivateKey: string
  apiUrl?: string
  offlineAccess?: boolean
}): Promise<FakePicked>

A Picked API for the tests of one app. Give its fetch to the installation client. It answers the operations that the installation client sends: appInstallationTokenCreate, the labels of an installation, labelsSet and labelsDelete. It also publishes its public keys at /.well-known/picked-app-keys.json.

OptionDefaultDescription
appPrivateKeyrequiredThe private key of the app. The test API accepts a picked-app-assertion from its public key.
apiUrlhttps://api.picked.testThe origin of the test API.
offlineAccessfalseWhen true, each installation has offlineAccess.
FakePickedTypeDescription
apiUrlstringThe origin of the test API.
fetchtypeof fetchThe fetch function that sends requests to the test API.
pickedKeysPublicKeySetThe public keys of the test API. Give them to createAppHandler.
labelsMap<string, Map<string, AppLabel>>The labels, by installation ID, then by <namespace>.<key>.
received{ operationName: string; variables: Record<string, unknown> }[]Each GraphQL operation that the test API got, from first to last.
tokenFor(installationId) => Promise<{ token; expiresAt }>Makes an installation token.
installationRef(installationId, overrides?) => Promise<InstallationRef>An InstallationRef with a new token. The default organization is org and the default project is proj_1.
signedRequest(url, payload) => Promise<Request>A POST request that the test API signs, as Picked does.
mcpRequest(url, ref, payload) => Promise<Request>An MCP request that the test API signs, as Picked does.
sessionRequest(params: { ref; url; method?; body? }) => Promise<Request>A request from a page of the app, with a session token for the user user-test.

toolCall

toolCall(ref: InstallationRef, tool: string, args: Record<string, unknown>, test?: boolean): ToolCall

Makes a ToolCall body. With test: true, run.test is true.

import { generateKeyPair } from '@picked/app-kit'
import { createAppHandler } from '@picked/app-kit/server'
import { createFakePicked, toolCall } from '@picked/app-kit/testing'
 
const { privateKey } = await generateKeyPair()
const picked = await createFakePicked({ appPrivateKey: privateKey })
const handler = createAppHandler({
  pickedKeys: picked.pickedKeys,
  tools: { score_lead: async () => ({ score: 80, tier: 'hot' }) },
})
 
const ref = await picked.installationRef('appi_test')
const response = await handler(
  await picked.signedRequest(
    'https://app.test/tools/score_lead',
    toolCall(ref, 'score_lead', { email: 'ada@example.com' }),
  ),
)
console.log(response.status, await response.json())

oauthCookie

oauthCookie(response: Response): string

Returns the <name>=<value> of the cookie that a POST /oauth/start answer sets, or an empty string. Give it as the cookie header of a callback request in a test.

In this example, handler, picked and ref are from the example of toolCall. The fallback of handler sends /oauth/start and /oauth/callback to the OAuth functions.

const started = await handler(
  await picked.sessionRequest({
    ref,
    url: 'https://app.test/oauth/start',
    method: 'POST',
    body: { region: 'eu' },
  }),
)
const { url } = await started.json()
const state = new URL(url).searchParams.get('state') ?? ''
const callback = await handler(
  new Request(`https://app.test/oauth/callback?code=abc&state=${state}`, {
    headers: { cookie: oauthCookie(started) },
  }),
)

app-kit-copy-frame

app-kit-copy-frame <dir>

Copies the browser build of @picked/app-kit/frame to <dir>/app-kit/frame.js. Use it on a host that serves static files, for example the public directory of a Vercel project. Without <dir>, it writes Usage: app-kit-copy-frame <dir> and stops with status 1.