@parall/cli 1.80.0 → 1.82.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/dist/commands/apps-actions-sdk.generated.d.ts +1 -1
  2. package/dist/commands/apps-actions-sdk.generated.d.ts.map +1 -1
  3. package/dist/commands/apps-actions-sdk.generated.js +1 -1
  4. package/dist/commands/apps-actions.d.ts.map +1 -1
  5. package/dist/commands/apps-actions.js +13 -0
  6. package/dist/commands/apps-local-runner.generated.d.ts +1 -1
  7. package/dist/commands/apps-local-runner.generated.d.ts.map +1 -1
  8. package/dist/commands/apps-local-runner.generated.js +1 -1
  9. package/dist/commands/apps-template-catalog.d.ts +19 -23
  10. package/dist/commands/apps-template-catalog.d.ts.map +1 -1
  11. package/dist/commands/apps-template-catalog.gen.d.ts.map +1 -1
  12. package/dist/commands/apps-template-catalog.gen.js +158 -144
  13. package/dist/commands/apps-template-catalog.js +1 -1
  14. package/dist/commands/apps-template-init.d.ts.map +1 -1
  15. package/dist/commands/apps-template-init.js +6 -4
  16. package/dist/commands/apps-templates.gen.d.ts.map +1 -1
  17. package/dist/commands/apps-templates.gen.js +14 -16
  18. package/dist/commands/browser.js +2 -2
  19. package/dist/commands/clip-connection.d.ts.map +1 -1
  20. package/dist/commands/clip-connection.js +11 -11
  21. package/dist/commands/clip.d.ts +6 -0
  22. package/dist/commands/clip.d.ts.map +1 -1
  23. package/dist/commands/clip.js +57 -41
  24. package/dist/commands/messages-react.d.ts +15 -0
  25. package/dist/commands/messages-react.d.ts.map +1 -0
  26. package/dist/commands/messages-react.js +65 -0
  27. package/dist/commands/messages.d.ts.map +1 -1
  28. package/dist/commands/messages.js +2 -15
  29. package/dist/lib/connector-ref.d.ts +3 -0
  30. package/dist/lib/connector-ref.d.ts.map +1 -0
  31. package/dist/lib/connector-ref.js +2 -0
  32. package/dist/lib/publish-source.js +4 -4
  33. package/package.json +4 -4
@@ -1,2 +1,2 @@
1
- export declare const ACTIONS_SDK_SOURCE = "/**\n * @parall/miniapp-sdk/actions \u2014 the action side of a Mini App\n * (docs/engineering-design/mini-app-action-design.md \u00A72): `defineActions`\n * turns the author's functions into the module entry the action loader\n * calls; `ActionError` is the error whose message the caller may see.\n *\n * This file runs inside the Cloudflare isolate, not in the page. It is the\n * only part of the SDK that imports `cloudflare:workers`, and an action\n * module is built from it into one file whose sole external import is that\n * one. Export the result as `ActionRunner` \u2014 the loader looks it up by name:\n *\n * export const ActionRunner = defineActions({\n * async addNote(ctx, { text }) {\n * const { rows } = await ctx.db.exec(\n * 'INSERT INTO notes (text, created_by) VALUES ($1, $2) RETURNING id',\n * [text, ctx.viewer.id],\n * );\n * return rows[0];\n * },\n * });\n *\n * Security does not depend on this wrapper: the loader accepts only the two\n * result shapes run() returns, whatever produced them (design \u00A73.1).\n *\n * An action that declares `\"clip\": true` in the manifest (write actions only)\n * may call Clip as the person who called the action\n * (docs/engineering-design/mini-app-clip-design.md):\n *\n * const profile = await ctx.clip.exec('linkedin', 'get-profile', { id }, { connection: 'sales-li' });\n *\n * `ctx.fetch` requests a public HTTP(S) address and returns a standard\n * `Response` (docs/engineering-design/mini-app-network-design.md):\n *\n * const res = await ctx.fetch('https://api.example.com/v1/items');\n * if (!res.ok) throw new ActionError(`the items API answered ${res.status}`);\n * return res.json();\n *\n * `ctx.env` holds the app's secrets by name. Online they are the org shared\n * secrets an org owner or admin gave this app (org settings \u2192 \u5171\u4EAB\u5BC6\u94A5 \u2192\n * \u7ED9\u54EA\u4E9B app); a name the app was not given is undefined:\n *\n * const key = ctx.env.EXAMPLE_API_KEY;\n * if (!key) throw new ActionError('EXAMPLE_API_KEY is missing: an org owner or admin can give it to this app');\n * const res = await ctx.fetch('https://api.example.com/v1/items', { headers: { Authorization: `Bearer ${key}` } });\n */\n\nimport { WorkerEntrypoint } from 'cloudflare:workers';\n\n/** An error whose message reaches every caller as is (ACTION_FAILED with\n * error_kind action_error). Anything else thrown is an unexpected failure. */\nexport class ActionError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ActionError';\n }\n}\n\n/** A database call that was refused or failed. `code` is the platform's:\n * SQL_ERROR, SQL_REJECTED, ACTION_READ_ONLY, ACTION_LIMIT_EXCEEDED, \u2026 */\nexport class ActionDbError extends Error {\n readonly code: string;\n\n constructor(code: string, message: string) {\n super(message);\n this.name = 'ActionDbError';\n this.code = code;\n }\n}\n\n/** A Clip call that was refused or failed. `code` is the platform's \u2014 the\n * same codes the caller gets running `parall clip exec` themselves\n * (CONNECTION_NOT_ALLOWED, SCRIPT_ERROR, MCP_TOOL_FAILED, \u2026) \u2014 or the\n * action's own: CLIP_NOT_DECLARED, ACTION_LIMIT_EXCEEDED, ACTION_DEADLINE.\n * OUTCOME_UNKNOWN means the command may have run: never retry it blindly. */\nexport class ClipError extends Error {\n readonly code: string;\n\n constructor(code: string, message: string) {\n super(message);\n this.name = 'ClipError';\n this.code = code;\n }\n}\n\n/** An outbound request (ctx.fetch) that was refused or failed \u2014 an HTTP\n * error status is not one: it comes back as a Response. `code` is the\n * platform's:\n *\n * - not sent: ACTION_INVALID_CALL (the URL, method, headers or body),\n * NET_ADDRESS_BLOCKED (an IP address or a loopback name such as localhost\n * written in the URL, the platform's own hosts), ACTION_LIMIT_EXCEEDED\n * (too many requests, or one too large), ACTION_DEADLINE (too little time\n * left), NET_BUSY (the platform is busy; try again shortly),\n * NET_UNAVAILABLE, USER_DISABLED, ACTION_HANDLE_REVOKED;\n * - sent, so it may have reached the server: NET_TIMEOUT, NET_FAILED,\n * NET_RESPONSE_TOO_LARGE (answers are at most 1 MiB).\n *\n * A host name that resolves to a private or loopback address is not refused\n * here: Cloudflare's edge refuses it, and ctx.fetch returns an ordinary\n * Response with status 530 (body like \"error code: 1016\"), not a NetError;\n * the outbound record shows it as answered with HTTP 530.\n *\n * The platform never retries; send an idempotency key where the other side\n * supports one. */\nexport class NetError extends Error {\n readonly code: string;\n\n constructor(code: string, message: string) {\n super(message);\n this.name = 'NetError';\n this.code = code;\n }\n}\n\n/** The caller, as the platform vouches for it (design \u00A72.2). */\nexport interface ActionViewer {\n id: string;\n display_name: string;\n is_agent: boolean;\n /** Organization role: owner, admin or member. */\n role: string;\n}\n\nexport interface ActionApp {\n id: string;\n version_seq: number;\n}\n\n/** A row as an object keyed by column name, in select-list order. */\nexport type ActionRow = Record<string, unknown>;\n\nexport interface ActionQueryResult {\n rows: ActionRow[];\n truncated: boolean;\n}\n\nexport interface ActionStatementResult {\n rows: ActionRow[];\n rows_affected: number;\n truncated: boolean;\n}\n\nexport interface ActionExecResult extends ActionStatementResult {\n data_seq: number;\n}\n\nexport interface ActionBatchStatement {\n sql: string;\n params?: unknown[];\n}\n\nexport interface ActionBatchResult {\n results: ActionStatementResult[];\n data_seq: number;\n}\n\n/** ctx.db: one statement per query / exec; a batch is one transaction. */\nexport interface ActionDb {\n query(sql: string, params?: unknown[]): Promise<ActionQueryResult>;\n /** Write actions only. */\n exec(sql: string, params?: unknown[]): Promise<ActionExecResult>;\n /** Write actions only; at most 50 statements, counted as one call. */\n batch(statements: ActionBatchStatement[]): Promise<ActionBatchResult>;\n}\n\nexport interface ActionClipOptions {\n /** The connection to run on: its alias or ccn_ id. The caller must be\n * allowed to use it, exactly as for their own `parall clip exec`. */\n connection: string;\n profile?: string;\n /** The command's timeout; 30 s by default, cut to what the action's\n * deadline leaves. */\n timeoutMs?: number;\n}\n\n/** ctx.clip: Clip calls as the action's caller; actions that declare clip only. */\nexport interface ActionClip {\n /** Runs a command of a Clip (its name or crg_ id) and returns the Clip's\n * data; throws ClipError. */\n exec(clip: string, command: string, args: unknown, options: ActionClipOptions): Promise<unknown>;\n}\n\n/** ctx.fetch's options: the standard ones \u2014 method, headers, body, signal,\n * redirect \u2014 and the request's timeout. Others (cache, credentials, mode,\n * the Workers `cf`) are not looked at: every request is uncached and carries\n * only what the code sets. */\nexport interface ActionFetchInit extends RequestInit {\n /** This request's timeout; 30 s by default, cut to what the action's\n * deadline leaves. With redirects, each hop has it. */\n timeoutMs?: number;\n}\n\n/** ctx.fetch: a public HTTP(S) request from the platform, recorded in the\n * app's call record (host, method, status, size and time \u2014 never the query\n * string, headers or bodies). A local run (`parall app action run --local`,\n * `parall app dev`) sends it straight from your machine and records nothing.\n * Redirects are followed up to 5 times: within the same origin as Fetch\n * does; to another origin with only Accept, Accept-Language,\n * Content-Language and User-Agent kept, and not at all when the next request\n * would carry the body (307, 308, and 301 / 302 for a method other than GET,\n * HEAD or POST) or when it would go from https: to http: \u2014 then the redirect\n * itself comes back. Each hop is a request of its own and counts toward the\n * invocation's request limit (20 by default). At most 4 requests (by\n * default) run at once; more wait their turn. Request and answer bodies are\n * at most 1 MiB each. */\nexport type ActionFetch = (\n input: string | URL | Request,\n init?: ActionFetchInit,\n) => Promise<Response>;\n\nexport interface ActionContext {\n viewer: ActionViewer;\n app: ActionApp;\n db: ActionDb;\n clip: ActionClip;\n fetch: ActionFetch;\n /** The app's secrets by name; read-only. Online they are the org shared\n * secrets an org owner or admin gave this app; a local run (`parall app\n * action run --local`) reads the project's .dev.vars instead. Never pass\n * them as params or write them to the Database or a result. */\n env: Readonly<Record<string, string>>;\n}\n\n// biome-ignore lint/suspicious/noExplicitAny: the platform validates params against the declared schema before the call\nexport type ActionFunction = (ctx: ActionContext, params: any) => unknown;\n\n/** What the loader passes run() (ts/actions-worker src/run.ts). A loader\n * before the network sends neither env nor net_in_flight. */\nexport interface ActionRunRequest {\n action: string;\n params: unknown;\n viewer: ActionViewer;\n app: ActionApp;\n env?: Record<string, string>;\n /** How many requests the handle takes at once. */\n net_in_flight?: number;\n}\n\n/** The only two shapes the loader accepts back (ts/actions-worker src/outcome.ts). */\nexport type ActionRunResult =\n | { ok: true; json: string }\n | { ok: false; error: { kind: 'action_error' | 'unexpected'; message: string; stack?: string } };\n\n/** What a handle method resolves to. Failures travel as values because\n * Workers RPC keeps only an exception's name and message (design \u00A76). */\nexport type ActionHandleResult =\n | { ok: true; value: unknown }\n | { ok: false; error: { code: string; message: string } };\n\n/** What the handle's clip method takes. */\nexport interface ActionHandleClipRequest {\n clip: string;\n command: string;\n args?: unknown;\n connection: string;\n profile?: string;\n timeout_ms?: number;\n}\n\n/** What the handle's request method takes: one request, rebuilt by the\n * loader from exactly these fields. */\nexport interface ActionHandleNetRequest {\n url: string;\n method: string;\n headers: [string, string][];\n body: ArrayBuffer | null;\n timeout_ms?: number;\n}\n\n/** What it answers with on success: the answer, never followed. */\nexport interface ActionHandleNetAnswer {\n status: number;\n status_text: string;\n headers: [string, string][];\n body: ArrayBuffer | null;\n}\n\n/** The per-invocation handle the loader passes run(). A loader before Clip\n * calls has no clip method; one before the network has no request method. */\nexport interface ActionHandle {\n query(sql: string, params: unknown[]): Promise<ActionHandleResult>;\n exec(sql: string, params: unknown[]): Promise<ActionHandleResult>;\n batch(statements: ActionBatchStatement[]): Promise<ActionHandleResult>;\n clip?(req: ActionHandleClipRequest): Promise<ActionHandleResult>;\n request?(req: ActionHandleNetRequest): Promise<ActionHandleResult>;\n}\n\n/** What defineActions returns; export it as `ActionRunner`. */\nexport interface ActionRunnerClass {\n /** The actions the module implements, sorted; `parall app check` compares\n * them with the manifest. */\n readonly actions: readonly string[];\n new (\n ctx: unknown,\n env: unknown,\n ): { run(req: ActionRunRequest, handle: ActionHandle): Promise<ActionRunResult> };\n}\n\nfunction unwrap(result: ActionHandleResult): unknown {\n if (result?.ok === true) return result.value;\n if (result?.ok === false) throw new ActionDbError(result.error.code, result.error.message);\n throw new ActionDbError(\n 'ACTION_DB_UNAVAILABLE',\n 'the database handle answered in an unknown shape',\n );\n}\n\nfunction unwrapClip(result: ActionHandleResult): unknown {\n if (result?.ok === true) return result.value;\n if (result?.ok === false) throw new ClipError(result.error.code, result.error.message);\n throw new ClipError(\n 'OUTCOME_UNKNOWN',\n 'the Clip call answered in an unknown shape; it may or may not have run',\n );\n}\n\nfunction unwrapNet(result: ActionHandleResult): ActionHandleNetAnswer {\n if (result?.ok === false) throw new NetError(result.error.code, result.error.message);\n const a = (result?.ok === true ? result.value : null) as ActionHandleNetAnswer | null;\n if (\n !a ||\n typeof a.status !== 'number' ||\n !Array.isArray(a.headers) ||\n (a.body !== null && !(a.body instanceof ArrayBuffer))\n ) {\n throw new NetError(\n 'NET_FAILED',\n 'the request answered in an unknown shape; it may have reached the server',\n );\n }\n return a;\n}\n\n// Statuses whose Response has no body (Fetch's null body status).\nconst NULL_BODY_STATUS = new Set([101, 103, 204, 205, 304]);\nconst REDIRECT_STATUS = new Set([301, 302, 303, 307, 308]);\n// What a redirect to another origin keeps of the author's headers\n// (mini-app-network-design.md \u00A74): a key may be in any other one.\nconst CROSS_ORIGIN_HEADERS = new Set([\n 'accept',\n 'accept-language',\n 'content-language',\n 'user-agent',\n]);\n// Dropped with the body when a redirect turns the request into a GET.\nconst BODY_HEADERS = new Set([\n 'content-encoding',\n 'content-language',\n 'content-location',\n 'content-type',\n]);\nconst MAX_REDIRECTS = 5;\nconst DEFAULT_IN_FLIGHT = 4;\n\n/** One request of a ctx.fetch: the first, or a redirect's next hop. */\ninterface Hop {\n url: string;\n method: string;\n headers: [string, string][];\n body: ArrayBuffer | null;\n}\n\nfunction headerPairs(headers: Headers): [string, string][] {\n const out: [string, string][] = [];\n headers.forEach((value, name) => {\n out.push([name, value]);\n });\n return out;\n}\n\n/** The first hop, as a standard Request reads the input and init \u2014 only\n * the method, headers and body are taken from them. */\nasync function firstHop(input: string | URL | Request, init: ActionFetchInit | undefined) {\n let request: Request;\n try {\n request = new Request(input, {\n method: init?.method,\n headers: init?.headers,\n body: init?.body,\n });\n } catch (err) {\n throw new NetError(\n 'ACTION_INVALID_CALL',\n `ctx.fetch: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n const hop: Hop = {\n url: request.url,\n method: request.method,\n headers: headerPairs(request.headers),\n body: request.body ? await request.arrayBuffer() : null,\n };\n const fromInput = typeof input === 'object' && 'redirect' in input ? input.redirect : undefined;\n return {\n hop,\n redirect: (init?.redirect ?? fromInput ?? 'follow') as RequestRedirect,\n signal: init?.signal ?? (input instanceof Request ? input.signal : null),\n };\n}\n\n/** The next hop for a redirect, or null when it is not to be followed\n * (mini-app-network-design.md \u00A74). The handle checks the address of every\n * hop as it does the first: an IP address or loopback name in the Location,\n * or the platform, is refused there; a name that resolves to a private\n * address is left to Cloudflare's edge (status 530). */\nfunction nextHop(hop: Hop, status: number, location: string | undefined): Hop | null {\n if (!REDIRECT_STATUS.has(status) || location === undefined) return null;\n let from: URL;\n let to: URL;\n try {\n from = new URL(hop.url);\n to = new URL(location, hop.url);\n } catch {\n return null;\n }\n if (from.protocol === 'https:' && to.protocol === 'http:') return null;\n const sameOrigin = to.origin === from.origin && to.origin !== 'null';\n const toGet =\n (status === 303 && hop.method !== 'GET' && hop.method !== 'HEAD') ||\n ((status === 301 || status === 302) && hop.method === 'POST');\n if (!sameOrigin) {\n // The next request would carry the body to another origin.\n if (status === 307 || status === 308) return null;\n if ((status === 301 || status === 302) && !['GET', 'HEAD', 'POST'].includes(hop.method)) {\n return null;\n }\n }\n let { method, headers, body } = hop;\n if (toGet) {\n method = 'GET';\n body = null;\n headers = headers.filter(([name]) => !BODY_HEADERS.has(name.toLowerCase()));\n }\n if (!sameOrigin)\n headers = headers.filter(([name]) => CROSS_ORIGIN_HEADERS.has(name.toLowerCase()));\n return { url: to.href, method, headers, body };\n}\n\nfunction toResponse(answer: ActionHandleNetAnswer, hop: Hop, redirected: boolean): Response {\n if (answer.status < 200 || answer.status > 599) {\n throw new NetError('NET_FAILED', `the server answered with status ${answer.status}`);\n }\n // As Fetch does: no body for a HEAD request or a null body status.\n const body = hop.method === 'HEAD' || NULL_BODY_STATUS.has(answer.status) ? null : answer.body;\n let res: Response;\n try {\n res = new Response(body, {\n status: answer.status,\n statusText: answer.status_text,\n headers: answer.headers,\n });\n } catch {\n try {\n res = new Response(body, { status: answer.status, headers: answer.headers });\n } catch {\n throw new NetError('NET_FAILED', 'the answer could not be read');\n }\n }\n // As a fetch Response: the URL that answered, and whether it was reached\n // through a redirect.\n Object.defineProperty(res, 'url', { value: hop.url });\n if (redirected) Object.defineProperty(res, 'redirected', { value: true });\n return res;\n}\n\n/** p, or the signal's reason as soon as it aborts. A request already at\n * the handle runs on, and the loader waits for it before answering; one\n * still waiting for its turn is never sent. */\nfunction abortable<T>(p: Promise<T>, signal: AbortSignal | null | undefined): Promise<T> {\n if (!signal) return p;\n if (signal.aborted) return Promise.reject(signal.reason);\n return new Promise<T>((resolve, reject) => {\n const onAbort = () => reject(signal.reason);\n signal.addEventListener('abort', onAbort, { once: true });\n p.then(\n (v) => {\n signal.removeEventListener('abort', onAbort);\n resolve(v);\n },\n (e) => {\n signal.removeEventListener('abort', onAbort);\n reject(e);\n },\n );\n });\n}\n\n/** ctx.env: the secrets as a frozen object of strings. */\nfunction envOf(raw: unknown): Readonly<Record<string, string>> {\n const entries =\n raw && typeof raw === 'object' && !Array.isArray(raw)\n ? Object.entries(raw).filter((e): e is [string, string] => typeof e[1] === 'string')\n : [];\n return Object.freeze(Object.fromEntries(entries));\n}\n\nfunction failure(err: unknown): ActionRunResult {\n if (err instanceof ActionError || (err instanceof Error && err.name === 'ActionError')) {\n return { ok: false, error: { kind: 'action_error', message: err.message } };\n }\n const e = err instanceof Error ? err : new Error(String(err));\n const label =\n e instanceof ActionDbError || e instanceof ClipError || e instanceof NetError\n ? `${e.name} ${e.code}`\n : e.name;\n return {\n ok: false,\n error: { kind: 'unexpected', message: `${label}: ${e.message}`, stack: e.stack ?? '' },\n };\n}\n\n/** A database call as the author's code holds it. It notes whether the code\n * attached a rejection handler anywhere along its chain \u2014 `await`,\n * `try`/`catch`, `.catch()`, `.then(f).catch(g)`, `Promise.all` all do \u2014 so\n * a failure nobody looked at fails the action instead of being lost.\n * Promises derived from a call point back to it. */\nclass DbCall<T> extends Promise<T> {\n handled = false;\n origin?: DbCall<unknown>;\n #inFinally = false;\n\n override then<R1 = T, R2 = never>(\n onFulfilled?: ((value: T) => R1 | PromiseLike<R1>) | null,\n onRejected?: ((reason: unknown) => R2 | PromiseLike<R2>) | null,\n ): Promise<R1 | R2> {\n const origin = this.origin ?? this;\n if (typeof onRejected === 'function' && !this.#inFinally) origin.handled = true;\n const derived = super.then(onFulfilled, onRejected) as DbCall<R1 | R2>;\n derived.origin = origin;\n return derived;\n }\n\n // finally() calls then() with a rejection handler that throws the failure\n // on: it handles nothing. A catch on what it returns still counts.\n override finally(onFinally?: (() => void) | null): Promise<T> {\n this.#inFinally = true;\n try {\n return super.finally(onFinally);\n } finally {\n this.#inFinally = false;\n }\n }\n}\n\n// The wrapper's own bookkeeping on a DbCall, which must not count as the\n// author handling it.\nconst observe = Promise.prototype.then as <T>(\n this: Promise<T>,\n onFulfilled: (value: T) => unknown,\n onRejected?: (reason: unknown) => unknown,\n) => Promise<unknown>;\n\n/** Wraps the author's functions into the module entry the loader calls. */\nexport function defineActions(actions: Record<string, ActionFunction>): ActionRunnerClass {\n const names = Object.keys(actions).sort();\n // Not named ActionRunner: the author's export usually is, and a bundler\n // would rename this class to tell the two apart.\n class ActionEntrypoint extends WorkerEntrypoint {\n static readonly actions: readonly string[] = names;\n\n async run(req: ActionRunRequest, handle: ActionHandle): Promise<ActionRunResult> {\n // Database calls still in flight are waited for before answering \u2014 a\n // write the author forgot to await commits before the caller has the\n // result. Calls started from a finishing call are waited for too; the\n // loader refuses any that arrive after run() returns.\n const pending = new Set<Promise<unknown>>();\n const failed = new Map<DbCall<unknown>, unknown>();\n const track = <T>(\n call: Promise<ActionHandleResult>,\n open: (result: ActionHandleResult) => unknown = unwrap,\n ): Promise<T> => {\n const dbCall = new DbCall<T>((resolve, reject) => {\n call.then(open).then(resolve as (value: unknown) => void, reject);\n });\n const settled = observe.call(\n dbCall,\n () => undefined,\n (err) => {\n failed.set(dbCall, err);\n },\n );\n pending.add(settled);\n observe.call(settled, () => pending.delete(settled));\n return dbCall;\n };\n const drain = async () => {\n while (pending.size > 0) await Promise.allSettled([...pending]);\n };\n const db: ActionDb = {\n query: (sql, params = []) => track(handle.query(sql, params)),\n exec: (sql, params = []) => track(handle.exec(sql, params)),\n batch: (statements) => track(handle.batch(statements)),\n };\n // Clip calls are tracked like database calls: waited for before the\n // answer, and a failure nobody looked at fails the action.\n const clip: ActionClip = {\n exec: (clipName, command, args, options) => {\n const request: ActionHandleClipRequest = {\n clip: clipName,\n command,\n args,\n connection: options?.connection,\n profile: options?.profile,\n timeout_ms: options?.timeoutMs,\n };\n const sent =\n typeof handle.clip === 'function'\n ? handle.clip(request)\n : Promise.resolve<ActionHandleResult>({\n ok: false,\n error: { code: 'CLIP_UNAVAILABLE', message: 'this runtime cannot call Clip yet' },\n });\n return track(sent, unwrapClip);\n },\n };\n // Outbound requests: one handle call per hop, at most net_in_flight at\n // once (more wait their turn), tracked like database calls.\n const limit = Math.max(1, req.net_in_flight || DEFAULT_IN_FLIGHT);\n let active = 0;\n const waiting: (() => void)[] = [];\n const send = async (hop: Hop, timeoutMs: number | undefined, signal: AbortSignal | null) => {\n while (active >= limit) await new Promise<void>((resume) => waiting.push(resume));\n active++;\n try {\n // Aborted while it waited for its turn (the code has already had\n // the abort): it is never sent, and the turn passes on.\n if (signal?.aborted) throw signal.reason;\n if (typeof handle.request !== 'function') {\n throw new NetError('NET_UNAVAILABLE', 'this runtime cannot make requests yet');\n }\n return unwrapNet(\n await handle.request({\n ...hop,\n ...(timeoutMs === undefined ? {} : { timeout_ms: timeoutMs }),\n }),\n );\n } finally {\n active--;\n waiting.shift()?.();\n }\n };\n const request = async (input: string | URL | Request, init?: ActionFetchInit) => {\n const first = await firstHop(input, init);\n const { redirect, signal } = first;\n let hop = first.hop;\n for (let followed = 0; ; followed++) {\n // Aborted before this hop: it is never asked for.\n if (signal?.aborted) throw signal.reason;\n const answer = await abortable(send(hop, init?.timeoutMs, signal), signal);\n if (redirect !== 'manual' && REDIRECT_STATUS.has(answer.status)) {\n if (redirect === 'error') {\n throw new NetError(\n 'NET_FAILED',\n `the server redirected (${answer.status}) and redirect is \"error\"`,\n );\n }\n const location = answer.headers.find(\n ([name]) => name.toLowerCase() === 'location',\n )?.[1];\n const next = nextHop(hop, answer.status, location);\n if (next) {\n if (followed >= MAX_REDIRECTS) {\n throw new NetError(\n 'ACTION_LIMIT_EXCEEDED',\n `ctx.fetch follows at most ${MAX_REDIRECTS} redirects`,\n );\n }\n hop = next;\n continue;\n }\n }\n return toResponse(answer, hop, followed > 0);\n }\n };\n const ctxFetch: ActionFetch = (input, init) =>\n track<Response>(\n request(input, init).then((res) => ({ ok: true, value: res }) as ActionHandleResult),\n (result) => (result as { value: unknown }).value,\n );\n const env = envOf(req.env);\n try {\n const fn = Object.hasOwn(actions, req.action) ? actions[req.action] : undefined;\n if (typeof fn !== 'function') {\n throw new Error(\n `this module does not implement the action ${JSON.stringify(req.action)}`,\n );\n }\n const value = await fn(\n { viewer: req.viewer, app: req.app, db, clip, fetch: ctxFetch, env },\n req.params,\n );\n await drain();\n // A call that failed while the code never looked at it (a forgotten\n // await) fails the action: answering ok would claim a write that did\n // not happen.\n for (const [dbCall, err] of failed) if (!dbCall.handled) throw err;\n const json = JSON.stringify(value === undefined ? null : value);\n if (typeof json !== 'string') {\n throw new TypeError('the action returned a value JSON cannot represent');\n }\n return { ok: true, json };\n } catch (err) {\n await drain();\n return failure(err);\n }\n }\n }\n return ActionEntrypoint;\n}\n";
1
+ export declare const ACTIONS_SDK_SOURCE = "/**\n * @parall/miniapp-sdk/actions \u2014 the action side of a Mini App\n * (docs/engineering-design/mini-app-action-design.md \u00A72): `defineActions`\n * turns the author's functions into the module entry the action loader\n * calls; `ActionError` is the error whose message the caller may see.\n *\n * This file runs inside the Cloudflare isolate, not in the page. It is the\n * only part of the SDK that imports `cloudflare:workers`, and an action\n * module is built from it into one file whose sole external import is that\n * one. Export the result as `ActionRunner` \u2014 the loader looks it up by name:\n *\n * export const ActionRunner = defineActions({\n * async addNote(ctx, { text }) {\n * const { rows } = await ctx.db.exec(\n * 'INSERT INTO notes (text, created_by) VALUES ($1, $2) RETURNING id',\n * [text, ctx.viewer.id],\n * );\n * return rows[0];\n * },\n * });\n *\n * Security does not depend on this wrapper: the loader accepts only the two\n * result shapes run() returns, whatever produced them (design \u00A73.1).\n *\n * An action that declares `\"clip\": true` in the manifest (write actions only)\n * may call connectors as the person who called the action\n * (docs/engineering-design/mini-app-clip-design.md):\n *\n * const profile = await ctx.clip.exec('linkedin', 'get-profile', { id }, { connection: 'sales-li' });\n *\n * `ctx.fetch` requests a public HTTP(S) address and returns a standard\n * `Response` (docs/engineering-design/mini-app-network-design.md):\n *\n * const res = await ctx.fetch('https://api.example.com/v1/items');\n * if (!res.ok) throw new ActionError(`the items API answered ${res.status}`);\n * return res.json();\n *\n * `ctx.env` holds the app's secrets by name. Online they are the org shared\n * secrets an org owner or admin gave this app (org settings \u2192 \u5171\u4EAB\u5BC6\u94A5 \u2192\n * \u7ED9\u54EA\u4E9B app); a name the app was not given is undefined:\n *\n * const key = ctx.env.EXAMPLE_API_KEY;\n * if (!key) throw new ActionError('EXAMPLE_API_KEY is missing: an org owner or admin can give it to this app');\n * const res = await ctx.fetch('https://api.example.com/v1/items', { headers: { Authorization: `Bearer ${key}` } });\n *\n * `ctx.parall.get(refs)` reads Parall files, tasks and members by reference\n * and `ctx.parall.members()` lists the members, as the caller and read-only\n * (ActionParall below).\n */\n\nimport { WorkerEntrypoint } from 'cloudflare:workers';\n\n/** An error whose message reaches every caller as is (ACTION_FAILED with\n * error_kind action_error). Anything else thrown is an unexpected failure. */\nexport class ActionError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ActionError';\n }\n}\n\n/** An error that carries the platform's `code`: what ActionDbError,\n * ClipError, NetError and ParallError have in common. */\nexport class CodedError extends Error {\n readonly code: string;\n\n constructor(code: string, message: string) {\n super(message);\n this.code = code;\n }\n}\n\n/** A database call that was refused or failed. `code` is the platform's:\n * SQL_ERROR, SQL_REJECTED, ACTION_READ_ONLY, ACTION_LIMIT_EXCEEDED, \u2026 */\nexport class ActionDbError extends CodedError {\n override name = 'ActionDbError';\n}\n\n/** A connector call that was refused or failed. `code` is the platform's \u2014 the\n * same codes the caller gets running `parall connector exec` themselves\n * (CONNECTION_NOT_ALLOWED, SCRIPT_ERROR, MCP_TOOL_FAILED, \u2026) \u2014 or the\n * action's own: CLIP_NOT_DECLARED, ACTION_LIMIT_EXCEEDED, ACTION_DEADLINE.\n * OUTCOME_UNKNOWN means the command may have run: never retry it blindly. */\nexport class ClipError extends CodedError {\n override name = 'ClipError';\n}\n\n/** An outbound request (ctx.fetch) that was refused or failed \u2014 an HTTP\n * error status is not one: it comes back as a Response. `code` is the\n * platform's:\n *\n * - not sent: ACTION_INVALID_CALL (the URL, method, headers or body),\n * NET_ADDRESS_BLOCKED (an IP address or a loopback name such as localhost\n * written in the URL, the platform's own hosts), ACTION_LIMIT_EXCEEDED\n * (too many requests, or one too large), ACTION_DEADLINE (too little time\n * left), NET_BUSY (the platform is busy; try again shortly),\n * NET_UNAVAILABLE, USER_DISABLED, ACTION_HANDLE_REVOKED;\n * - sent, so it may have reached the server: NET_TIMEOUT, NET_FAILED,\n * NET_RESPONSE_TOO_LARGE (answers are at most 1 MiB).\n *\n * A host name that resolves to a private or loopback address is not refused\n * here: Cloudflare's edge refuses it, and ctx.fetch returns an ordinary\n * Response with status 530 (body like \"error code: 1016\"), not a NetError;\n * the outbound record shows it as answered with HTTP 530.\n *\n * The platform never retries; send an idempotency key where the other side\n * supports one. */\nexport class NetError extends CodedError {\n override name = 'NetError';\n}\n\n/** A ctx.parall.get or members() refused as a whole (an item a get cannot read\n * is in its result instead): ACTION_INVALID_CALL (refs not 1 to 100 strings),\n * ACTION_LIMIT_EXCEEDED, ACTION_DEADLINE, ACTION_HANDLE_REVOKED, USER_DISABLED,\n * ORG_FORBIDDEN (left the org), TOO_LARGE (the members past 1 MiB: read them\n * by reference), PARALL_READ_UNAVAILABLE (off or lost: retry). */\nexport class ParallError extends CodedError {\n override name = 'ParallError';\n}\n\n/** The caller, as the platform vouches for it (design \u00A72.2). */\nexport interface ActionViewer {\n id: string;\n display_name: string;\n is_agent: boolean;\n /** Organization role: owner, admin or member. */\n role: string;\n}\n\nexport interface ActionApp {\n id: string;\n version_seq: number;\n}\n\n/** A row as an object keyed by column name, in select-list order. */\nexport type ActionRow = Record<string, unknown>;\n\nexport interface ActionQueryResult {\n rows: ActionRow[];\n truncated: boolean;\n}\n\nexport interface ActionStatementResult {\n rows: ActionRow[];\n rows_affected: number;\n truncated: boolean;\n}\n\nexport interface ActionExecResult extends ActionStatementResult {\n data_seq: number;\n}\n\nexport interface ActionBatchStatement {\n sql: string;\n params?: unknown[];\n}\n\nexport interface ActionBatchResult {\n results: ActionStatementResult[];\n data_seq: number;\n}\n\n/** ctx.db: one statement per query / exec; a batch is one transaction. */\nexport interface ActionDb {\n query(sql: string, params?: unknown[]): Promise<ActionQueryResult>;\n /** Write actions only. */\n exec(sql: string, params?: unknown[]): Promise<ActionExecResult>;\n /** Write actions only; at most 50 statements, counted as one call. */\n batch(statements: ActionBatchStatement[]): Promise<ActionBatchResult>;\n}\n\nexport interface ActionClipOptions {\n /** The connection to run on: its alias or ccn_ id. The caller must be\n * allowed to use it, exactly as for their own `parall connector exec`. */\n connection: string;\n profile?: string;\n /** The command's timeout; 30 s by default, cut to what the action's\n * deadline leaves. */\n timeoutMs?: number;\n}\n\n/** ctx.clip: connector calls as the action's caller; actions that declare clip only. */\nexport interface ActionClip {\n /** Runs a command of a connector (its name or crg_ id) and returns the connector's\n * data; throws ClipError. */\n exec(clip: string, command: string, args: unknown, options: ActionClipOptions): Promise<unknown>;\n}\n\n/** A file (a chat attachment): no link, no uploader; width and height for images. */\nexport interface ParallFile {\n id: string;\n file_name: string;\n mime_type: string;\n file_size: number;\n width?: number;\n height?: number;\n}\n\n/** A task: due_date is YYYY-MM-DD or null; archived_at once it is archived. */\nexport interface ParallTask {\n id: string;\n identifier?: string;\n title: string;\n status: string;\n priority: string;\n assignee_id?: string;\n project_id?: string;\n due_date: string | null;\n created_at: string;\n updated_at: string;\n archived_at?: string;\n}\n\n/** An active member of the app's organization, person or agent; no email. */\nexport interface ParallMember {\n user_id: string;\n display_name: string;\n avatar_url?: string;\n type: 'human' | 'agent';\n role: string;\n title: string;\n joined_at: string;\n}\n\n/** One reference's answer; a refusal carries only its code: RESTRICTED (the\n * caller may not read it), NOT_FOUND (not in the app's organization: deleted,\n * another organization's, a member who left), INVALID_REF (not an att_, tsk_\n * or usr_ reference) or TOO_LARGE (past the get's 1 MiB). Others: unreadable. */\nexport type ParallItem =\n | { ok: true; type: 'file'; item: ParallFile }\n | { ok: true; type: 'task'; item: ParallTask }\n | { ok: true; type: 'member'; item: ParallMember }\n | { ok: false; code: string };\n\nexport interface ActionParall {\n /** Reads up to 100 references (prll://att_\u2026, tsk_\u2026, usr_\u2026 or bare IDs), one\n * item each in order, as the caller's own read now; read-only. The result\n * is the caller's view: store references, never the result across\n * invocations or in page storage. 20 gets per invocation, 10 s each. */\n get(refs: readonly string[]): Promise<ParallItem[]>;\n /** Every active member of the organization, people and agents, with a\n * get's member fields, in the order they joined; counts as one get. */\n members(): Promise<ParallMember[]>;\n}\n\n/** ctx.fetch's options: the standard ones \u2014 method, headers, body, signal,\n * redirect \u2014 and the request's timeout. Others (cache, credentials, mode,\n * the Workers `cf`) are not looked at: every request is uncached and carries\n * only what the code sets. */\nexport interface ActionFetchInit extends RequestInit {\n /** This request's timeout; 30 s by default, cut to what the action's\n * deadline leaves. With redirects, each hop has it. */\n timeoutMs?: number;\n}\n\n/** ctx.fetch: a public HTTP(S) request from the platform, recorded in the\n * app's call record (host, method, status, size and time \u2014 never the query\n * string, headers or bodies). A local run (`parall app action run --local`,\n * `parall app dev`) sends it straight from your machine and records nothing.\n * Redirects are followed up to 5 times: within the same origin as Fetch\n * does; to another origin with only Accept, Accept-Language,\n * Content-Language and User-Agent kept, and not at all when the next request\n * would carry the body (307, 308, and 301 / 302 for a method other than GET,\n * HEAD or POST) or when it would go from https: to http: \u2014 then the redirect\n * itself comes back. Each hop is a request of its own and counts toward the\n * invocation's request limit (20 by default). At most 4 requests (by\n * default) run at once; more wait their turn. Request and answer bodies are\n * at most 1 MiB each. */\nexport type ActionFetch = (\n input: string | URL | Request,\n init?: ActionFetchInit,\n) => Promise<Response>;\n\nexport interface ActionContext {\n viewer: ActionViewer;\n app: ActionApp;\n db: ActionDb;\n clip: ActionClip;\n fetch: ActionFetch;\n parall: ActionParall;\n /** The app's secrets by name; read-only. Online they are the org shared\n * secrets an org owner or admin gave this app; a local run (`parall app\n * action run --local`) reads the project's .dev.vars instead. Never pass\n * them as params or write them to the Database or a result. */\n env: Readonly<Record<string, string>>;\n}\n\n// biome-ignore lint/suspicious/noExplicitAny: the platform validates params against the declared schema before the call\nexport type ActionFunction = (ctx: ActionContext, params: any) => unknown;\n\n/** What the loader passes run() (ts/actions-worker src/run.ts). A loader\n * before the network sends neither env nor net_in_flight. */\nexport interface ActionRunRequest {\n action: string;\n params: unknown;\n viewer: ActionViewer;\n app: ActionApp;\n env?: Record<string, string>;\n /** How many requests the handle takes at once. */\n net_in_flight?: number;\n}\n\n/** The only two shapes the loader accepts back (ts/actions-worker src/outcome.ts). */\nexport type ActionRunResult =\n | { ok: true; json: string }\n | { ok: false; error: { kind: 'action_error' | 'unexpected'; message: string; stack?: string } };\n\n/** What a handle method resolves to. Failures travel as values because\n * Workers RPC keeps only an exception's name and message (design \u00A76). */\nexport type ActionHandleResult =\n | { ok: true; value: unknown }\n | { ok: false; error: { code: string; message: string } };\n\n/** What the handle's clip method takes. */\nexport interface ActionHandleClipRequest {\n clip: string;\n command: string;\n args?: unknown;\n connection: string;\n profile?: string;\n timeout_ms?: number;\n}\n\n/** What the handle's request method takes: one request, rebuilt by the\n * loader from exactly these fields. */\nexport interface ActionHandleNetRequest {\n url: string;\n method: string;\n headers: [string, string][];\n body: ArrayBuffer | null;\n timeout_ms?: number;\n}\n\n/** What it answers with on success: the answer, never followed. */\nexport interface ActionHandleNetAnswer {\n status: number;\n status_text: string;\n headers: [string, string][];\n body: ArrayBuffer | null;\n}\n\n/** The per-invocation handle the loader passes run(). Loaders older than Clip\n * calls, the network, Parall reads or the member list lack clip, request,\n * parall or parallMembers. */\nexport interface ActionHandle {\n query(sql: string, params: unknown[]): Promise<ActionHandleResult>;\n exec(sql: string, params: unknown[]): Promise<ActionHandleResult>;\n batch(statements: ActionBatchStatement[]): Promise<ActionHandleResult>;\n clip?(req: ActionHandleClipRequest): Promise<ActionHandleResult>;\n request?(req: ActionHandleNetRequest): Promise<ActionHandleResult>;\n parall?(req: { refs: string[] }): Promise<ActionHandleResult>;\n parallMembers?(): Promise<ActionHandleResult>;\n}\n\n/** What defineActions returns; export it as `ActionRunner`. */\nexport interface ActionRunnerClass {\n /** The actions the module implements, sorted; `parall app check` compares\n * them with the manifest. */\n readonly actions: readonly string[];\n new (\n ctx: unknown,\n env: unknown,\n ): { run(req: ActionRunRequest, handle: ActionHandle): Promise<ActionRunResult> };\n}\n\nfunction unwrap(result: ActionHandleResult): unknown {\n if (result?.ok === true) return result.value;\n if (result?.ok === false) throw new ActionDbError(result.error.code, result.error.message);\n throw new ActionDbError(\n 'ACTION_DB_UNAVAILABLE',\n 'the database handle answered in an unknown shape',\n );\n}\n\nfunction unwrapClip(result: ActionHandleResult): unknown {\n if (result?.ok === true) return result.value;\n if (result?.ok === false) throw new ClipError(result.error.code, result.error.message);\n throw new ClipError(\n 'OUTCOME_UNKNOWN',\n 'the connector call answered in an unknown shape; it may or may not have run',\n );\n}\n\nfunction unwrapParall(result: ActionHandleResult): unknown[] {\n if (result?.ok === false) throw new ParallError(result.error.code, result.error.message);\n if (result?.ok === true && Array.isArray(result.value)) return result.value;\n throw new ParallError('PARALL_READ_UNAVAILABLE', 'the read answered in an unknown shape');\n}\n\n/** One read (the handle checks it). Over RPC the handle is a stub that takes\n * any name for a method, so a loader without this one refuses the call. */\nasync function readParall(read: () => Promise<ActionHandleResult>): Promise<ActionHandleResult> {\n try {\n return await read();\n } catch {\n const message = 'this runtime cannot read Parall data yet';\n return { ok: false, error: { code: 'PARALL_READ_UNAVAILABLE', message } };\n }\n}\n\nfunction unwrapNet(result: ActionHandleResult): ActionHandleNetAnswer {\n if (result?.ok === false) throw new NetError(result.error.code, result.error.message);\n const a = (result?.ok === true ? result.value : null) as ActionHandleNetAnswer | null;\n if (\n !a ||\n typeof a.status !== 'number' ||\n !Array.isArray(a.headers) ||\n (a.body !== null && !(a.body instanceof ArrayBuffer))\n ) {\n throw new NetError(\n 'NET_FAILED',\n 'the request answered in an unknown shape; it may have reached the server',\n );\n }\n return a;\n}\n\n// Statuses whose Response has no body (Fetch's null body status).\nconst NULL_BODY_STATUS = new Set([101, 103, 204, 205, 304]);\nconst REDIRECT_STATUS = new Set([301, 302, 303, 307, 308]);\n// What a redirect to another origin keeps of the author's headers\n// (mini-app-network-design.md \u00A74): a key may be in any other one.\nconst CROSS_ORIGIN_HEADERS = new Set([\n 'accept',\n 'accept-language',\n 'content-language',\n 'user-agent',\n]);\n// Dropped with the body when a redirect turns the request into a GET.\nconst BODY_HEADERS = new Set([\n 'content-encoding',\n 'content-language',\n 'content-location',\n 'content-type',\n]);\nconst MAX_REDIRECTS = 5;\nconst DEFAULT_IN_FLIGHT = 4;\n\n/** One request of a ctx.fetch: the first, or a redirect's next hop. */\ninterface Hop {\n url: string;\n method: string;\n headers: [string, string][];\n body: ArrayBuffer | null;\n}\n\nfunction headerPairs(headers: Headers): [string, string][] {\n const out: [string, string][] = [];\n headers.forEach((value, name) => {\n out.push([name, value]);\n });\n return out;\n}\n\n/** The first hop, as a standard Request reads the input and init \u2014 only\n * the method, headers and body are taken from them. */\nasync function firstHop(input: string | URL | Request, init: ActionFetchInit | undefined) {\n let request: Request;\n try {\n request = new Request(input, {\n method: init?.method,\n headers: init?.headers,\n body: init?.body,\n });\n } catch (err) {\n throw new NetError(\n 'ACTION_INVALID_CALL',\n `ctx.fetch: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n const hop: Hop = {\n url: request.url,\n method: request.method,\n headers: headerPairs(request.headers),\n body: request.body ? await request.arrayBuffer() : null,\n };\n const fromInput = typeof input === 'object' && 'redirect' in input ? input.redirect : undefined;\n return {\n hop,\n redirect: (init?.redirect ?? fromInput ?? 'follow') as RequestRedirect,\n signal: init?.signal ?? (input instanceof Request ? input.signal : null),\n };\n}\n\n/** The next hop for a redirect, or null when it is not to be followed\n * (mini-app-network-design.md \u00A74). The handle checks the address of every\n * hop as it does the first: an IP address or loopback name in the Location,\n * or the platform, is refused there; a name that resolves to a private\n * address is left to Cloudflare's edge (status 530). */\nfunction nextHop(hop: Hop, status: number, location: string | undefined): Hop | null {\n if (!REDIRECT_STATUS.has(status) || location === undefined) return null;\n let from: URL;\n let to: URL;\n try {\n from = new URL(hop.url);\n to = new URL(location, hop.url);\n } catch {\n return null;\n }\n if (from.protocol === 'https:' && to.protocol === 'http:') return null;\n const sameOrigin = to.origin === from.origin && to.origin !== 'null';\n const toGet =\n (status === 303 && hop.method !== 'GET' && hop.method !== 'HEAD') ||\n ((status === 301 || status === 302) && hop.method === 'POST');\n if (!sameOrigin) {\n // The next request would carry the body to another origin.\n if (status === 307 || status === 308) return null;\n if ((status === 301 || status === 302) && !['GET', 'HEAD', 'POST'].includes(hop.method)) {\n return null;\n }\n }\n let { method, headers, body } = hop;\n if (toGet) {\n method = 'GET';\n body = null;\n headers = headers.filter(([name]) => !BODY_HEADERS.has(name.toLowerCase()));\n }\n if (!sameOrigin)\n headers = headers.filter(([name]) => CROSS_ORIGIN_HEADERS.has(name.toLowerCase()));\n return { url: to.href, method, headers, body };\n}\n\nfunction toResponse(answer: ActionHandleNetAnswer, hop: Hop, redirected: boolean): Response {\n if (answer.status < 200 || answer.status > 599) {\n throw new NetError('NET_FAILED', `the server answered with status ${answer.status}`);\n }\n // As Fetch does: no body for a HEAD request or a null body status.\n const body = hop.method === 'HEAD' || NULL_BODY_STATUS.has(answer.status) ? null : answer.body;\n let res: Response;\n try {\n res = new Response(body, {\n status: answer.status,\n statusText: answer.status_text,\n headers: answer.headers,\n });\n } catch {\n try {\n res = new Response(body, { status: answer.status, headers: answer.headers });\n } catch {\n throw new NetError('NET_FAILED', 'the answer could not be read');\n }\n }\n // As a fetch Response: the URL that answered, and whether it was reached\n // through a redirect.\n Object.defineProperty(res, 'url', { value: hop.url });\n if (redirected) Object.defineProperty(res, 'redirected', { value: true });\n return res;\n}\n\n/** p, or the signal's reason as soon as it aborts. A request already at\n * the handle runs on, and the loader waits for it before answering; one\n * still waiting for its turn is never sent. */\nfunction abortable<T>(p: Promise<T>, signal: AbortSignal | null | undefined): Promise<T> {\n if (!signal) return p;\n if (signal.aborted) return Promise.reject(signal.reason);\n return new Promise<T>((resolve, reject) => {\n const onAbort = () => reject(signal.reason);\n signal.addEventListener('abort', onAbort, { once: true });\n p.then(\n (v) => {\n signal.removeEventListener('abort', onAbort);\n resolve(v);\n },\n (e) => {\n signal.removeEventListener('abort', onAbort);\n reject(e);\n },\n );\n });\n}\n\n/** ctx.env: the secrets as a frozen object of strings. */\nfunction envOf(raw: unknown): Readonly<Record<string, string>> {\n const entries =\n raw && typeof raw === 'object' && !Array.isArray(raw)\n ? Object.entries(raw).filter((e): e is [string, string] => typeof e[1] === 'string')\n : [];\n return Object.freeze(Object.fromEntries(entries));\n}\n\nfunction failure(err: unknown): ActionRunResult {\n if (err instanceof ActionError || (err instanceof Error && err.name === 'ActionError')) {\n return { ok: false, error: { kind: 'action_error', message: err.message } };\n }\n const e = err instanceof Error ? err : new Error(String(err));\n const coded = [ActionDbError, ClipError, NetError, ParallError].some((c) => e instanceof c);\n const label = coded ? `${e.name} ${(e as ParallError).code}` : e.name;\n return {\n ok: false,\n error: { kind: 'unexpected', message: `${label}: ${e.message}`, stack: e.stack ?? '' },\n };\n}\n\n/** A database call as the author's code holds it. It notes whether the code\n * attached a rejection handler anywhere along its chain \u2014 `await`,\n * `try`/`catch`, `.catch()`, `.then(f).catch(g)`, `Promise.all` all do \u2014 so\n * a failure nobody looked at fails the action instead of being lost.\n * Promises derived from a call point back to it. */\nclass DbCall<T> extends Promise<T> {\n handled = false;\n origin?: DbCall<unknown>;\n #inFinally = false;\n\n override then<R1 = T, R2 = never>(\n onFulfilled?: ((value: T) => R1 | PromiseLike<R1>) | null,\n onRejected?: ((reason: unknown) => R2 | PromiseLike<R2>) | null,\n ): Promise<R1 | R2> {\n const origin = this.origin ?? this;\n if (typeof onRejected === 'function' && !this.#inFinally) origin.handled = true;\n const derived = super.then(onFulfilled, onRejected) as DbCall<R1 | R2>;\n derived.origin = origin;\n return derived;\n }\n\n // finally() calls then() with a rejection handler that throws the failure\n // on: it handles nothing. A catch on what it returns still counts.\n override finally(onFinally?: (() => void) | null): Promise<T> {\n this.#inFinally = true;\n try {\n return super.finally(onFinally);\n } finally {\n this.#inFinally = false;\n }\n }\n}\n\n// The wrapper's own bookkeeping on a DbCall, which must not count as the\n// author handling it.\nconst observe = Promise.prototype.then as <T>(\n this: Promise<T>,\n onFulfilled: (value: T) => unknown,\n onRejected?: (reason: unknown) => unknown,\n) => Promise<unknown>;\n\n/** Wraps the author's functions into the module entry the loader calls. */\nexport function defineActions(actions: Record<string, ActionFunction>): ActionRunnerClass {\n const names = Object.keys(actions).sort();\n // Not named ActionRunner: the author's export usually is, and a bundler\n // would rename this class to tell the two apart.\n class ActionEntrypoint extends WorkerEntrypoint {\n static readonly actions: readonly string[] = names;\n\n async run(req: ActionRunRequest, handle: ActionHandle): Promise<ActionRunResult> {\n // Database calls still in flight are waited for before answering \u2014 a\n // write the author forgot to await commits before the caller has the\n // result. Calls started from a finishing call are waited for too; the\n // loader refuses any that arrive after run() returns.\n const pending = new Set<Promise<unknown>>();\n const failed = new Map<DbCall<unknown>, unknown>();\n const track = <T>(\n call: Promise<ActionHandleResult>,\n open: (result: ActionHandleResult) => unknown = unwrap,\n ): Promise<T> => {\n const dbCall = new DbCall<T>((resolve, reject) => {\n call.then(open).then(resolve as (value: unknown) => void, reject);\n });\n const settled = observe.call(\n dbCall,\n () => undefined,\n (err) => {\n failed.set(dbCall, err);\n },\n );\n pending.add(settled);\n observe.call(settled, () => pending.delete(settled));\n return dbCall;\n };\n const drain = async () => {\n while (pending.size > 0) await Promise.allSettled([...pending]);\n };\n const db: ActionDb = {\n query: (sql, params = []) => track(handle.query(sql, params)),\n exec: (sql, params = []) => track(handle.exec(sql, params)),\n batch: (statements) => track(handle.batch(statements)),\n };\n // Clip calls are tracked like database calls: waited for before the\n // answer, and a failure nobody looked at fails the action.\n const clip: ActionClip = {\n exec: (clipName, command, args, options) => {\n const request: ActionHandleClipRequest = {\n clip: clipName,\n command,\n args,\n connection: options?.connection,\n profile: options?.profile,\n timeout_ms: options?.timeoutMs,\n };\n const sent =\n typeof handle.clip === 'function'\n ? handle.clip(request)\n : Promise.resolve<ActionHandleResult>({\n ok: false,\n error: {\n code: 'CLIP_UNAVAILABLE',\n message: 'this runtime cannot call connectors yet',\n },\n });\n return track(sent, unwrapClip);\n },\n };\n // Outbound requests: one handle call per hop, at most net_in_flight at\n // once (more wait their turn), tracked like database calls.\n const limit = Math.max(1, req.net_in_flight || DEFAULT_IN_FLIGHT);\n let active = 0;\n const waiting: (() => void)[] = [];\n const send = async (hop: Hop, timeoutMs: number | undefined, signal: AbortSignal | null) => {\n while (active >= limit) await new Promise<void>((resume) => waiting.push(resume));\n active++;\n try {\n // Aborted while it waited for its turn (the code has already had\n // the abort): it is never sent, and the turn passes on.\n if (signal?.aborted) throw signal.reason;\n if (typeof handle.request !== 'function') {\n throw new NetError('NET_UNAVAILABLE', 'this runtime cannot make requests yet');\n }\n return unwrapNet(\n await handle.request({\n ...hop,\n ...(timeoutMs === undefined ? {} : { timeout_ms: timeoutMs }),\n }),\n );\n } finally {\n active--;\n waiting.shift()?.();\n }\n };\n const request = async (input: string | URL | Request, init?: ActionFetchInit) => {\n const first = await firstHop(input, init);\n const { redirect, signal } = first;\n let hop = first.hop;\n for (let followed = 0; ; followed++) {\n // Aborted before this hop: it is never asked for.\n if (signal?.aborted) throw signal.reason;\n const answer = await abortable(send(hop, init?.timeoutMs, signal), signal);\n if (redirect !== 'manual' && REDIRECT_STATUS.has(answer.status)) {\n if (redirect === 'error') {\n throw new NetError(\n 'NET_FAILED',\n `the server redirected (${answer.status}) and redirect is \"error\"`,\n );\n }\n const location = answer.headers.find(\n ([name]) => name.toLowerCase() === 'location',\n )?.[1];\n const next = nextHop(hop, answer.status, location);\n if (next) {\n if (followed >= MAX_REDIRECTS) {\n throw new NetError(\n 'ACTION_LIMIT_EXCEEDED',\n `ctx.fetch follows at most ${MAX_REDIRECTS} redirects`,\n );\n }\n hop = next;\n continue;\n }\n }\n return toResponse(answer, hop, followed > 0);\n }\n };\n const ctxFetch: ActionFetch = (input, init) =>\n track<Response>(\n request(input, init).then((res) => ({ ok: true, value: res }) as ActionHandleResult),\n (result) => (result as { value: unknown }).value,\n );\n const reads = handle as Required<ActionHandle>;\n const read = <T>(r: () => Promise<ActionHandleResult>) =>\n track<T>(readParall(r), unwrapParall);\n const parall: ActionParall = {\n get: (refs) => read<ParallItem[]>(() => reads.parall({ refs: refs as string[] })),\n members: () => read<ParallMember[]>(() => reads.parallMembers()),\n };\n const env = envOf(req.env);\n try {\n const fn = Object.hasOwn(actions, req.action) ? actions[req.action] : undefined;\n if (typeof fn !== 'function') {\n throw new Error(\n `this module does not implement the action ${JSON.stringify(req.action)}`,\n );\n }\n const value = await fn(\n { viewer: req.viewer, app: req.app, db, clip, fetch: ctxFetch, parall, env },\n req.params,\n );\n await drain();\n // A call that failed while the code never looked at it (a forgotten\n // await) fails the action: answering ok would claim a write that did\n // not happen.\n for (const [dbCall, err] of failed) if (!dbCall.handled) throw err;\n const json = JSON.stringify(value === undefined ? null : value);\n if (typeof json !== 'string') {\n throw new TypeError('the action returned a value JSON cannot represent');\n }\n return { ok: true, json };\n } catch (err) {\n await drain();\n return failure(err);\n }\n }\n }\n return ActionEntrypoint;\n}\n";
2
2
  //# sourceMappingURL=apps-actions-sdk.generated.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"apps-actions-sdk.generated.d.ts","sourceRoot":"","sources":["../../src/commands/apps-actions-sdk.generated.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,kBAAkB,8p2BAAwg2B,CAAC"}
1
+ {"version":3,"file":"apps-actions-sdk.generated.d.ts","sourceRoot":"","sources":["../../src/commands/apps-actions-sdk.generated.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,kBAAkB,4q+BAAug+B,CAAC"}
@@ -1,3 +1,3 @@
1
1
  // Generated from ts/miniapp-sdk/src/actions.ts by scripts/generate-miniapp-sdk.mjs. Do not edit.
2
2
  // biome-ignore format: generated copy
3
- export const ACTIONS_SDK_SOURCE = "/**\n * @parall/miniapp-sdk/actions — the action side of a Mini App\n * (docs/engineering-design/mini-app-action-design.md §2): `defineActions`\n * turns the author's functions into the module entry the action loader\n * calls; `ActionError` is the error whose message the caller may see.\n *\n * This file runs inside the Cloudflare isolate, not in the page. It is the\n * only part of the SDK that imports `cloudflare:workers`, and an action\n * module is built from it into one file whose sole external import is that\n * one. Export the result as `ActionRunner` — the loader looks it up by name:\n *\n * export const ActionRunner = defineActions({\n * async addNote(ctx, { text }) {\n * const { rows } = await ctx.db.exec(\n * 'INSERT INTO notes (text, created_by) VALUES ($1, $2) RETURNING id',\n * [text, ctx.viewer.id],\n * );\n * return rows[0];\n * },\n * });\n *\n * Security does not depend on this wrapper: the loader accepts only the two\n * result shapes run() returns, whatever produced them (design §3.1).\n *\n * An action that declares `\"clip\": true` in the manifest (write actions only)\n * may call Clip as the person who called the action\n * (docs/engineering-design/mini-app-clip-design.md):\n *\n * const profile = await ctx.clip.exec('linkedin', 'get-profile', { id }, { connection: 'sales-li' });\n *\n * `ctx.fetch` requests a public HTTP(S) address and returns a standard\n * `Response` (docs/engineering-design/mini-app-network-design.md):\n *\n * const res = await ctx.fetch('https://api.example.com/v1/items');\n * if (!res.ok) throw new ActionError(`the items API answered ${res.status}`);\n * return res.json();\n *\n * `ctx.env` holds the app's secrets by name. Online they are the org shared\n * secrets an org owner or admin gave this app (org settings → 共享密钥 →\n * 给哪些 app); a name the app was not given is undefined:\n *\n * const key = ctx.env.EXAMPLE_API_KEY;\n * if (!key) throw new ActionError('EXAMPLE_API_KEY is missing: an org owner or admin can give it to this app');\n * const res = await ctx.fetch('https://api.example.com/v1/items', { headers: { Authorization: `Bearer ${key}` } });\n */\n\nimport { WorkerEntrypoint } from 'cloudflare:workers';\n\n/** An error whose message reaches every caller as is (ACTION_FAILED with\n * error_kind action_error). Anything else thrown is an unexpected failure. */\nexport class ActionError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ActionError';\n }\n}\n\n/** A database call that was refused or failed. `code` is the platform's:\n * SQL_ERROR, SQL_REJECTED, ACTION_READ_ONLY, ACTION_LIMIT_EXCEEDED, … */\nexport class ActionDbError extends Error {\n readonly code: string;\n\n constructor(code: string, message: string) {\n super(message);\n this.name = 'ActionDbError';\n this.code = code;\n }\n}\n\n/** A Clip call that was refused or failed. `code` is the platform's — the\n * same codes the caller gets running `parall clip exec` themselves\n * (CONNECTION_NOT_ALLOWED, SCRIPT_ERROR, MCP_TOOL_FAILED, …) — or the\n * action's own: CLIP_NOT_DECLARED, ACTION_LIMIT_EXCEEDED, ACTION_DEADLINE.\n * OUTCOME_UNKNOWN means the command may have run: never retry it blindly. */\nexport class ClipError extends Error {\n readonly code: string;\n\n constructor(code: string, message: string) {\n super(message);\n this.name = 'ClipError';\n this.code = code;\n }\n}\n\n/** An outbound request (ctx.fetch) that was refused or failed — an HTTP\n * error status is not one: it comes back as a Response. `code` is the\n * platform's:\n *\n * - not sent: ACTION_INVALID_CALL (the URL, method, headers or body),\n * NET_ADDRESS_BLOCKED (an IP address or a loopback name such as localhost\n * written in the URL, the platform's own hosts), ACTION_LIMIT_EXCEEDED\n * (too many requests, or one too large), ACTION_DEADLINE (too little time\n * left), NET_BUSY (the platform is busy; try again shortly),\n * NET_UNAVAILABLE, USER_DISABLED, ACTION_HANDLE_REVOKED;\n * - sent, so it may have reached the server: NET_TIMEOUT, NET_FAILED,\n * NET_RESPONSE_TOO_LARGE (answers are at most 1 MiB).\n *\n * A host name that resolves to a private or loopback address is not refused\n * here: Cloudflare's edge refuses it, and ctx.fetch returns an ordinary\n * Response with status 530 (body like \"error code: 1016\"), not a NetError;\n * the outbound record shows it as answered with HTTP 530.\n *\n * The platform never retries; send an idempotency key where the other side\n * supports one. */\nexport class NetError extends Error {\n readonly code: string;\n\n constructor(code: string, message: string) {\n super(message);\n this.name = 'NetError';\n this.code = code;\n }\n}\n\n/** The caller, as the platform vouches for it (design §2.2). */\nexport interface ActionViewer {\n id: string;\n display_name: string;\n is_agent: boolean;\n /** Organization role: owner, admin or member. */\n role: string;\n}\n\nexport interface ActionApp {\n id: string;\n version_seq: number;\n}\n\n/** A row as an object keyed by column name, in select-list order. */\nexport type ActionRow = Record<string, unknown>;\n\nexport interface ActionQueryResult {\n rows: ActionRow[];\n truncated: boolean;\n}\n\nexport interface ActionStatementResult {\n rows: ActionRow[];\n rows_affected: number;\n truncated: boolean;\n}\n\nexport interface ActionExecResult extends ActionStatementResult {\n data_seq: number;\n}\n\nexport interface ActionBatchStatement {\n sql: string;\n params?: unknown[];\n}\n\nexport interface ActionBatchResult {\n results: ActionStatementResult[];\n data_seq: number;\n}\n\n/** ctx.db: one statement per query / exec; a batch is one transaction. */\nexport interface ActionDb {\n query(sql: string, params?: unknown[]): Promise<ActionQueryResult>;\n /** Write actions only. */\n exec(sql: string, params?: unknown[]): Promise<ActionExecResult>;\n /** Write actions only; at most 50 statements, counted as one call. */\n batch(statements: ActionBatchStatement[]): Promise<ActionBatchResult>;\n}\n\nexport interface ActionClipOptions {\n /** The connection to run on: its alias or ccn_ id. The caller must be\n * allowed to use it, exactly as for their own `parall clip exec`. */\n connection: string;\n profile?: string;\n /** The command's timeout; 30 s by default, cut to what the action's\n * deadline leaves. */\n timeoutMs?: number;\n}\n\n/** ctx.clip: Clip calls as the action's caller; actions that declare clip only. */\nexport interface ActionClip {\n /** Runs a command of a Clip (its name or crg_ id) and returns the Clip's\n * data; throws ClipError. */\n exec(clip: string, command: string, args: unknown, options: ActionClipOptions): Promise<unknown>;\n}\n\n/** ctx.fetch's options: the standard ones — method, headers, body, signal,\n * redirect — and the request's timeout. Others (cache, credentials, mode,\n * the Workers `cf`) are not looked at: every request is uncached and carries\n * only what the code sets. */\nexport interface ActionFetchInit extends RequestInit {\n /** This request's timeout; 30 s by default, cut to what the action's\n * deadline leaves. With redirects, each hop has it. */\n timeoutMs?: number;\n}\n\n/** ctx.fetch: a public HTTP(S) request from the platform, recorded in the\n * app's call record (host, method, status, size and time — never the query\n * string, headers or bodies). A local run (`parall app action run --local`,\n * `parall app dev`) sends it straight from your machine and records nothing.\n * Redirects are followed up to 5 times: within the same origin as Fetch\n * does; to another origin with only Accept, Accept-Language,\n * Content-Language and User-Agent kept, and not at all when the next request\n * would carry the body (307, 308, and 301 / 302 for a method other than GET,\n * HEAD or POST) or when it would go from https: to http: — then the redirect\n * itself comes back. Each hop is a request of its own and counts toward the\n * invocation's request limit (20 by default). At most 4 requests (by\n * default) run at once; more wait their turn. Request and answer bodies are\n * at most 1 MiB each. */\nexport type ActionFetch = (\n input: string | URL | Request,\n init?: ActionFetchInit,\n) => Promise<Response>;\n\nexport interface ActionContext {\n viewer: ActionViewer;\n app: ActionApp;\n db: ActionDb;\n clip: ActionClip;\n fetch: ActionFetch;\n /** The app's secrets by name; read-only. Online they are the org shared\n * secrets an org owner or admin gave this app; a local run (`parall app\n * action run --local`) reads the project's .dev.vars instead. Never pass\n * them as params or write them to the Database or a result. */\n env: Readonly<Record<string, string>>;\n}\n\n// biome-ignore lint/suspicious/noExplicitAny: the platform validates params against the declared schema before the call\nexport type ActionFunction = (ctx: ActionContext, params: any) => unknown;\n\n/** What the loader passes run() (ts/actions-worker src/run.ts). A loader\n * before the network sends neither env nor net_in_flight. */\nexport interface ActionRunRequest {\n action: string;\n params: unknown;\n viewer: ActionViewer;\n app: ActionApp;\n env?: Record<string, string>;\n /** How many requests the handle takes at once. */\n net_in_flight?: number;\n}\n\n/** The only two shapes the loader accepts back (ts/actions-worker src/outcome.ts). */\nexport type ActionRunResult =\n | { ok: true; json: string }\n | { ok: false; error: { kind: 'action_error' | 'unexpected'; message: string; stack?: string } };\n\n/** What a handle method resolves to. Failures travel as values because\n * Workers RPC keeps only an exception's name and message (design §6). */\nexport type ActionHandleResult =\n | { ok: true; value: unknown }\n | { ok: false; error: { code: string; message: string } };\n\n/** What the handle's clip method takes. */\nexport interface ActionHandleClipRequest {\n clip: string;\n command: string;\n args?: unknown;\n connection: string;\n profile?: string;\n timeout_ms?: number;\n}\n\n/** What the handle's request method takes: one request, rebuilt by the\n * loader from exactly these fields. */\nexport interface ActionHandleNetRequest {\n url: string;\n method: string;\n headers: [string, string][];\n body: ArrayBuffer | null;\n timeout_ms?: number;\n}\n\n/** What it answers with on success: the answer, never followed. */\nexport interface ActionHandleNetAnswer {\n status: number;\n status_text: string;\n headers: [string, string][];\n body: ArrayBuffer | null;\n}\n\n/** The per-invocation handle the loader passes run(). A loader before Clip\n * calls has no clip method; one before the network has no request method. */\nexport interface ActionHandle {\n query(sql: string, params: unknown[]): Promise<ActionHandleResult>;\n exec(sql: string, params: unknown[]): Promise<ActionHandleResult>;\n batch(statements: ActionBatchStatement[]): Promise<ActionHandleResult>;\n clip?(req: ActionHandleClipRequest): Promise<ActionHandleResult>;\n request?(req: ActionHandleNetRequest): Promise<ActionHandleResult>;\n}\n\n/** What defineActions returns; export it as `ActionRunner`. */\nexport interface ActionRunnerClass {\n /** The actions the module implements, sorted; `parall app check` compares\n * them with the manifest. */\n readonly actions: readonly string[];\n new (\n ctx: unknown,\n env: unknown,\n ): { run(req: ActionRunRequest, handle: ActionHandle): Promise<ActionRunResult> };\n}\n\nfunction unwrap(result: ActionHandleResult): unknown {\n if (result?.ok === true) return result.value;\n if (result?.ok === false) throw new ActionDbError(result.error.code, result.error.message);\n throw new ActionDbError(\n 'ACTION_DB_UNAVAILABLE',\n 'the database handle answered in an unknown shape',\n );\n}\n\nfunction unwrapClip(result: ActionHandleResult): unknown {\n if (result?.ok === true) return result.value;\n if (result?.ok === false) throw new ClipError(result.error.code, result.error.message);\n throw new ClipError(\n 'OUTCOME_UNKNOWN',\n 'the Clip call answered in an unknown shape; it may or may not have run',\n );\n}\n\nfunction unwrapNet(result: ActionHandleResult): ActionHandleNetAnswer {\n if (result?.ok === false) throw new NetError(result.error.code, result.error.message);\n const a = (result?.ok === true ? result.value : null) as ActionHandleNetAnswer | null;\n if (\n !a ||\n typeof a.status !== 'number' ||\n !Array.isArray(a.headers) ||\n (a.body !== null && !(a.body instanceof ArrayBuffer))\n ) {\n throw new NetError(\n 'NET_FAILED',\n 'the request answered in an unknown shape; it may have reached the server',\n );\n }\n return a;\n}\n\n// Statuses whose Response has no body (Fetch's null body status).\nconst NULL_BODY_STATUS = new Set([101, 103, 204, 205, 304]);\nconst REDIRECT_STATUS = new Set([301, 302, 303, 307, 308]);\n// What a redirect to another origin keeps of the author's headers\n// (mini-app-network-design.md §4): a key may be in any other one.\nconst CROSS_ORIGIN_HEADERS = new Set([\n 'accept',\n 'accept-language',\n 'content-language',\n 'user-agent',\n]);\n// Dropped with the body when a redirect turns the request into a GET.\nconst BODY_HEADERS = new Set([\n 'content-encoding',\n 'content-language',\n 'content-location',\n 'content-type',\n]);\nconst MAX_REDIRECTS = 5;\nconst DEFAULT_IN_FLIGHT = 4;\n\n/** One request of a ctx.fetch: the first, or a redirect's next hop. */\ninterface Hop {\n url: string;\n method: string;\n headers: [string, string][];\n body: ArrayBuffer | null;\n}\n\nfunction headerPairs(headers: Headers): [string, string][] {\n const out: [string, string][] = [];\n headers.forEach((value, name) => {\n out.push([name, value]);\n });\n return out;\n}\n\n/** The first hop, as a standard Request reads the input and init — only\n * the method, headers and body are taken from them. */\nasync function firstHop(input: string | URL | Request, init: ActionFetchInit | undefined) {\n let request: Request;\n try {\n request = new Request(input, {\n method: init?.method,\n headers: init?.headers,\n body: init?.body,\n });\n } catch (err) {\n throw new NetError(\n 'ACTION_INVALID_CALL',\n `ctx.fetch: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n const hop: Hop = {\n url: request.url,\n method: request.method,\n headers: headerPairs(request.headers),\n body: request.body ? await request.arrayBuffer() : null,\n };\n const fromInput = typeof input === 'object' && 'redirect' in input ? input.redirect : undefined;\n return {\n hop,\n redirect: (init?.redirect ?? fromInput ?? 'follow') as RequestRedirect,\n signal: init?.signal ?? (input instanceof Request ? input.signal : null),\n };\n}\n\n/** The next hop for a redirect, or null when it is not to be followed\n * (mini-app-network-design.md §4). The handle checks the address of every\n * hop as it does the first: an IP address or loopback name in the Location,\n * or the platform, is refused there; a name that resolves to a private\n * address is left to Cloudflare's edge (status 530). */\nfunction nextHop(hop: Hop, status: number, location: string | undefined): Hop | null {\n if (!REDIRECT_STATUS.has(status) || location === undefined) return null;\n let from: URL;\n let to: URL;\n try {\n from = new URL(hop.url);\n to = new URL(location, hop.url);\n } catch {\n return null;\n }\n if (from.protocol === 'https:' && to.protocol === 'http:') return null;\n const sameOrigin = to.origin === from.origin && to.origin !== 'null';\n const toGet =\n (status === 303 && hop.method !== 'GET' && hop.method !== 'HEAD') ||\n ((status === 301 || status === 302) && hop.method === 'POST');\n if (!sameOrigin) {\n // The next request would carry the body to another origin.\n if (status === 307 || status === 308) return null;\n if ((status === 301 || status === 302) && !['GET', 'HEAD', 'POST'].includes(hop.method)) {\n return null;\n }\n }\n let { method, headers, body } = hop;\n if (toGet) {\n method = 'GET';\n body = null;\n headers = headers.filter(([name]) => !BODY_HEADERS.has(name.toLowerCase()));\n }\n if (!sameOrigin)\n headers = headers.filter(([name]) => CROSS_ORIGIN_HEADERS.has(name.toLowerCase()));\n return { url: to.href, method, headers, body };\n}\n\nfunction toResponse(answer: ActionHandleNetAnswer, hop: Hop, redirected: boolean): Response {\n if (answer.status < 200 || answer.status > 599) {\n throw new NetError('NET_FAILED', `the server answered with status ${answer.status}`);\n }\n // As Fetch does: no body for a HEAD request or a null body status.\n const body = hop.method === 'HEAD' || NULL_BODY_STATUS.has(answer.status) ? null : answer.body;\n let res: Response;\n try {\n res = new Response(body, {\n status: answer.status,\n statusText: answer.status_text,\n headers: answer.headers,\n });\n } catch {\n try {\n res = new Response(body, { status: answer.status, headers: answer.headers });\n } catch {\n throw new NetError('NET_FAILED', 'the answer could not be read');\n }\n }\n // As a fetch Response: the URL that answered, and whether it was reached\n // through a redirect.\n Object.defineProperty(res, 'url', { value: hop.url });\n if (redirected) Object.defineProperty(res, 'redirected', { value: true });\n return res;\n}\n\n/** p, or the signal's reason as soon as it aborts. A request already at\n * the handle runs on, and the loader waits for it before answering; one\n * still waiting for its turn is never sent. */\nfunction abortable<T>(p: Promise<T>, signal: AbortSignal | null | undefined): Promise<T> {\n if (!signal) return p;\n if (signal.aborted) return Promise.reject(signal.reason);\n return new Promise<T>((resolve, reject) => {\n const onAbort = () => reject(signal.reason);\n signal.addEventListener('abort', onAbort, { once: true });\n p.then(\n (v) => {\n signal.removeEventListener('abort', onAbort);\n resolve(v);\n },\n (e) => {\n signal.removeEventListener('abort', onAbort);\n reject(e);\n },\n );\n });\n}\n\n/** ctx.env: the secrets as a frozen object of strings. */\nfunction envOf(raw: unknown): Readonly<Record<string, string>> {\n const entries =\n raw && typeof raw === 'object' && !Array.isArray(raw)\n ? Object.entries(raw).filter((e): e is [string, string] => typeof e[1] === 'string')\n : [];\n return Object.freeze(Object.fromEntries(entries));\n}\n\nfunction failure(err: unknown): ActionRunResult {\n if (err instanceof ActionError || (err instanceof Error && err.name === 'ActionError')) {\n return { ok: false, error: { kind: 'action_error', message: err.message } };\n }\n const e = err instanceof Error ? err : new Error(String(err));\n const label =\n e instanceof ActionDbError || e instanceof ClipError || e instanceof NetError\n ? `${e.name} ${e.code}`\n : e.name;\n return {\n ok: false,\n error: { kind: 'unexpected', message: `${label}: ${e.message}`, stack: e.stack ?? '' },\n };\n}\n\n/** A database call as the author's code holds it. It notes whether the code\n * attached a rejection handler anywhere along its chain — `await`,\n * `try`/`catch`, `.catch()`, `.then(f).catch(g)`, `Promise.all` all do — so\n * a failure nobody looked at fails the action instead of being lost.\n * Promises derived from a call point back to it. */\nclass DbCall<T> extends Promise<T> {\n handled = false;\n origin?: DbCall<unknown>;\n #inFinally = false;\n\n override then<R1 = T, R2 = never>(\n onFulfilled?: ((value: T) => R1 | PromiseLike<R1>) | null,\n onRejected?: ((reason: unknown) => R2 | PromiseLike<R2>) | null,\n ): Promise<R1 | R2> {\n const origin = this.origin ?? this;\n if (typeof onRejected === 'function' && !this.#inFinally) origin.handled = true;\n const derived = super.then(onFulfilled, onRejected) as DbCall<R1 | R2>;\n derived.origin = origin;\n return derived;\n }\n\n // finally() calls then() with a rejection handler that throws the failure\n // on: it handles nothing. A catch on what it returns still counts.\n override finally(onFinally?: (() => void) | null): Promise<T> {\n this.#inFinally = true;\n try {\n return super.finally(onFinally);\n } finally {\n this.#inFinally = false;\n }\n }\n}\n\n// The wrapper's own bookkeeping on a DbCall, which must not count as the\n// author handling it.\nconst observe = Promise.prototype.then as <T>(\n this: Promise<T>,\n onFulfilled: (value: T) => unknown,\n onRejected?: (reason: unknown) => unknown,\n) => Promise<unknown>;\n\n/** Wraps the author's functions into the module entry the loader calls. */\nexport function defineActions(actions: Record<string, ActionFunction>): ActionRunnerClass {\n const names = Object.keys(actions).sort();\n // Not named ActionRunner: the author's export usually is, and a bundler\n // would rename this class to tell the two apart.\n class ActionEntrypoint extends WorkerEntrypoint {\n static readonly actions: readonly string[] = names;\n\n async run(req: ActionRunRequest, handle: ActionHandle): Promise<ActionRunResult> {\n // Database calls still in flight are waited for before answering — a\n // write the author forgot to await commits before the caller has the\n // result. Calls started from a finishing call are waited for too; the\n // loader refuses any that arrive after run() returns.\n const pending = new Set<Promise<unknown>>();\n const failed = new Map<DbCall<unknown>, unknown>();\n const track = <T>(\n call: Promise<ActionHandleResult>,\n open: (result: ActionHandleResult) => unknown = unwrap,\n ): Promise<T> => {\n const dbCall = new DbCall<T>((resolve, reject) => {\n call.then(open).then(resolve as (value: unknown) => void, reject);\n });\n const settled = observe.call(\n dbCall,\n () => undefined,\n (err) => {\n failed.set(dbCall, err);\n },\n );\n pending.add(settled);\n observe.call(settled, () => pending.delete(settled));\n return dbCall;\n };\n const drain = async () => {\n while (pending.size > 0) await Promise.allSettled([...pending]);\n };\n const db: ActionDb = {\n query: (sql, params = []) => track(handle.query(sql, params)),\n exec: (sql, params = []) => track(handle.exec(sql, params)),\n batch: (statements) => track(handle.batch(statements)),\n };\n // Clip calls are tracked like database calls: waited for before the\n // answer, and a failure nobody looked at fails the action.\n const clip: ActionClip = {\n exec: (clipName, command, args, options) => {\n const request: ActionHandleClipRequest = {\n clip: clipName,\n command,\n args,\n connection: options?.connection,\n profile: options?.profile,\n timeout_ms: options?.timeoutMs,\n };\n const sent =\n typeof handle.clip === 'function'\n ? handle.clip(request)\n : Promise.resolve<ActionHandleResult>({\n ok: false,\n error: { code: 'CLIP_UNAVAILABLE', message: 'this runtime cannot call Clip yet' },\n });\n return track(sent, unwrapClip);\n },\n };\n // Outbound requests: one handle call per hop, at most net_in_flight at\n // once (more wait their turn), tracked like database calls.\n const limit = Math.max(1, req.net_in_flight || DEFAULT_IN_FLIGHT);\n let active = 0;\n const waiting: (() => void)[] = [];\n const send = async (hop: Hop, timeoutMs: number | undefined, signal: AbortSignal | null) => {\n while (active >= limit) await new Promise<void>((resume) => waiting.push(resume));\n active++;\n try {\n // Aborted while it waited for its turn (the code has already had\n // the abort): it is never sent, and the turn passes on.\n if (signal?.aborted) throw signal.reason;\n if (typeof handle.request !== 'function') {\n throw new NetError('NET_UNAVAILABLE', 'this runtime cannot make requests yet');\n }\n return unwrapNet(\n await handle.request({\n ...hop,\n ...(timeoutMs === undefined ? {} : { timeout_ms: timeoutMs }),\n }),\n );\n } finally {\n active--;\n waiting.shift()?.();\n }\n };\n const request = async (input: string | URL | Request, init?: ActionFetchInit) => {\n const first = await firstHop(input, init);\n const { redirect, signal } = first;\n let hop = first.hop;\n for (let followed = 0; ; followed++) {\n // Aborted before this hop: it is never asked for.\n if (signal?.aborted) throw signal.reason;\n const answer = await abortable(send(hop, init?.timeoutMs, signal), signal);\n if (redirect !== 'manual' && REDIRECT_STATUS.has(answer.status)) {\n if (redirect === 'error') {\n throw new NetError(\n 'NET_FAILED',\n `the server redirected (${answer.status}) and redirect is \"error\"`,\n );\n }\n const location = answer.headers.find(\n ([name]) => name.toLowerCase() === 'location',\n )?.[1];\n const next = nextHop(hop, answer.status, location);\n if (next) {\n if (followed >= MAX_REDIRECTS) {\n throw new NetError(\n 'ACTION_LIMIT_EXCEEDED',\n `ctx.fetch follows at most ${MAX_REDIRECTS} redirects`,\n );\n }\n hop = next;\n continue;\n }\n }\n return toResponse(answer, hop, followed > 0);\n }\n };\n const ctxFetch: ActionFetch = (input, init) =>\n track<Response>(\n request(input, init).then((res) => ({ ok: true, value: res }) as ActionHandleResult),\n (result) => (result as { value: unknown }).value,\n );\n const env = envOf(req.env);\n try {\n const fn = Object.hasOwn(actions, req.action) ? actions[req.action] : undefined;\n if (typeof fn !== 'function') {\n throw new Error(\n `this module does not implement the action ${JSON.stringify(req.action)}`,\n );\n }\n const value = await fn(\n { viewer: req.viewer, app: req.app, db, clip, fetch: ctxFetch, env },\n req.params,\n );\n await drain();\n // A call that failed while the code never looked at it (a forgotten\n // await) fails the action: answering ok would claim a write that did\n // not happen.\n for (const [dbCall, err] of failed) if (!dbCall.handled) throw err;\n const json = JSON.stringify(value === undefined ? null : value);\n if (typeof json !== 'string') {\n throw new TypeError('the action returned a value JSON cannot represent');\n }\n return { ok: true, json };\n } catch (err) {\n await drain();\n return failure(err);\n }\n }\n }\n return ActionEntrypoint;\n}\n";
3
+ export const ACTIONS_SDK_SOURCE = "/**\n * @parall/miniapp-sdk/actions — the action side of a Mini App\n * (docs/engineering-design/mini-app-action-design.md §2): `defineActions`\n * turns the author's functions into the module entry the action loader\n * calls; `ActionError` is the error whose message the caller may see.\n *\n * This file runs inside the Cloudflare isolate, not in the page. It is the\n * only part of the SDK that imports `cloudflare:workers`, and an action\n * module is built from it into one file whose sole external import is that\n * one. Export the result as `ActionRunner` — the loader looks it up by name:\n *\n * export const ActionRunner = defineActions({\n * async addNote(ctx, { text }) {\n * const { rows } = await ctx.db.exec(\n * 'INSERT INTO notes (text, created_by) VALUES ($1, $2) RETURNING id',\n * [text, ctx.viewer.id],\n * );\n * return rows[0];\n * },\n * });\n *\n * Security does not depend on this wrapper: the loader accepts only the two\n * result shapes run() returns, whatever produced them (design §3.1).\n *\n * An action that declares `\"clip\": true` in the manifest (write actions only)\n * may call connectors as the person who called the action\n * (docs/engineering-design/mini-app-clip-design.md):\n *\n * const profile = await ctx.clip.exec('linkedin', 'get-profile', { id }, { connection: 'sales-li' });\n *\n * `ctx.fetch` requests a public HTTP(S) address and returns a standard\n * `Response` (docs/engineering-design/mini-app-network-design.md):\n *\n * const res = await ctx.fetch('https://api.example.com/v1/items');\n * if (!res.ok) throw new ActionError(`the items API answered ${res.status}`);\n * return res.json();\n *\n * `ctx.env` holds the app's secrets by name. Online they are the org shared\n * secrets an org owner or admin gave this app (org settings → 共享密钥 →\n * 给哪些 app); a name the app was not given is undefined:\n *\n * const key = ctx.env.EXAMPLE_API_KEY;\n * if (!key) throw new ActionError('EXAMPLE_API_KEY is missing: an org owner or admin can give it to this app');\n * const res = await ctx.fetch('https://api.example.com/v1/items', { headers: { Authorization: `Bearer ${key}` } });\n *\n * `ctx.parall.get(refs)` reads Parall files, tasks and members by reference\n * and `ctx.parall.members()` lists the members, as the caller and read-only\n * (ActionParall below).\n */\n\nimport { WorkerEntrypoint } from 'cloudflare:workers';\n\n/** An error whose message reaches every caller as is (ACTION_FAILED with\n * error_kind action_error). Anything else thrown is an unexpected failure. */\nexport class ActionError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ActionError';\n }\n}\n\n/** An error that carries the platform's `code`: what ActionDbError,\n * ClipError, NetError and ParallError have in common. */\nexport class CodedError extends Error {\n readonly code: string;\n\n constructor(code: string, message: string) {\n super(message);\n this.code = code;\n }\n}\n\n/** A database call that was refused or failed. `code` is the platform's:\n * SQL_ERROR, SQL_REJECTED, ACTION_READ_ONLY, ACTION_LIMIT_EXCEEDED, … */\nexport class ActionDbError extends CodedError {\n override name = 'ActionDbError';\n}\n\n/** A connector call that was refused or failed. `code` is the platform's — the\n * same codes the caller gets running `parall connector exec` themselves\n * (CONNECTION_NOT_ALLOWED, SCRIPT_ERROR, MCP_TOOL_FAILED, …) — or the\n * action's own: CLIP_NOT_DECLARED, ACTION_LIMIT_EXCEEDED, ACTION_DEADLINE.\n * OUTCOME_UNKNOWN means the command may have run: never retry it blindly. */\nexport class ClipError extends CodedError {\n override name = 'ClipError';\n}\n\n/** An outbound request (ctx.fetch) that was refused or failed — an HTTP\n * error status is not one: it comes back as a Response. `code` is the\n * platform's:\n *\n * - not sent: ACTION_INVALID_CALL (the URL, method, headers or body),\n * NET_ADDRESS_BLOCKED (an IP address or a loopback name such as localhost\n * written in the URL, the platform's own hosts), ACTION_LIMIT_EXCEEDED\n * (too many requests, or one too large), ACTION_DEADLINE (too little time\n * left), NET_BUSY (the platform is busy; try again shortly),\n * NET_UNAVAILABLE, USER_DISABLED, ACTION_HANDLE_REVOKED;\n * - sent, so it may have reached the server: NET_TIMEOUT, NET_FAILED,\n * NET_RESPONSE_TOO_LARGE (answers are at most 1 MiB).\n *\n * A host name that resolves to a private or loopback address is not refused\n * here: Cloudflare's edge refuses it, and ctx.fetch returns an ordinary\n * Response with status 530 (body like \"error code: 1016\"), not a NetError;\n * the outbound record shows it as answered with HTTP 530.\n *\n * The platform never retries; send an idempotency key where the other side\n * supports one. */\nexport class NetError extends CodedError {\n override name = 'NetError';\n}\n\n/** A ctx.parall.get or members() refused as a whole (an item a get cannot read\n * is in its result instead): ACTION_INVALID_CALL (refs not 1 to 100 strings),\n * ACTION_LIMIT_EXCEEDED, ACTION_DEADLINE, ACTION_HANDLE_REVOKED, USER_DISABLED,\n * ORG_FORBIDDEN (left the org), TOO_LARGE (the members past 1 MiB: read them\n * by reference), PARALL_READ_UNAVAILABLE (off or lost: retry). */\nexport class ParallError extends CodedError {\n override name = 'ParallError';\n}\n\n/** The caller, as the platform vouches for it (design §2.2). */\nexport interface ActionViewer {\n id: string;\n display_name: string;\n is_agent: boolean;\n /** Organization role: owner, admin or member. */\n role: string;\n}\n\nexport interface ActionApp {\n id: string;\n version_seq: number;\n}\n\n/** A row as an object keyed by column name, in select-list order. */\nexport type ActionRow = Record<string, unknown>;\n\nexport interface ActionQueryResult {\n rows: ActionRow[];\n truncated: boolean;\n}\n\nexport interface ActionStatementResult {\n rows: ActionRow[];\n rows_affected: number;\n truncated: boolean;\n}\n\nexport interface ActionExecResult extends ActionStatementResult {\n data_seq: number;\n}\n\nexport interface ActionBatchStatement {\n sql: string;\n params?: unknown[];\n}\n\nexport interface ActionBatchResult {\n results: ActionStatementResult[];\n data_seq: number;\n}\n\n/** ctx.db: one statement per query / exec; a batch is one transaction. */\nexport interface ActionDb {\n query(sql: string, params?: unknown[]): Promise<ActionQueryResult>;\n /** Write actions only. */\n exec(sql: string, params?: unknown[]): Promise<ActionExecResult>;\n /** Write actions only; at most 50 statements, counted as one call. */\n batch(statements: ActionBatchStatement[]): Promise<ActionBatchResult>;\n}\n\nexport interface ActionClipOptions {\n /** The connection to run on: its alias or ccn_ id. The caller must be\n * allowed to use it, exactly as for their own `parall connector exec`. */\n connection: string;\n profile?: string;\n /** The command's timeout; 30 s by default, cut to what the action's\n * deadline leaves. */\n timeoutMs?: number;\n}\n\n/** ctx.clip: connector calls as the action's caller; actions that declare clip only. */\nexport interface ActionClip {\n /** Runs a command of a connector (its name or crg_ id) and returns the connector's\n * data; throws ClipError. */\n exec(clip: string, command: string, args: unknown, options: ActionClipOptions): Promise<unknown>;\n}\n\n/** A file (a chat attachment): no link, no uploader; width and height for images. */\nexport interface ParallFile {\n id: string;\n file_name: string;\n mime_type: string;\n file_size: number;\n width?: number;\n height?: number;\n}\n\n/** A task: due_date is YYYY-MM-DD or null; archived_at once it is archived. */\nexport interface ParallTask {\n id: string;\n identifier?: string;\n title: string;\n status: string;\n priority: string;\n assignee_id?: string;\n project_id?: string;\n due_date: string | null;\n created_at: string;\n updated_at: string;\n archived_at?: string;\n}\n\n/** An active member of the app's organization, person or agent; no email. */\nexport interface ParallMember {\n user_id: string;\n display_name: string;\n avatar_url?: string;\n type: 'human' | 'agent';\n role: string;\n title: string;\n joined_at: string;\n}\n\n/** One reference's answer; a refusal carries only its code: RESTRICTED (the\n * caller may not read it), NOT_FOUND (not in the app's organization: deleted,\n * another organization's, a member who left), INVALID_REF (not an att_, tsk_\n * or usr_ reference) or TOO_LARGE (past the get's 1 MiB). Others: unreadable. */\nexport type ParallItem =\n | { ok: true; type: 'file'; item: ParallFile }\n | { ok: true; type: 'task'; item: ParallTask }\n | { ok: true; type: 'member'; item: ParallMember }\n | { ok: false; code: string };\n\nexport interface ActionParall {\n /** Reads up to 100 references (prll://att_…, tsk_…, usr_… or bare IDs), one\n * item each in order, as the caller's own read now; read-only. The result\n * is the caller's view: store references, never the result across\n * invocations or in page storage. 20 gets per invocation, 10 s each. */\n get(refs: readonly string[]): Promise<ParallItem[]>;\n /** Every active member of the organization, people and agents, with a\n * get's member fields, in the order they joined; counts as one get. */\n members(): Promise<ParallMember[]>;\n}\n\n/** ctx.fetch's options: the standard ones — method, headers, body, signal,\n * redirect — and the request's timeout. Others (cache, credentials, mode,\n * the Workers `cf`) are not looked at: every request is uncached and carries\n * only what the code sets. */\nexport interface ActionFetchInit extends RequestInit {\n /** This request's timeout; 30 s by default, cut to what the action's\n * deadline leaves. With redirects, each hop has it. */\n timeoutMs?: number;\n}\n\n/** ctx.fetch: a public HTTP(S) request from the platform, recorded in the\n * app's call record (host, method, status, size and time — never the query\n * string, headers or bodies). A local run (`parall app action run --local`,\n * `parall app dev`) sends it straight from your machine and records nothing.\n * Redirects are followed up to 5 times: within the same origin as Fetch\n * does; to another origin with only Accept, Accept-Language,\n * Content-Language and User-Agent kept, and not at all when the next request\n * would carry the body (307, 308, and 301 / 302 for a method other than GET,\n * HEAD or POST) or when it would go from https: to http: — then the redirect\n * itself comes back. Each hop is a request of its own and counts toward the\n * invocation's request limit (20 by default). At most 4 requests (by\n * default) run at once; more wait their turn. Request and answer bodies are\n * at most 1 MiB each. */\nexport type ActionFetch = (\n input: string | URL | Request,\n init?: ActionFetchInit,\n) => Promise<Response>;\n\nexport interface ActionContext {\n viewer: ActionViewer;\n app: ActionApp;\n db: ActionDb;\n clip: ActionClip;\n fetch: ActionFetch;\n parall: ActionParall;\n /** The app's secrets by name; read-only. Online they are the org shared\n * secrets an org owner or admin gave this app; a local run (`parall app\n * action run --local`) reads the project's .dev.vars instead. Never pass\n * them as params or write them to the Database or a result. */\n env: Readonly<Record<string, string>>;\n}\n\n// biome-ignore lint/suspicious/noExplicitAny: the platform validates params against the declared schema before the call\nexport type ActionFunction = (ctx: ActionContext, params: any) => unknown;\n\n/** What the loader passes run() (ts/actions-worker src/run.ts). A loader\n * before the network sends neither env nor net_in_flight. */\nexport interface ActionRunRequest {\n action: string;\n params: unknown;\n viewer: ActionViewer;\n app: ActionApp;\n env?: Record<string, string>;\n /** How many requests the handle takes at once. */\n net_in_flight?: number;\n}\n\n/** The only two shapes the loader accepts back (ts/actions-worker src/outcome.ts). */\nexport type ActionRunResult =\n | { ok: true; json: string }\n | { ok: false; error: { kind: 'action_error' | 'unexpected'; message: string; stack?: string } };\n\n/** What a handle method resolves to. Failures travel as values because\n * Workers RPC keeps only an exception's name and message (design §6). */\nexport type ActionHandleResult =\n | { ok: true; value: unknown }\n | { ok: false; error: { code: string; message: string } };\n\n/** What the handle's clip method takes. */\nexport interface ActionHandleClipRequest {\n clip: string;\n command: string;\n args?: unknown;\n connection: string;\n profile?: string;\n timeout_ms?: number;\n}\n\n/** What the handle's request method takes: one request, rebuilt by the\n * loader from exactly these fields. */\nexport interface ActionHandleNetRequest {\n url: string;\n method: string;\n headers: [string, string][];\n body: ArrayBuffer | null;\n timeout_ms?: number;\n}\n\n/** What it answers with on success: the answer, never followed. */\nexport interface ActionHandleNetAnswer {\n status: number;\n status_text: string;\n headers: [string, string][];\n body: ArrayBuffer | null;\n}\n\n/** The per-invocation handle the loader passes run(). Loaders older than Clip\n * calls, the network, Parall reads or the member list lack clip, request,\n * parall or parallMembers. */\nexport interface ActionHandle {\n query(sql: string, params: unknown[]): Promise<ActionHandleResult>;\n exec(sql: string, params: unknown[]): Promise<ActionHandleResult>;\n batch(statements: ActionBatchStatement[]): Promise<ActionHandleResult>;\n clip?(req: ActionHandleClipRequest): Promise<ActionHandleResult>;\n request?(req: ActionHandleNetRequest): Promise<ActionHandleResult>;\n parall?(req: { refs: string[] }): Promise<ActionHandleResult>;\n parallMembers?(): Promise<ActionHandleResult>;\n}\n\n/** What defineActions returns; export it as `ActionRunner`. */\nexport interface ActionRunnerClass {\n /** The actions the module implements, sorted; `parall app check` compares\n * them with the manifest. */\n readonly actions: readonly string[];\n new (\n ctx: unknown,\n env: unknown,\n ): { run(req: ActionRunRequest, handle: ActionHandle): Promise<ActionRunResult> };\n}\n\nfunction unwrap(result: ActionHandleResult): unknown {\n if (result?.ok === true) return result.value;\n if (result?.ok === false) throw new ActionDbError(result.error.code, result.error.message);\n throw new ActionDbError(\n 'ACTION_DB_UNAVAILABLE',\n 'the database handle answered in an unknown shape',\n );\n}\n\nfunction unwrapClip(result: ActionHandleResult): unknown {\n if (result?.ok === true) return result.value;\n if (result?.ok === false) throw new ClipError(result.error.code, result.error.message);\n throw new ClipError(\n 'OUTCOME_UNKNOWN',\n 'the connector call answered in an unknown shape; it may or may not have run',\n );\n}\n\nfunction unwrapParall(result: ActionHandleResult): unknown[] {\n if (result?.ok === false) throw new ParallError(result.error.code, result.error.message);\n if (result?.ok === true && Array.isArray(result.value)) return result.value;\n throw new ParallError('PARALL_READ_UNAVAILABLE', 'the read answered in an unknown shape');\n}\n\n/** One read (the handle checks it). Over RPC the handle is a stub that takes\n * any name for a method, so a loader without this one refuses the call. */\nasync function readParall(read: () => Promise<ActionHandleResult>): Promise<ActionHandleResult> {\n try {\n return await read();\n } catch {\n const message = 'this runtime cannot read Parall data yet';\n return { ok: false, error: { code: 'PARALL_READ_UNAVAILABLE', message } };\n }\n}\n\nfunction unwrapNet(result: ActionHandleResult): ActionHandleNetAnswer {\n if (result?.ok === false) throw new NetError(result.error.code, result.error.message);\n const a = (result?.ok === true ? result.value : null) as ActionHandleNetAnswer | null;\n if (\n !a ||\n typeof a.status !== 'number' ||\n !Array.isArray(a.headers) ||\n (a.body !== null && !(a.body instanceof ArrayBuffer))\n ) {\n throw new NetError(\n 'NET_FAILED',\n 'the request answered in an unknown shape; it may have reached the server',\n );\n }\n return a;\n}\n\n// Statuses whose Response has no body (Fetch's null body status).\nconst NULL_BODY_STATUS = new Set([101, 103, 204, 205, 304]);\nconst REDIRECT_STATUS = new Set([301, 302, 303, 307, 308]);\n// What a redirect to another origin keeps of the author's headers\n// (mini-app-network-design.md §4): a key may be in any other one.\nconst CROSS_ORIGIN_HEADERS = new Set([\n 'accept',\n 'accept-language',\n 'content-language',\n 'user-agent',\n]);\n// Dropped with the body when a redirect turns the request into a GET.\nconst BODY_HEADERS = new Set([\n 'content-encoding',\n 'content-language',\n 'content-location',\n 'content-type',\n]);\nconst MAX_REDIRECTS = 5;\nconst DEFAULT_IN_FLIGHT = 4;\n\n/** One request of a ctx.fetch: the first, or a redirect's next hop. */\ninterface Hop {\n url: string;\n method: string;\n headers: [string, string][];\n body: ArrayBuffer | null;\n}\n\nfunction headerPairs(headers: Headers): [string, string][] {\n const out: [string, string][] = [];\n headers.forEach((value, name) => {\n out.push([name, value]);\n });\n return out;\n}\n\n/** The first hop, as a standard Request reads the input and init — only\n * the method, headers and body are taken from them. */\nasync function firstHop(input: string | URL | Request, init: ActionFetchInit | undefined) {\n let request: Request;\n try {\n request = new Request(input, {\n method: init?.method,\n headers: init?.headers,\n body: init?.body,\n });\n } catch (err) {\n throw new NetError(\n 'ACTION_INVALID_CALL',\n `ctx.fetch: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n const hop: Hop = {\n url: request.url,\n method: request.method,\n headers: headerPairs(request.headers),\n body: request.body ? await request.arrayBuffer() : null,\n };\n const fromInput = typeof input === 'object' && 'redirect' in input ? input.redirect : undefined;\n return {\n hop,\n redirect: (init?.redirect ?? fromInput ?? 'follow') as RequestRedirect,\n signal: init?.signal ?? (input instanceof Request ? input.signal : null),\n };\n}\n\n/** The next hop for a redirect, or null when it is not to be followed\n * (mini-app-network-design.md §4). The handle checks the address of every\n * hop as it does the first: an IP address or loopback name in the Location,\n * or the platform, is refused there; a name that resolves to a private\n * address is left to Cloudflare's edge (status 530). */\nfunction nextHop(hop: Hop, status: number, location: string | undefined): Hop | null {\n if (!REDIRECT_STATUS.has(status) || location === undefined) return null;\n let from: URL;\n let to: URL;\n try {\n from = new URL(hop.url);\n to = new URL(location, hop.url);\n } catch {\n return null;\n }\n if (from.protocol === 'https:' && to.protocol === 'http:') return null;\n const sameOrigin = to.origin === from.origin && to.origin !== 'null';\n const toGet =\n (status === 303 && hop.method !== 'GET' && hop.method !== 'HEAD') ||\n ((status === 301 || status === 302) && hop.method === 'POST');\n if (!sameOrigin) {\n // The next request would carry the body to another origin.\n if (status === 307 || status === 308) return null;\n if ((status === 301 || status === 302) && !['GET', 'HEAD', 'POST'].includes(hop.method)) {\n return null;\n }\n }\n let { method, headers, body } = hop;\n if (toGet) {\n method = 'GET';\n body = null;\n headers = headers.filter(([name]) => !BODY_HEADERS.has(name.toLowerCase()));\n }\n if (!sameOrigin)\n headers = headers.filter(([name]) => CROSS_ORIGIN_HEADERS.has(name.toLowerCase()));\n return { url: to.href, method, headers, body };\n}\n\nfunction toResponse(answer: ActionHandleNetAnswer, hop: Hop, redirected: boolean): Response {\n if (answer.status < 200 || answer.status > 599) {\n throw new NetError('NET_FAILED', `the server answered with status ${answer.status}`);\n }\n // As Fetch does: no body for a HEAD request or a null body status.\n const body = hop.method === 'HEAD' || NULL_BODY_STATUS.has(answer.status) ? null : answer.body;\n let res: Response;\n try {\n res = new Response(body, {\n status: answer.status,\n statusText: answer.status_text,\n headers: answer.headers,\n });\n } catch {\n try {\n res = new Response(body, { status: answer.status, headers: answer.headers });\n } catch {\n throw new NetError('NET_FAILED', 'the answer could not be read');\n }\n }\n // As a fetch Response: the URL that answered, and whether it was reached\n // through a redirect.\n Object.defineProperty(res, 'url', { value: hop.url });\n if (redirected) Object.defineProperty(res, 'redirected', { value: true });\n return res;\n}\n\n/** p, or the signal's reason as soon as it aborts. A request already at\n * the handle runs on, and the loader waits for it before answering; one\n * still waiting for its turn is never sent. */\nfunction abortable<T>(p: Promise<T>, signal: AbortSignal | null | undefined): Promise<T> {\n if (!signal) return p;\n if (signal.aborted) return Promise.reject(signal.reason);\n return new Promise<T>((resolve, reject) => {\n const onAbort = () => reject(signal.reason);\n signal.addEventListener('abort', onAbort, { once: true });\n p.then(\n (v) => {\n signal.removeEventListener('abort', onAbort);\n resolve(v);\n },\n (e) => {\n signal.removeEventListener('abort', onAbort);\n reject(e);\n },\n );\n });\n}\n\n/** ctx.env: the secrets as a frozen object of strings. */\nfunction envOf(raw: unknown): Readonly<Record<string, string>> {\n const entries =\n raw && typeof raw === 'object' && !Array.isArray(raw)\n ? Object.entries(raw).filter((e): e is [string, string] => typeof e[1] === 'string')\n : [];\n return Object.freeze(Object.fromEntries(entries));\n}\n\nfunction failure(err: unknown): ActionRunResult {\n if (err instanceof ActionError || (err instanceof Error && err.name === 'ActionError')) {\n return { ok: false, error: { kind: 'action_error', message: err.message } };\n }\n const e = err instanceof Error ? err : new Error(String(err));\n const coded = [ActionDbError, ClipError, NetError, ParallError].some((c) => e instanceof c);\n const label = coded ? `${e.name} ${(e as ParallError).code}` : e.name;\n return {\n ok: false,\n error: { kind: 'unexpected', message: `${label}: ${e.message}`, stack: e.stack ?? '' },\n };\n}\n\n/** A database call as the author's code holds it. It notes whether the code\n * attached a rejection handler anywhere along its chain — `await`,\n * `try`/`catch`, `.catch()`, `.then(f).catch(g)`, `Promise.all` all do — so\n * a failure nobody looked at fails the action instead of being lost.\n * Promises derived from a call point back to it. */\nclass DbCall<T> extends Promise<T> {\n handled = false;\n origin?: DbCall<unknown>;\n #inFinally = false;\n\n override then<R1 = T, R2 = never>(\n onFulfilled?: ((value: T) => R1 | PromiseLike<R1>) | null,\n onRejected?: ((reason: unknown) => R2 | PromiseLike<R2>) | null,\n ): Promise<R1 | R2> {\n const origin = this.origin ?? this;\n if (typeof onRejected === 'function' && !this.#inFinally) origin.handled = true;\n const derived = super.then(onFulfilled, onRejected) as DbCall<R1 | R2>;\n derived.origin = origin;\n return derived;\n }\n\n // finally() calls then() with a rejection handler that throws the failure\n // on: it handles nothing. A catch on what it returns still counts.\n override finally(onFinally?: (() => void) | null): Promise<T> {\n this.#inFinally = true;\n try {\n return super.finally(onFinally);\n } finally {\n this.#inFinally = false;\n }\n }\n}\n\n// The wrapper's own bookkeeping on a DbCall, which must not count as the\n// author handling it.\nconst observe = Promise.prototype.then as <T>(\n this: Promise<T>,\n onFulfilled: (value: T) => unknown,\n onRejected?: (reason: unknown) => unknown,\n) => Promise<unknown>;\n\n/** Wraps the author's functions into the module entry the loader calls. */\nexport function defineActions(actions: Record<string, ActionFunction>): ActionRunnerClass {\n const names = Object.keys(actions).sort();\n // Not named ActionRunner: the author's export usually is, and a bundler\n // would rename this class to tell the two apart.\n class ActionEntrypoint extends WorkerEntrypoint {\n static readonly actions: readonly string[] = names;\n\n async run(req: ActionRunRequest, handle: ActionHandle): Promise<ActionRunResult> {\n // Database calls still in flight are waited for before answering — a\n // write the author forgot to await commits before the caller has the\n // result. Calls started from a finishing call are waited for too; the\n // loader refuses any that arrive after run() returns.\n const pending = new Set<Promise<unknown>>();\n const failed = new Map<DbCall<unknown>, unknown>();\n const track = <T>(\n call: Promise<ActionHandleResult>,\n open: (result: ActionHandleResult) => unknown = unwrap,\n ): Promise<T> => {\n const dbCall = new DbCall<T>((resolve, reject) => {\n call.then(open).then(resolve as (value: unknown) => void, reject);\n });\n const settled = observe.call(\n dbCall,\n () => undefined,\n (err) => {\n failed.set(dbCall, err);\n },\n );\n pending.add(settled);\n observe.call(settled, () => pending.delete(settled));\n return dbCall;\n };\n const drain = async () => {\n while (pending.size > 0) await Promise.allSettled([...pending]);\n };\n const db: ActionDb = {\n query: (sql, params = []) => track(handle.query(sql, params)),\n exec: (sql, params = []) => track(handle.exec(sql, params)),\n batch: (statements) => track(handle.batch(statements)),\n };\n // Clip calls are tracked like database calls: waited for before the\n // answer, and a failure nobody looked at fails the action.\n const clip: ActionClip = {\n exec: (clipName, command, args, options) => {\n const request: ActionHandleClipRequest = {\n clip: clipName,\n command,\n args,\n connection: options?.connection,\n profile: options?.profile,\n timeout_ms: options?.timeoutMs,\n };\n const sent =\n typeof handle.clip === 'function'\n ? handle.clip(request)\n : Promise.resolve<ActionHandleResult>({\n ok: false,\n error: {\n code: 'CLIP_UNAVAILABLE',\n message: 'this runtime cannot call connectors yet',\n },\n });\n return track(sent, unwrapClip);\n },\n };\n // Outbound requests: one handle call per hop, at most net_in_flight at\n // once (more wait their turn), tracked like database calls.\n const limit = Math.max(1, req.net_in_flight || DEFAULT_IN_FLIGHT);\n let active = 0;\n const waiting: (() => void)[] = [];\n const send = async (hop: Hop, timeoutMs: number | undefined, signal: AbortSignal | null) => {\n while (active >= limit) await new Promise<void>((resume) => waiting.push(resume));\n active++;\n try {\n // Aborted while it waited for its turn (the code has already had\n // the abort): it is never sent, and the turn passes on.\n if (signal?.aborted) throw signal.reason;\n if (typeof handle.request !== 'function') {\n throw new NetError('NET_UNAVAILABLE', 'this runtime cannot make requests yet');\n }\n return unwrapNet(\n await handle.request({\n ...hop,\n ...(timeoutMs === undefined ? {} : { timeout_ms: timeoutMs }),\n }),\n );\n } finally {\n active--;\n waiting.shift()?.();\n }\n };\n const request = async (input: string | URL | Request, init?: ActionFetchInit) => {\n const first = await firstHop(input, init);\n const { redirect, signal } = first;\n let hop = first.hop;\n for (let followed = 0; ; followed++) {\n // Aborted before this hop: it is never asked for.\n if (signal?.aborted) throw signal.reason;\n const answer = await abortable(send(hop, init?.timeoutMs, signal), signal);\n if (redirect !== 'manual' && REDIRECT_STATUS.has(answer.status)) {\n if (redirect === 'error') {\n throw new NetError(\n 'NET_FAILED',\n `the server redirected (${answer.status}) and redirect is \"error\"`,\n );\n }\n const location = answer.headers.find(\n ([name]) => name.toLowerCase() === 'location',\n )?.[1];\n const next = nextHop(hop, answer.status, location);\n if (next) {\n if (followed >= MAX_REDIRECTS) {\n throw new NetError(\n 'ACTION_LIMIT_EXCEEDED',\n `ctx.fetch follows at most ${MAX_REDIRECTS} redirects`,\n );\n }\n hop = next;\n continue;\n }\n }\n return toResponse(answer, hop, followed > 0);\n }\n };\n const ctxFetch: ActionFetch = (input, init) =>\n track<Response>(\n request(input, init).then((res) => ({ ok: true, value: res }) as ActionHandleResult),\n (result) => (result as { value: unknown }).value,\n );\n const reads = handle as Required<ActionHandle>;\n const read = <T>(r: () => Promise<ActionHandleResult>) =>\n track<T>(readParall(r), unwrapParall);\n const parall: ActionParall = {\n get: (refs) => read<ParallItem[]>(() => reads.parall({ refs: refs as string[] })),\n members: () => read<ParallMember[]>(() => reads.parallMembers()),\n };\n const env = envOf(req.env);\n try {\n const fn = Object.hasOwn(actions, req.action) ? actions[req.action] : undefined;\n if (typeof fn !== 'function') {\n throw new Error(\n `this module does not implement the action ${JSON.stringify(req.action)}`,\n );\n }\n const value = await fn(\n { viewer: req.viewer, app: req.app, db, clip, fetch: ctxFetch, parall, env },\n req.params,\n );\n await drain();\n // A call that failed while the code never looked at it (a forgotten\n // await) fails the action: answering ok would claim a write that did\n // not happen.\n for (const [dbCall, err] of failed) if (!dbCall.handled) throw err;\n const json = JSON.stringify(value === undefined ? null : value);\n if (typeof json !== 'string') {\n throw new TypeError('the action returned a value JSON cannot represent');\n }\n return { ok: true, json };\n } catch (err) {\n await drain();\n return failure(err);\n }\n }\n }\n return ActionEntrypoint;\n}\n";
@@ -1 +1 @@
1
- {"version":3,"file":"apps-actions.d.ts","sourceRoot":"","sources":["../../src/commands/apps-actions.ts"],"names":[],"mappings":"AAEA,OAAO,EAGL,KAAK,mBAAmB,EAEzB,MAAM,aAAa,CAAC;AACrB,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAOzC;;;;;;;kBAOkB;AAClB,wBAAgB,yBAAyB,CAAC,GAAG,EAAE,OAAO,QAsIrD;AAaD,UAAU,YAAY;IACpB,KAAK,CAAC,EAAE,MAAM,EAAE,CAAC;IACjB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB;AAED;;0EAE0E;AAC1E,wBAAsB,WAAW,CAC/B,MAAM,EAAE,mBAAmB,GAAG,IAAI,EAClC,IAAI,EAAE,YAAY,GACjB,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAkBlC"}
1
+ {"version":3,"file":"apps-actions.d.ts","sourceRoot":"","sources":["../../src/commands/apps-actions.ts"],"names":[],"mappings":"AAEA,OAAO,EAGL,KAAK,mBAAmB,EAEzB,MAAM,aAAa,CAAC;AACrB,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAoBzC;;;;;;;kBAOkB;AAClB,wBAAgB,yBAAyB,CAAC,GAAG,EAAE,OAAO,QAuIrD;AAaD,UAAU,YAAY;IACpB,KAAK,CAAC,EAAE,MAAM,EAAE,CAAC;IACjB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB;AAED;;0EAE0E;AAC1E,wBAAsB,WAAW,CAC/B,MAAM,EAAE,mBAAmB,GAAG,IAAI,EAClC,IAAI,EAAE,YAAY,GACjB,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAkBlC"}
@@ -6,6 +6,18 @@ import { parsePositiveInt, printError, printJson } from '../lib/output.js';
6
6
  import { readLocalAction, runLocalAction } from './apps-action-local.js';
7
7
  import { appAndArg, appIdFrom, withApp } from './apps-args.js';
8
8
  import { mapActionStack } from './apps-action-stack.js';
9
+ /** What `log` prints of a call (design §5.3): the server blanks what the
10
+ * reader may not see; this says why a field is null. */
11
+ const LOG_HELP = `
12
+ Who sees what: every write call, and every read call that failed or sent
13
+ outbound requests, is listed to everyone who can open the app. What was
14
+ passed and said is not: on a call someone else made, params and
15
+ params_preview are null and error_message is absent unless you are one of
16
+ the app's authors or an org owner/admin — read and write calls alike. On a
17
+ call of your own you see its params and its ActionError or over-limit
18
+ message. Only the authors and org owners/admins see an unexpected failure's
19
+ message and stack, and the path of an outbound request, even on a call of
20
+ your own.`;
9
21
  /** `parall app action list | run | log`
10
22
  * (docs/engineering-design/mini-app-action-design.md §3, §5.3, §10): the
11
23
  * same endpoints the page calls, for agents and authors. Anyone who can open
@@ -93,6 +105,7 @@ export function registerAppActionCommands(app) {
93
105
  }
94
106
  });
95
107
  withApp(action.command('log').description("List the app's audited invocations, newest first"))
108
+ .addHelpText('after', LOG_HELP)
96
109
  .option('--limit <n>', 'Entries to return (default 50, at most 200)')
97
110
  .option('--before <rfc3339>', "Page: the previous page's last started_at")
98
111
  .option('--before-id <invocationId>', "Page: the previous page's last invocation_id")