@parall/cli 1.71.0 → 1.73.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.
@@ -1 +1 @@
1
- {"version":3,"file":"apps-action-local.d.ts","sourceRoot":"","sources":["../../src/commands/apps-action-local.ts"],"names":[],"mappings":"AAGA,OAAO,EAEL,KAAK,yBAAyB,EAC9B,KAAK,iBAAiB,EACtB,KAAK,mBAAmB,EACzB,MAAM,aAAa,CAAC;AACrB,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAQ3D;;;;;;;;;;;;cAYc;AAEd,MAAM,WAAW,WAAW;IAC1B,+DAA+D;IAC/D,WAAW,EAAE,OAAO,CAAC;IACrB,IAAI,EAAE,iBAAiB,CAAC;IACxB,MAAM,EAAE,mBAAmB,GAAG,IAAI,CAAC;IACnC,qDAAqD;IACrD,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;CAChB;AAED;iEACiE;AACjE,wBAAsB,eAAe,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,WAAW,CAAC,CAiBtF;AAED,KAAK,MAAM,GAAG,UAAU,CAAC,OAAO,kBAAkB,CAAC,CAAC,QAAQ,CAAC,CAAC;AAU9D;6BAC6B;AAC7B,MAAM,WAAW,gBAAgB;IAC/B,4DAA4D;IAC5D,OAAO,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;IACjC,qDAAqD;IACrD,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,EAAE,EAAE,MAAM,CAAA;KAAE,KAAK,IAAI,CAAC;CAC7D;AAMD;uEACuE;AACvE,wBAAsB,cAAc,CAClC,MAAM,EAAE,MAAM,EACd,KAAK,EAAE,MAAM,EACb,KAAK,EAAE,MAAM,EACb,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,WAAW,EACnB,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC/B,OAAO,GAAE,gBAAqB,GAC7B,OAAO,CAAC,yBAAyB,CAAC,CAgEpC"}
1
+ {"version":3,"file":"apps-action-local.d.ts","sourceRoot":"","sources":["../../src/commands/apps-action-local.ts"],"names":[],"mappings":"AAGA,OAAO,EAEL,KAAK,yBAAyB,EAC9B,KAAK,iBAAiB,EACtB,KAAK,mBAAmB,EACzB,MAAM,aAAa,CAAC;AACrB,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAQ3D;;;;;;;;;;;;cAYc;AAEd,MAAM,WAAW,WAAW;IAC1B,+DAA+D;IAC/D,WAAW,EAAE,OAAO,CAAC;IACrB,IAAI,EAAE,iBAAiB,CAAC;IACxB,MAAM,EAAE,mBAAmB,GAAG,IAAI,CAAC;IACnC,qDAAqD;IACrD,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;CAChB;AAED;iEACiE;AACjE,wBAAsB,eAAe,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,WAAW,CAAC,CAiBtF;AAED,KAAK,MAAM,GAAG,UAAU,CAAC,OAAO,kBAAkB,CAAC,CAAC,QAAQ,CAAC,CAAC;AAU9D;6BAC6B;AAC7B,MAAM,WAAW,gBAAgB;IAC/B,4DAA4D;IAC5D,OAAO,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;IACjC,qDAAqD;IACrD,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,EAAE,EAAE,MAAM,CAAA;KAAE,KAAK,IAAI,CAAC;CAC7D;AAMD;uEACuE;AACvE,wBAAsB,cAAc,CAClC,MAAM,EAAE,MAAM,EACd,KAAK,EAAE,MAAM,EACb,KAAK,EAAE,MAAM,EACb,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,WAAW,EACnB,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC/B,OAAO,GAAE,gBAAqB,GAC7B,OAAO,CAAC,yBAAyB,CAAC,CAiEpC"}
@@ -62,6 +62,7 @@ export async function runLocalAction(client, orgId, appId, apiUrl, dist, name, a
62
62
  module: { sha256: action.sha256 },
63
63
  action: name,
64
64
  kind: action.kind,
65
+ clip: dev.clip === true,
65
66
  params: dev.params,
66
67
  viewer: dev.viewer,
67
68
  ticket: dev.ticket,
@@ -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\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/** 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 ActionContext {\n viewer: ActionViewer;\n app: ActionApp;\n db: ActionDb;\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/invoke.ts). */\nexport interface ActionRunRequest {\n action: string;\n params: unknown;\n viewer: ActionViewer;\n app: ActionApp;\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/** The per-invocation database handle the loader passes run(). */\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}\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 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 = e instanceof ActionDbError ? `${e.name} ${e.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>(call: Promise<ActionHandleResult>): Promise<T> => {\n const dbCall = new DbCall<T>((resolve, reject) => {\n call.then(unwrap).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 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({ viewer: req.viewer, app: req.app, db }, req.params);\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 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\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/** 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\nexport interface ActionContext {\n viewer: ActionViewer;\n app: ActionApp;\n db: ActionDb;\n clip: ActionClip;\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/invoke.ts). */\nexport interface ActionRunRequest {\n action: string;\n params: unknown;\n viewer: ActionViewer;\n app: ActionApp;\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/** The per-invocation handle the loader passes run(). A loader before Clip\n * calls has no clip 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}\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 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.name} ${e.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: { code: 'CLIP_UNAVAILABLE', message: 'this runtime cannot call Clip yet' },\n });\n return track(sent, unwrapClip);\n },\n };\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({ viewer: req.viewer, app: req.app, db, clip }, req.params);\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,49TAA06T,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,kqaAAima,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\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/** 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 ActionContext {\n viewer: ActionViewer;\n app: ActionApp;\n db: ActionDb;\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/invoke.ts). */\nexport interface ActionRunRequest {\n action: string;\n params: unknown;\n viewer: ActionViewer;\n app: ActionApp;\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/** The per-invocation database handle the loader passes run(). */\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}\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 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 = e instanceof ActionDbError ? `${e.name} ${e.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>(call: Promise<ActionHandleResult>): Promise<T> => {\n const dbCall = new DbCall<T>((resolve, reject) => {\n call.then(unwrap).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 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({ viewer: req.viewer, app: req.app, db }, req.params);\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 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\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/** 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\nexport interface ActionContext {\n viewer: ActionViewer;\n app: ActionApp;\n db: ActionDb;\n clip: ActionClip;\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/invoke.ts). */\nexport interface ActionRunRequest {\n action: string;\n params: unknown;\n viewer: ActionViewer;\n app: ActionApp;\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/** The per-invocation handle the loader passes run(). A loader before Clip\n * calls has no clip 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}\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 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.name} ${e.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: { code: 'CLIP_UNAVAILABLE', message: 'this runtime cannot call Clip yet' },\n });\n return track(sent, unwrapClip);\n },\n };\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({ viewer: req.viewer, app: req.app, db, clip }, req.params);\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,3 +1,3 @@
1
1
  export declare const LOCAL_RUNNER_COMPATIBILITY_DATE = "2026-04-01";
2
- export declare const LOCAL_RUNNER_SOURCE = "// ../actions-worker/src/contract.ts\nvar INSTANCE = /^(default|pr-\\d{1,6})$/;\nvar APP_ID = /^app_[0-9a-z]{21}$/;\nvar SHA256 = /^[0-9a-f]{64}$/;\nvar ACTION_NAME = /^[a-zA-Z][a-zA-Z0-9_]{0,63}$/;\nvar INVOCATION_ID = /^[0-9A-Za-z_-]{1,64}$/;\nvar LIMIT_CEILINGS = {\n cpu_ms: 3e4,\n db_calls: 1e3,\n batch_statements: 1e3,\n batch_bytes: 8 * 1024 * 1024,\n result_bytes: 8 * 1024 * 1024,\n message_bytes: 64 * 1024,\n stack_bytes: 256 * 1024\n};\nfunction isRecord(v) {\n return typeof v === \"object\" && v !== null && !Array.isArray(v);\n}\nfunction positiveInt(v, max) {\n return typeof v === \"number\" && Number.isInteger(v) && v > 0 && v <= max;\n}\nfunction parseInvokeRequest(raw, opts = {}) {\n if (!isRecord(raw)) return \"body is not an object\";\n const {\n invocation_id,\n instance,\n app,\n module,\n action,\n kind,\n viewer,\n ticket,\n deadline_ms,\n limits\n } = raw;\n if (typeof invocation_id !== \"string\" || !INVOCATION_ID.test(invocation_id))\n return \"invocation_id\";\n if (typeof instance !== \"string\" || !INSTANCE.test(instance)) return \"instance\";\n if (!isRecord(app) || typeof app.id !== \"string\" || !APP_ID.test(app.id)) return \"app.id\";\n if (!(opts.unpublished && app.version_seq === 0) && !positiveInt(app.version_seq, 2 ** 31))\n return \"app.version_seq\";\n if (!isRecord(module) || typeof module.sha256 !== \"string\" || !SHA256.test(module.sha256))\n return \"module.sha256\";\n if (typeof action !== \"string\" || !ACTION_NAME.test(action)) return \"action\";\n if (kind !== \"read\" && kind !== \"write\") return \"kind\";\n if (!(\"params\" in raw)) return \"params\";\n if (!isRecord(viewer) || typeof viewer.id !== \"string\" || typeof viewer.display_name !== \"string\" || typeof viewer.is_agent !== \"boolean\" || typeof viewer.role !== \"string\") {\n return \"viewer\";\n }\n if (typeof ticket !== \"string\" || ticket.length === 0 || ticket.length > 4096) return \"ticket\";\n if (typeof deadline_ms !== \"number\" || !Number.isFinite(deadline_ms)) return \"deadline_ms\";\n if (!isRecord(limits)) return \"limits\";\n for (const key of Object.keys(LIMIT_CEILINGS)) {\n if (!positiveInt(limits[key], LIMIT_CEILINGS[key])) return `limits.${key}`;\n }\n return {\n invocation_id,\n instance,\n app: { id: app.id, version_seq: app.version_seq },\n module: { sha256: module.sha256 },\n action,\n kind,\n params: raw.params,\n viewer: {\n id: viewer.id,\n display_name: viewer.display_name,\n is_agent: viewer.is_agent,\n role: viewer.role\n },\n ticket,\n deadline_ms,\n limits\n };\n}\n\n// ../actions-worker/src/db-caller.ts\nvar USER_AGENT = \"parall-actions-worker/1\";\nvar TICKET_HEADER = \"X-Prll-Action-Ticket\";\nvar INVOCATION_HEADER = \"X-Prll-Action-Invocation\";\nvar SWIMLANE_HEADER = \"X-Prll-Swimlane\";\nvar MAX_SQL_BYTES = 256 * 1024;\nvar encoder = new TextEncoder();\nfunction handleError(code, message) {\n const err = new Error(message);\n err.name = \"ActionDbError\";\n err.code = code;\n return err;\n}\nfunction statementOf(v) {\n if (typeof v !== \"object\" || v === null) return null;\n const { sql, params } = v;\n if (typeof sql !== \"string\" || sql.length === 0 || encoder.encode(sql).byteLength > MAX_SQL_BYTES)\n return null;\n if (params !== void 0 && !Array.isArray(params)) return null;\n return { sql, params: params ?? [] };\n}\nfunction requestBody(op, payload, limits) {\n if (op === \"batch\") {\n const statements = payload?.statements;\n if (!Array.isArray(statements) || statements.length === 0) {\n throw handleError(\"ACTION_INVALID_CALL\", \"batch needs a non-empty array of { sql, params }\");\n }\n if (statements.length > limits.batch_statements) {\n throw handleError(\n \"ACTION_LIMIT_EXCEEDED\",\n `a batch may hold at most ${limits.batch_statements} statements`\n );\n }\n const parsed = statements.map(statementOf);\n if (parsed.some((s) => s === null)) {\n throw handleError(\n \"ACTION_INVALID_CALL\",\n \"every batch entry needs a non-empty sql string and a params array\"\n );\n }\n const body = JSON.stringify({ statements: parsed });\n if (encoder.encode(body).byteLength > limits.batch_bytes) {\n throw handleError(\n \"ACTION_LIMIT_EXCEEDED\",\n `a batch may be at most ${limits.batch_bytes} bytes`\n );\n }\n return body;\n }\n const statement = statementOf(payload);\n if (!statement)\n throw handleError(\n \"ACTION_INVALID_CALL\",\n `${op} needs a non-empty sql string and a params array`\n );\n return JSON.stringify(statement);\n}\nfunction trackDataSeq(state, result) {\n const seq = result?.data_seq;\n if (typeof seq !== \"number\" || !Number.isInteger(seq)) return;\n state.dataSeq = state.dataSeq ? { from: Math.min(state.dataSeq.from, seq), to: Math.max(state.dataSeq.to, seq) } : { from: seq, to: seq };\n}\nasync function readCapped(res, maxBytes) {\n if (!res.body) return \"\";\n const reader = res.body.getReader();\n const chunks = [];\n let total = 0;\n for (; ; ) {\n const { done, value } = await reader.read();\n if (done) break;\n total += value.byteLength;\n if (total > maxBytes) {\n await reader.cancel();\n throw handleError(\n \"ACTION_RESULT_TOO_LARGE\",\n `a database result may be at most ${maxBytes} bytes`\n );\n }\n chunks.push(value);\n }\n const out = new Uint8Array(total);\n let off = 0;\n for (const c of chunks) {\n out.set(c, off);\n off += c.byteLength;\n }\n return new TextDecoder().decode(out);\n}\nfunction createDbCaller(cfg) {\n const fetchImpl = cfg.fetchImpl ?? fetch;\n const now = cfg.now ?? Date.now;\n const state = {\n revoked: false,\n calls: 0,\n limitHit: false,\n inflight: /* @__PURE__ */ new Set(),\n dataSeq: null,\n indeterminate: false\n };\n const origin = cfg.callbackOrigin.replace(/\\/+$/, \"\");\n async function send(op, body) {\n const headers = {\n \"Content-Type\": \"application/json\",\n \"User-Agent\": USER_AGENT,\n [TICKET_HEADER]: cfg.ticket,\n [INVOCATION_HEADER]: cfg.invocationId\n };\n if (cfg.instance !== \"default\") headers[SWIMLANE_HEADER] = cfg.instance;\n const remaining = Math.max(1, cfg.deadlineMs - now());\n let res;\n try {\n res = await fetchImpl(`${origin}/api/v1/mini-app-actions/db/${op}`, {\n method: \"POST\",\n headers,\n body,\n signal: AbortSignal.timeout(remaining)\n });\n } catch {\n if (op !== \"query\") state.indeterminate = true;\n throw handleError(\"ACTION_DB_UNAVAILABLE\", \"the database could not be reached\");\n }\n let parsed;\n try {\n const text = await readCapped(res, cfg.limits.result_bytes + 64 * 1024);\n parsed = text ? JSON.parse(text) : null;\n } catch (err) {\n if (op !== \"query\") state.indeterminate = true;\n if (err.code === \"ACTION_RESULT_TOO_LARGE\") throw err;\n throw handleError(\"ACTION_DB_UNAVAILABLE\", \"the database returned an unreadable response\");\n }\n if (!res.ok) {\n const env = parsed?.error;\n if (typeof env?.code !== \"string\") {\n if (op !== \"query\") state.indeterminate = true;\n throw handleError(`HTTP_${res.status}`, `database call failed (${res.status})`);\n }\n const message = typeof env.message === \"string\" ? env.message : `database call failed (${res.status})`;\n throw handleError(env.code, message);\n }\n trackDataSeq(state, parsed);\n return parsed;\n }\n async function call(op, payload) {\n if (state.revoked)\n throw handleError(\"ACTION_HANDLE_REVOKED\", \"this database handle is no longer valid\");\n if (now() >= cfg.deadlineMs)\n throw handleError(\"ACTION_DEADLINE\", \"the action ran past its deadline\");\n if (cfg.kind === \"read\" && op !== \"query\") {\n throw handleError(\"ACTION_READ_ONLY\", \"a read action can only query\");\n }\n state.calls++;\n if (state.calls > cfg.limits.db_calls) {\n state.limitHit = true;\n throw handleError(\n \"ACTION_LIMIT_EXCEEDED\",\n `an action may make at most ${cfg.limits.db_calls} database calls`\n );\n }\n const body = requestBody(op, payload, cfg.limits);\n const pending = send(op, body);\n state.inflight.add(pending);\n try {\n return await pending;\n } finally {\n state.inflight.delete(pending);\n }\n }\n return { state, call };\n}\nasync function settleCall(caller, op, payload) {\n try {\n return { ok: true, value: await caller.call(op, payload) };\n } catch (err) {\n const { code, message } = err ?? {};\n return {\n ok: false,\n error: {\n code: typeof code === \"string\" ? code : \"ACTION_DB_UNAVAILABLE\",\n message: typeof message === \"string\" ? message : \"the database call failed\"\n }\n };\n }\n}\nasync function settle(caller, deadlineMs, now = Date.now) {\n caller.state.revoked = true;\n const inflight = [...caller.state.inflight];\n if (inflight.length === 0) return true;\n const remaining = deadlineMs - now();\n if (remaining > 0) {\n let timer = null;\n await Promise.race([\n Promise.allSettled(inflight),\n new Promise((r) => {\n timer = setTimeout(r, remaining);\n })\n ]);\n if (timer !== null) clearTimeout(timer);\n }\n return caller.state.inflight.size === 0;\n}\n\n// ../actions-worker/src/handle.ts\nimport { RpcTarget } from \"cloudflare:workers\";\nvar ActionDb = class extends RpcTarget {\n #caller;\n constructor(caller) {\n super();\n this.#caller = caller;\n }\n query(sql, params) {\n return settleCall(this.#caller, \"query\", { sql, params });\n }\n exec(sql, params) {\n return settleCall(this.#caller, \"exec\", { sql, params });\n }\n batch(statements) {\n return settleCall(this.#caller, \"batch\", { statements });\n }\n};\nfunction makeHandle(caller) {\n return new ActionDb(caller);\n}\n\n// ../actions-worker/src/outcome.ts\nvar encoder2 = new TextEncoder();\nfunction truncateBytes(s, maxBytes) {\n const bytes = encoder2.encode(s);\n if (bytes.byteLength <= maxBytes) return s;\n return new TextDecoder().decode(bytes.subarray(0, maxBytes)).replace(/\uFFFD+$/u, \"\");\n}\nfunction base(state) {\n return { db_calls: state.calls, data_seq: state.dataSeq };\n}\nfunction failed(state, error) {\n if (state.limitHit) {\n return {\n status: \"limit_exceeded\",\n error: { kind: \"limit\", message: \"the action made more database calls than allowed\" },\n ...base(state)\n };\n }\n return { status: \"failed\", error, ...base(state) };\n}\nfunction asString(v) {\n return typeof v === \"string\" ? v : \"\";\n}\nfunction outcomeFromResult(raw, limits, state) {\n if (typeof raw === \"object\" && raw !== null && !Array.isArray(raw)) {\n const r = raw;\n if (r.ok === true && typeof r.json === \"string\") {\n if (encoder2.encode(r.json).byteLength > limits.result_bytes) {\n return failed(state, {\n kind: \"unexpected\",\n message: `the action result is larger than ${limits.result_bytes} bytes`\n });\n }\n return { status: \"ok\", result_json: r.json, ...base(state) };\n }\n if (r.ok === false && typeof r.error === \"object\" && r.error !== null) {\n const e = r.error;\n if (e.kind === \"action_error\") {\n return failed(state, {\n kind: \"action_error\",\n message: truncateBytes(asString(e.message), limits.message_bytes)\n });\n }\n return failed(state, {\n kind: \"unexpected\",\n message: truncateBytes(asString(e.message), limits.message_bytes),\n stack: truncateBytes(asString(e.stack), limits.stack_bytes)\n });\n }\n }\n return failed(state, {\n kind: \"unexpected\",\n message: \"the action returned a result in an unknown shape\"\n });\n}\nvar CPU_LIMIT = /exceeded (its )?cpu|cpu time limit|exceeded resource limits/i;\nfunction isCpuLimitError(err) {\n const message = err instanceof Error ? err.message : String(err);\n return CPU_LIMIT.test(message);\n}\nfunction outcomeFromThrown(err, limits, state) {\n if (isCpuLimitError(err)) {\n return {\n status: \"limit_exceeded\",\n error: { kind: \"limit\", message: \"the action ran past its CPU time limit\" },\n ...base(state)\n };\n }\n const message = err instanceof Error ? `${err.name}: ${err.message}` : String(err);\n return failed(state, {\n kind: \"unexpected\",\n message: truncateBytes(message, limits.message_bytes)\n });\n}\nfunction timeoutOutcome(state) {\n return {\n status: \"timeout\",\n error: {\n kind: \"timeout\",\n message: \"the action ran past its deadline or lost a database answer; writes it started may have committed\"\n },\n ...base(state)\n };\n}\n\n// ../actions-worker/src/sandbox.ts\nvar COMPATIBILITY_DATE = \"2026-04-01\";\nvar COMPATIBILITY_FLAGS = [];\nvar ENTRYPOINT = \"ActionRunner\";\nvar PRELUDE = `// Runs before the author module (see actions-worker src/sandbox.ts).\nfor (const name of ['caches', 'WebSocket']) {\n try {\n delete globalThis[name];\n } catch {}\n if (name in globalThis) {\n Object.defineProperty(globalThis, name, { value: undefined, writable: false, configurable: false });\n }\n}\n`;\nvar ENTRY = `import './prelude.js';\nexport * from './author.js';\n`;\nfunction workerCode(authorSource) {\n return {\n compatibilityDate: COMPATIBILITY_DATE,\n compatibilityFlags: COMPATIBILITY_FLAGS,\n mainModule: \"entry.js\",\n modules: { \"entry.js\": ENTRY, \"prelude.js\": PRELUDE, \"author.js\": authorSource },\n env: {},\n globalOutbound: null\n };\n}\nvar runtimeVersion = null;\nfunction runtimeVersionOf() {\n if (!runtimeVersion) {\n const material = JSON.stringify([\n COMPATIBILITY_DATE,\n COMPATIBILITY_FLAGS,\n ENTRYPOINT,\n PRELUDE,\n ENTRY,\n \"env:{}\",\n \"outbound:null\"\n ]);\n runtimeVersion = crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(material)).then(\n (d) => Array.from(new Uint8Array(d).slice(0, 8), (b) => b.toString(16).padStart(2, \"0\")).join(\"\")\n );\n }\n return runtimeVersion;\n}\nfunction isolateId(instance, appId, sha256, runtime) {\n return `${instance}:${appId}:${sha256}:${runtime}`;\n}\n\n// ../actions-worker/src/run.ts\nvar DEADLINE_MARGIN_MS = 250;\nasync function runWithDeadline(call, budgetMs) {\n if (budgetMs <= 0) return { kind: \"timeout\" };\n let timer = null;\n const timedOut = new Promise((resolve) => {\n timer = setTimeout(() => resolve({ kind: \"timeout\" }), budgetMs);\n });\n try {\n return await Promise.race([\n call().then(\n (value) => ({ kind: \"result\", value }),\n (error) => ({ kind: \"thrown\", error })\n ),\n timedOut\n ]);\n } finally {\n if (timer !== null) clearTimeout(timer);\n }\n}\nasync function runInvocation(worker, req, callbackOrigin, loadFailure = () => null) {\n const effectiveDeadline = req.deadline_ms - DEADLINE_MARGIN_MS;\n const caller = createDbCaller({\n kind: req.kind,\n ticket: req.ticket,\n invocationId: req.invocation_id,\n instance: req.instance,\n callbackOrigin,\n deadlineMs: effectiveDeadline,\n limits: req.limits\n });\n const handle = makeHandle(caller);\n const entry = worker.getEntrypoint(ENTRYPOINT, { limits: { cpuMs: req.limits.cpu_ms } });\n const settled = await runWithDeadline(\n () => entry.run(\n {\n action: req.action,\n params: req.params,\n viewer: req.viewer,\n app: req.app,\n invocation_id: req.invocation_id\n },\n handle\n ),\n effectiveDeadline - Date.now()\n );\n const drained = await settle(caller, effectiveDeadline);\n if (settled.kind === \"timeout\" || !drained || caller.state.indeterminate) {\n return timeoutOutcome(caller.state);\n }\n if (settled.kind === \"thrown\") {\n return loadFailure() ?? outcomeFromThrown(settled.error, req.limits, caller.state);\n }\n return outcomeFromResult(settled.value, req.limits, caller.state);\n}\n\n// ../actions-worker/src/local.ts\nvar local_default = {\n async fetch(request, env) {\n let body;\n try {\n body = await request.json();\n } catch {\n return Response.json({ error: \"body is not JSON\" }, { status: 400 });\n }\n const req = parseInvokeRequest(body?.request, { unpublished: true });\n if (typeof req === \"string\") return Response.json({ error: `invalid ${req}` }, { status: 400 });\n if (typeof body.source !== \"string\" || typeof body.callback_origin !== \"string\") {\n return Response.json({ error: \"source and callback_origin are required\" }, { status: 400 });\n }\n const runtime = await runtimeVersionOf();\n const worker = env.LOADER.get(\n isolateId(req.instance, req.app.id, req.module.sha256, runtime),\n async () => workerCode(body.source)\n );\n return Response.json(await runInvocation(worker, req, body.callback_origin));\n }\n};\nexport {\n local_default as default\n};\n";
2
+ export declare const LOCAL_RUNNER_SOURCE = "// ../actions-worker/src/contract.ts\nvar INSTANCE = /^(default|pr-\\d{1,6})$/;\nvar APP_ID = /^app_[0-9a-z]{21}$/;\nvar SHA256 = /^[0-9a-f]{64}$/;\nvar ACTION_NAME = /^[a-zA-Z][a-zA-Z0-9_]{0,63}$/;\nvar INVOCATION_ID = /^[0-9A-Za-z_-]{1,64}$/;\nvar LIMIT_CEILINGS = {\n cpu_ms: 3e4,\n db_calls: 1e3,\n batch_statements: 1e3,\n batch_bytes: 8 * 1024 * 1024,\n result_bytes: 8 * 1024 * 1024,\n message_bytes: 64 * 1024,\n stack_bytes: 256 * 1024\n};\nvar CLIP_CALLS_CEILING = 100;\nfunction isRecord(v) {\n return typeof v === \"object\" && v !== null && !Array.isArray(v);\n}\nfunction positiveInt(v, max) {\n return typeof v === \"number\" && Number.isInteger(v) && v > 0 && v <= max;\n}\nfunction parseInvokeRequest(raw, opts = {}) {\n if (!isRecord(raw)) return \"body is not an object\";\n const {\n invocation_id,\n instance,\n app,\n module,\n action,\n kind,\n clip,\n viewer,\n ticket,\n deadline_ms,\n limits\n } = raw;\n if (typeof invocation_id !== \"string\" || !INVOCATION_ID.test(invocation_id))\n return \"invocation_id\";\n if (typeof instance !== \"string\" || !INSTANCE.test(instance)) return \"instance\";\n if (!isRecord(app) || typeof app.id !== \"string\" || !APP_ID.test(app.id)) return \"app.id\";\n if (!(opts.unpublished && app.version_seq === 0) && !positiveInt(app.version_seq, 2 ** 31))\n return \"app.version_seq\";\n if (!isRecord(module) || typeof module.sha256 !== \"string\" || !SHA256.test(module.sha256))\n return \"module.sha256\";\n if (typeof action !== \"string\" || !ACTION_NAME.test(action)) return \"action\";\n if (kind !== \"read\" && kind !== \"write\") return \"kind\";\n if (clip !== void 0 && clip !== false && !(clip === true && kind === \"write\")) return \"clip\";\n if (!(\"params\" in raw)) return \"params\";\n if (!isRecord(viewer) || typeof viewer.id !== \"string\" || typeof viewer.display_name !== \"string\" || typeof viewer.is_agent !== \"boolean\" || typeof viewer.role !== \"string\") {\n return \"viewer\";\n }\n if (typeof ticket !== \"string\" || ticket.length === 0 || ticket.length > 4096) return \"ticket\";\n if (typeof deadline_ms !== \"number\" || !Number.isFinite(deadline_ms)) return \"deadline_ms\";\n if (!isRecord(limits)) return \"limits\";\n for (const key of Object.keys(LIMIT_CEILINGS)) {\n if (!positiveInt(limits[key], LIMIT_CEILINGS[key])) return `limits.${key}`;\n }\n const clipCalls = limits.clip_calls ?? 0;\n if (clipCalls !== 0 && !positiveInt(clipCalls, CLIP_CALLS_CEILING)) return \"limits.clip_calls\";\n return {\n invocation_id,\n instance,\n app: { id: app.id, version_seq: app.version_seq },\n module: { sha256: module.sha256 },\n action,\n kind,\n clip: clip === true,\n params: raw.params,\n viewer: {\n id: viewer.id,\n display_name: viewer.display_name,\n is_agent: viewer.is_agent,\n role: viewer.role\n },\n ticket,\n deadline_ms,\n limits: { ...limits, clip_calls: clipCalls }\n };\n}\n\n// ../actions-worker/src/db-caller.ts\nvar USER_AGENT = \"parall-actions-worker/1\";\nvar TICKET_HEADER = \"X-Prll-Action-Ticket\";\nvar INVOCATION_HEADER = \"X-Prll-Action-Invocation\";\nvar SWIMLANE_HEADER = \"X-Prll-Swimlane\";\nvar MAX_SQL_BYTES = 256 * 1024;\nvar encoder = new TextEncoder();\nfunction handleError(code, message) {\n const err = new Error(message);\n err.name = \"ActionDbError\";\n err.code = code;\n return err;\n}\nfunction statementOf(v) {\n if (typeof v !== \"object\" || v === null) return null;\n const { sql, params } = v;\n if (typeof sql !== \"string\" || sql.length === 0 || encoder.encode(sql).byteLength > MAX_SQL_BYTES)\n return null;\n if (params !== void 0 && !Array.isArray(params)) return null;\n return { sql, params: params ?? [] };\n}\nfunction requestBody(op, payload, limits) {\n if (op === \"batch\") {\n const statements = payload?.statements;\n if (!Array.isArray(statements) || statements.length === 0) {\n throw handleError(\"ACTION_INVALID_CALL\", \"batch needs a non-empty array of { sql, params }\");\n }\n if (statements.length > limits.batch_statements) {\n throw handleError(\n \"ACTION_LIMIT_EXCEEDED\",\n `a batch may hold at most ${limits.batch_statements} statements`\n );\n }\n const parsed = statements.map(statementOf);\n if (parsed.some((s) => s === null)) {\n throw handleError(\n \"ACTION_INVALID_CALL\",\n \"every batch entry needs a non-empty sql string and a params array\"\n );\n }\n const body = JSON.stringify({ statements: parsed });\n if (encoder.encode(body).byteLength > limits.batch_bytes) {\n throw handleError(\n \"ACTION_LIMIT_EXCEEDED\",\n `a batch may be at most ${limits.batch_bytes} bytes`\n );\n }\n return body;\n }\n const statement = statementOf(payload);\n if (!statement)\n throw handleError(\n \"ACTION_INVALID_CALL\",\n `${op} needs a non-empty sql string and a params array`\n );\n return JSON.stringify(statement);\n}\nfunction trackDataSeq(state, result) {\n const seq = result?.data_seq;\n if (typeof seq !== \"number\" || !Number.isInteger(seq)) return;\n state.dataSeq = state.dataSeq ? { from: Math.min(state.dataSeq.from, seq), to: Math.max(state.dataSeq.to, seq) } : { from: seq, to: seq };\n}\nasync function readCapped(res, maxBytes) {\n if (!res.body) return \"\";\n const reader = res.body.getReader();\n const chunks = [];\n let total = 0;\n for (; ; ) {\n const { done, value } = await reader.read();\n if (done) break;\n total += value.byteLength;\n if (total > maxBytes) {\n await reader.cancel();\n throw handleError(\n \"ACTION_RESULT_TOO_LARGE\",\n `a database result may be at most ${maxBytes} bytes`\n );\n }\n chunks.push(value);\n }\n const out = new Uint8Array(total);\n let off = 0;\n for (const c of chunks) {\n out.set(c, off);\n off += c.byteLength;\n }\n return new TextDecoder().decode(out);\n}\nfunction createDbCaller(cfg) {\n const fetchImpl = cfg.fetchImpl ?? fetch;\n const now = cfg.now ?? Date.now;\n const state = {\n revoked: false,\n calls: 0,\n limitHit: false,\n inflight: /* @__PURE__ */ new Set(),\n dataSeq: null,\n indeterminate: false,\n clipCalls: 0,\n clipLimitHit: false\n };\n const origin = cfg.callbackOrigin.replace(/\\/+$/, \"\");\n async function send(op, body) {\n const headers = {\n \"Content-Type\": \"application/json\",\n \"User-Agent\": USER_AGENT,\n [TICKET_HEADER]: cfg.ticket,\n [INVOCATION_HEADER]: cfg.invocationId\n };\n if (cfg.instance !== \"default\") headers[SWIMLANE_HEADER] = cfg.instance;\n const remaining = Math.max(1, cfg.deadlineMs - now());\n let res;\n try {\n res = await fetchImpl(`${origin}/api/v1/mini-app-actions/db/${op}`, {\n method: \"POST\",\n headers,\n body,\n signal: AbortSignal.timeout(remaining)\n });\n } catch {\n if (op !== \"query\") state.indeterminate = true;\n throw handleError(\"ACTION_DB_UNAVAILABLE\", \"the database could not be reached\");\n }\n let parsed;\n try {\n const text = await readCapped(res, cfg.limits.result_bytes + 64 * 1024);\n parsed = text ? JSON.parse(text) : null;\n } catch (err) {\n if (op !== \"query\") state.indeterminate = true;\n if (err.code === \"ACTION_RESULT_TOO_LARGE\") throw err;\n throw handleError(\"ACTION_DB_UNAVAILABLE\", \"the database returned an unreadable response\");\n }\n if (!res.ok) {\n const env = parsed?.error;\n if (typeof env?.code !== \"string\") {\n if (op !== \"query\") state.indeterminate = true;\n throw handleError(`HTTP_${res.status}`, `database call failed (${res.status})`);\n }\n const message = typeof env.message === \"string\" ? env.message : `database call failed (${res.status})`;\n throw handleError(env.code, message);\n }\n trackDataSeq(state, parsed);\n return parsed;\n }\n async function call(op, payload) {\n if (state.revoked)\n throw handleError(\"ACTION_HANDLE_REVOKED\", \"this database handle is no longer valid\");\n if (now() >= cfg.deadlineMs)\n throw handleError(\"ACTION_DEADLINE\", \"the action ran past its deadline\");\n if (cfg.kind === \"read\" && op !== \"query\") {\n throw handleError(\"ACTION_READ_ONLY\", \"a read action can only query\");\n }\n state.calls++;\n if (state.calls > cfg.limits.db_calls) {\n state.limitHit = true;\n throw handleError(\n \"ACTION_LIMIT_EXCEEDED\",\n `an action may make at most ${cfg.limits.db_calls} database calls`\n );\n }\n const body = requestBody(op, payload, cfg.limits);\n const pending = send(op, body);\n state.inflight.add(pending);\n try {\n return await pending;\n } finally {\n state.inflight.delete(pending);\n }\n }\n return { state, call };\n}\nfunction settleCall(caller, op, payload) {\n return settleWith(\n () => caller.call(op, payload),\n \"ACTION_DB_UNAVAILABLE\",\n \"the database call failed\"\n );\n}\nasync function settleWith(run, fallbackCode, fallbackMessage) {\n try {\n return { ok: true, value: await run() };\n } catch (err) {\n const { code, message } = err ?? {};\n return {\n ok: false,\n error: {\n code: typeof code === \"string\" ? code : fallbackCode,\n message: typeof message === \"string\" ? message : fallbackMessage\n }\n };\n }\n}\nasync function settle(caller, deadlineMs, now = Date.now) {\n caller.state.revoked = true;\n const inflight = [...caller.state.inflight];\n if (inflight.length === 0) return true;\n const remaining = deadlineMs - now();\n if (remaining > 0) {\n let timer = null;\n await Promise.race([\n Promise.allSettled(inflight),\n new Promise((r) => {\n timer = setTimeout(r, remaining);\n })\n ]);\n if (timer !== null) clearTimeout(timer);\n }\n return caller.state.inflight.size === 0;\n}\n\n// ../actions-worker/src/clip-caller.ts\nvar ENVELOPE_BYTES = 64 * 1024;\nvar MAX_FIELD_BYTES = 256;\nvar encoder2 = new TextEncoder();\nfunction unknownOutcome() {\n return handleError(\n \"OUTCOME_UNKNOWN\",\n \"the Clip call\\u2019s answer was lost \\u2014 it may or may not have run; do not retry it blindly\"\n );\n}\nfunction field(v, required) {\n if (v === void 0 || v === null) return required ? null : void 0;\n if (typeof v !== \"string\" || encoder2.encode(v).byteLength > MAX_FIELD_BYTES) return null;\n if (required && v.trim() === \"\") return null;\n return v;\n}\nfunction requestBody2(req, seq, maxBytes) {\n const r = typeof req === \"object\" && req !== null ? req : {};\n const clip = field(r.clip, true);\n const command = field(r.command, true);\n const connection = field(r.connection, false);\n const profile = field(r.profile, false);\n const timeout = r.timeout_ms;\n if (clip === null || command === null || connection === null || profile === null) {\n throw handleError(\n \"ACTION_INVALID_CALL\",\n \"clip.exec needs a Clip name or id, a command, and string connection and profile options of at most 256 bytes\"\n );\n }\n if (timeout !== void 0 && (typeof timeout !== \"number\" || !Number.isInteger(timeout) || timeout <= 0 || timeout > 12e4)) {\n throw handleError(\n \"ACTION_INVALID_CALL\",\n \"timeoutMs must be a whole number of milliseconds from 1 to 120000\"\n );\n }\n let body;\n try {\n body = JSON.stringify({\n seq,\n clip,\n command,\n args: r.args,\n connection: connection ?? \"\",\n profile,\n timeout_ms: timeout\n });\n } catch {\n throw handleError(\"ACTION_INVALID_CALL\", \"the Clip arguments cannot be sent as JSON\");\n }\n if (encoder2.encode(body).byteLength > maxBytes) {\n throw handleError(\n \"ACTION_LIMIT_EXCEEDED\",\n `a Clip call's arguments may be at most ${maxBytes} bytes`\n );\n }\n return body;\n}\nfunction createClipCaller(cfg, state) {\n const fetchImpl = cfg.fetchImpl ?? fetch;\n const now = cfg.now ?? Date.now;\n const url = `${cfg.callbackOrigin.replace(/\\/+$/, \"\")}/api/v1/mini-app-actions/clip/exec`;\n async function send(body) {\n const headers = {\n \"Content-Type\": \"application/json\",\n \"User-Agent\": USER_AGENT,\n [TICKET_HEADER]: cfg.ticket,\n [INVOCATION_HEADER]: cfg.invocationId\n };\n if (cfg.instance !== \"default\") headers[SWIMLANE_HEADER] = cfg.instance;\n let res;\n try {\n res = await fetchImpl(url, {\n method: \"POST\",\n headers,\n body,\n signal: AbortSignal.timeout(Math.max(1, cfg.deadlineMs - now()))\n });\n } catch {\n throw unknownOutcome();\n }\n let parsed;\n try {\n const text = await readCapped(res, cfg.maxBytes + ENVELOPE_BYTES);\n parsed = text ? JSON.parse(text) : null;\n } catch {\n throw unknownOutcome();\n }\n if (res.ok) {\n const a = parsed;\n if (a?.ok === true) return a.value ?? null;\n if (a?.ok === false && typeof a.error?.code === \"string\") {\n throw handleError(\n a.error.code,\n typeof a.error.message === \"string\" ? a.error.message : a.error.code\n );\n }\n throw unknownOutcome();\n }\n const env = parsed?.error;\n if (typeof env?.code !== \"string\") throw unknownOutcome();\n throw handleError(\n env.code,\n typeof env.message === \"string\" ? env.message : `Clip call refused (${res.status})`\n );\n }\n async function call(req) {\n if (state.revoked) throw handleError(\"ACTION_HANDLE_REVOKED\", \"this handle is no longer valid\");\n if (!cfg.enabled) {\n throw handleError(\n \"CLIP_NOT_DECLARED\",\n \"this action does not declare clip, so it cannot call Clip\"\n );\n }\n if (now() >= cfg.deadlineMs)\n throw handleError(\"ACTION_DEADLINE\", \"the action ran past its deadline\");\n if (state.clipCalls >= cfg.maxCalls) {\n state.clipLimitHit = true;\n throw handleError(\n \"ACTION_LIMIT_EXCEEDED\",\n `an action may make at most ${cfg.maxCalls} Clip calls`\n );\n }\n const body = requestBody2(req, state.clipCalls + 1, cfg.maxBytes);\n state.clipCalls++;\n const pending = send(body);\n state.inflight.add(pending);\n try {\n return await pending;\n } finally {\n state.inflight.delete(pending);\n }\n }\n return { call };\n}\n\n// ../actions-worker/src/handle.ts\nimport { RpcTarget } from \"cloudflare:workers\";\nvar ActionHandle = class extends RpcTarget {\n #caller;\n #clip;\n constructor(caller, clip) {\n super();\n this.#caller = caller;\n this.#clip = clip;\n }\n query(sql, params) {\n return settleCall(this.#caller, \"query\", { sql, params });\n }\n exec(sql, params) {\n return settleCall(this.#caller, \"exec\", { sql, params });\n }\n batch(statements) {\n return settleCall(this.#caller, \"batch\", { statements });\n }\n clip(req) {\n return settleWith(() => this.#clip.call(req), \"CLIP_UNAVAILABLE\", \"the Clip call failed\");\n }\n};\nfunction makeHandle(caller, clip) {\n return new ActionHandle(caller, clip);\n}\n\n// ../actions-worker/src/outcome.ts\nvar encoder3 = new TextEncoder();\nfunction truncateBytes(s, maxBytes) {\n const bytes = encoder3.encode(s);\n if (bytes.byteLength <= maxBytes) return s;\n return new TextDecoder().decode(bytes.subarray(0, maxBytes)).replace(/\uFFFD+$/u, \"\");\n}\nfunction base(state) {\n return { db_calls: state.calls, data_seq: state.dataSeq, clip_calls: state.clipCalls };\n}\nfunction failed(state, error) {\n if (state.limitHit || state.clipLimitHit) {\n return {\n status: \"limit_exceeded\",\n error: {\n kind: \"limit\",\n message: state.limitHit ? \"the action made more database calls than allowed\" : \"the action made more Clip calls than allowed\"\n },\n ...base(state)\n };\n }\n return { status: \"failed\", error, ...base(state) };\n}\nfunction asString(v) {\n return typeof v === \"string\" ? v : \"\";\n}\nfunction outcomeFromResult(raw, limits, state) {\n if (typeof raw === \"object\" && raw !== null && !Array.isArray(raw)) {\n const r = raw;\n if (r.ok === true && typeof r.json === \"string\") {\n if (encoder3.encode(r.json).byteLength > limits.result_bytes) {\n return failed(state, {\n kind: \"unexpected\",\n message: `the action result is larger than ${limits.result_bytes} bytes`\n });\n }\n return { status: \"ok\", result_json: r.json, ...base(state) };\n }\n if (r.ok === false && typeof r.error === \"object\" && r.error !== null) {\n const e = r.error;\n if (e.kind === \"action_error\") {\n return failed(state, {\n kind: \"action_error\",\n message: truncateBytes(asString(e.message), limits.message_bytes)\n });\n }\n return failed(state, {\n kind: \"unexpected\",\n message: truncateBytes(asString(e.message), limits.message_bytes),\n stack: truncateBytes(asString(e.stack), limits.stack_bytes)\n });\n }\n }\n return failed(state, {\n kind: \"unexpected\",\n message: \"the action returned a result in an unknown shape\"\n });\n}\nvar CPU_LIMIT = /exceeded (its )?cpu|cpu time limit|exceeded resource limits/i;\nfunction isCpuLimitError(err) {\n const message = err instanceof Error ? err.message : String(err);\n return CPU_LIMIT.test(message);\n}\nfunction outcomeFromThrown(err, limits, state) {\n if (isCpuLimitError(err)) {\n return {\n status: \"limit_exceeded\",\n error: { kind: \"limit\", message: \"the action ran past its CPU time limit\" },\n ...base(state)\n };\n }\n const message = err instanceof Error ? `${err.name}: ${err.message}` : String(err);\n return failed(state, {\n kind: \"unexpected\",\n message: truncateBytes(message, limits.message_bytes)\n });\n}\nfunction timeoutOutcome(state) {\n return {\n status: \"timeout\",\n error: {\n kind: \"timeout\",\n message: \"the action ran past its deadline or lost a database answer; writes it started may have committed\"\n },\n ...base(state)\n };\n}\n\n// ../actions-worker/src/sandbox.ts\nvar COMPATIBILITY_DATE = \"2026-04-01\";\nvar COMPATIBILITY_FLAGS = [];\nvar ENTRYPOINT = \"ActionRunner\";\nvar PRELUDE = `// Runs before the author module (see actions-worker src/sandbox.ts).\nfor (const name of ['caches', 'WebSocket']) {\n try {\n delete globalThis[name];\n } catch {}\n if (name in globalThis) {\n Object.defineProperty(globalThis, name, { value: undefined, writable: false, configurable: false });\n }\n}\n`;\nvar ENTRY = `import './prelude.js';\nexport * from './author.js';\n`;\nfunction workerCode(authorSource) {\n return {\n compatibilityDate: COMPATIBILITY_DATE,\n compatibilityFlags: COMPATIBILITY_FLAGS,\n mainModule: \"entry.js\",\n modules: { \"entry.js\": ENTRY, \"prelude.js\": PRELUDE, \"author.js\": authorSource },\n env: {},\n globalOutbound: null\n };\n}\nvar runtimeVersion = null;\nfunction runtimeVersionOf() {\n if (!runtimeVersion) {\n const material = JSON.stringify([\n COMPATIBILITY_DATE,\n COMPATIBILITY_FLAGS,\n ENTRYPOINT,\n PRELUDE,\n ENTRY,\n \"env:{}\",\n \"outbound:null\"\n ]);\n runtimeVersion = crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(material)).then(\n (d) => Array.from(new Uint8Array(d).slice(0, 8), (b) => b.toString(16).padStart(2, \"0\")).join(\"\")\n );\n }\n return runtimeVersion;\n}\nfunction isolateId(instance, appId, sha256, runtime) {\n return `${instance}:${appId}:${sha256}:${runtime}`;\n}\n\n// ../actions-worker/src/run.ts\nvar DEADLINE_MARGIN_MS = 250;\nasync function runWithDeadline(call, budgetMs) {\n if (budgetMs <= 0) return { kind: \"timeout\" };\n let timer = null;\n const timedOut = new Promise((resolve) => {\n timer = setTimeout(() => resolve({ kind: \"timeout\" }), budgetMs);\n });\n try {\n return await Promise.race([\n call().then(\n (value) => ({ kind: \"result\", value }),\n (error) => ({ kind: \"thrown\", error })\n ),\n timedOut\n ]);\n } finally {\n if (timer !== null) clearTimeout(timer);\n }\n}\nasync function runInvocation(worker, req, callbackOrigin, loadFailure = () => null) {\n const effectiveDeadline = req.deadline_ms - DEADLINE_MARGIN_MS;\n const caller = createDbCaller({\n kind: req.kind,\n ticket: req.ticket,\n invocationId: req.invocation_id,\n instance: req.instance,\n callbackOrigin,\n deadlineMs: effectiveDeadline,\n limits: req.limits\n });\n const clip = createClipCaller(\n {\n enabled: req.clip,\n ticket: req.ticket,\n invocationId: req.invocation_id,\n instance: req.instance,\n callbackOrigin,\n deadlineMs: effectiveDeadline,\n maxCalls: req.limits.clip_calls,\n maxBytes: req.limits.result_bytes\n },\n caller.state\n );\n const handle = makeHandle(caller, clip);\n const entry = worker.getEntrypoint(ENTRYPOINT, { limits: { cpuMs: req.limits.cpu_ms } });\n const settled = await runWithDeadline(\n () => entry.run(\n {\n action: req.action,\n params: req.params,\n viewer: req.viewer,\n app: req.app,\n invocation_id: req.invocation_id\n },\n handle\n ),\n effectiveDeadline - Date.now()\n );\n const drained = await settle(caller, effectiveDeadline);\n if (settled.kind === \"timeout\" || !drained || caller.state.indeterminate) {\n return timeoutOutcome(caller.state);\n }\n if (settled.kind === \"thrown\") {\n return loadFailure() ?? outcomeFromThrown(settled.error, req.limits, caller.state);\n }\n return outcomeFromResult(settled.value, req.limits, caller.state);\n}\n\n// ../actions-worker/src/local.ts\nvar local_default = {\n async fetch(request, env) {\n let body;\n try {\n body = await request.json();\n } catch {\n return Response.json({ error: \"body is not JSON\" }, { status: 400 });\n }\n const req = parseInvokeRequest(body?.request, { unpublished: true });\n if (typeof req === \"string\") return Response.json({ error: `invalid ${req}` }, { status: 400 });\n if (typeof body.source !== \"string\" || typeof body.callback_origin !== \"string\") {\n return Response.json({ error: \"source and callback_origin are required\" }, { status: 400 });\n }\n const runtime = await runtimeVersionOf();\n const worker = env.LOADER.get(\n isolateId(req.instance, req.app.id, req.module.sha256, runtime),\n async () => workerCode(body.source)\n );\n return Response.json(await runInvocation(worker, req, body.callback_origin));\n }\n};\nexport {\n local_default as default\n};\n";
3
3
  //# sourceMappingURL=apps-local-runner.generated.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"apps-local-runner.generated.d.ts","sourceRoot":"","sources":["../../src/commands/apps-local-runner.generated.ts"],"names":[],"mappings":"AACA,eAAO,MAAM,+BAA+B,eAAe,CAAC;AAE5D,eAAO,MAAM,mBAAmB,47hBAAu7hB,CAAC"}
1
+ {"version":3,"file":"apps-local-runner.generated.d.ts","sourceRoot":"","sources":["../../src/commands/apps-local-runner.generated.ts"],"names":[],"mappings":"AACA,eAAO,MAAM,+BAA+B,eAAe,CAAC;AAE5D,eAAO,MAAM,mBAAmB,sitBAAiitB,CAAC"}
@@ -1,4 +1,4 @@
1
1
  // Generated from ts/actions-worker/src/local.ts by scripts/generate-local-runner.mjs. Do not edit.
2
2
  export const LOCAL_RUNNER_COMPATIBILITY_DATE = '2026-04-01';
3
3
  // biome-ignore format: generated copy
4
- export const LOCAL_RUNNER_SOURCE = "// ../actions-worker/src/contract.ts\nvar INSTANCE = /^(default|pr-\\d{1,6})$/;\nvar APP_ID = /^app_[0-9a-z]{21}$/;\nvar SHA256 = /^[0-9a-f]{64}$/;\nvar ACTION_NAME = /^[a-zA-Z][a-zA-Z0-9_]{0,63}$/;\nvar INVOCATION_ID = /^[0-9A-Za-z_-]{1,64}$/;\nvar LIMIT_CEILINGS = {\n cpu_ms: 3e4,\n db_calls: 1e3,\n batch_statements: 1e3,\n batch_bytes: 8 * 1024 * 1024,\n result_bytes: 8 * 1024 * 1024,\n message_bytes: 64 * 1024,\n stack_bytes: 256 * 1024\n};\nfunction isRecord(v) {\n return typeof v === \"object\" && v !== null && !Array.isArray(v);\n}\nfunction positiveInt(v, max) {\n return typeof v === \"number\" && Number.isInteger(v) && v > 0 && v <= max;\n}\nfunction parseInvokeRequest(raw, opts = {}) {\n if (!isRecord(raw)) return \"body is not an object\";\n const {\n invocation_id,\n instance,\n app,\n module,\n action,\n kind,\n viewer,\n ticket,\n deadline_ms,\n limits\n } = raw;\n if (typeof invocation_id !== \"string\" || !INVOCATION_ID.test(invocation_id))\n return \"invocation_id\";\n if (typeof instance !== \"string\" || !INSTANCE.test(instance)) return \"instance\";\n if (!isRecord(app) || typeof app.id !== \"string\" || !APP_ID.test(app.id)) return \"app.id\";\n if (!(opts.unpublished && app.version_seq === 0) && !positiveInt(app.version_seq, 2 ** 31))\n return \"app.version_seq\";\n if (!isRecord(module) || typeof module.sha256 !== \"string\" || !SHA256.test(module.sha256))\n return \"module.sha256\";\n if (typeof action !== \"string\" || !ACTION_NAME.test(action)) return \"action\";\n if (kind !== \"read\" && kind !== \"write\") return \"kind\";\n if (!(\"params\" in raw)) return \"params\";\n if (!isRecord(viewer) || typeof viewer.id !== \"string\" || typeof viewer.display_name !== \"string\" || typeof viewer.is_agent !== \"boolean\" || typeof viewer.role !== \"string\") {\n return \"viewer\";\n }\n if (typeof ticket !== \"string\" || ticket.length === 0 || ticket.length > 4096) return \"ticket\";\n if (typeof deadline_ms !== \"number\" || !Number.isFinite(deadline_ms)) return \"deadline_ms\";\n if (!isRecord(limits)) return \"limits\";\n for (const key of Object.keys(LIMIT_CEILINGS)) {\n if (!positiveInt(limits[key], LIMIT_CEILINGS[key])) return `limits.${key}`;\n }\n return {\n invocation_id,\n instance,\n app: { id: app.id, version_seq: app.version_seq },\n module: { sha256: module.sha256 },\n action,\n kind,\n params: raw.params,\n viewer: {\n id: viewer.id,\n display_name: viewer.display_name,\n is_agent: viewer.is_agent,\n role: viewer.role\n },\n ticket,\n deadline_ms,\n limits\n };\n}\n\n// ../actions-worker/src/db-caller.ts\nvar USER_AGENT = \"parall-actions-worker/1\";\nvar TICKET_HEADER = \"X-Prll-Action-Ticket\";\nvar INVOCATION_HEADER = \"X-Prll-Action-Invocation\";\nvar SWIMLANE_HEADER = \"X-Prll-Swimlane\";\nvar MAX_SQL_BYTES = 256 * 1024;\nvar encoder = new TextEncoder();\nfunction handleError(code, message) {\n const err = new Error(message);\n err.name = \"ActionDbError\";\n err.code = code;\n return err;\n}\nfunction statementOf(v) {\n if (typeof v !== \"object\" || v === null) return null;\n const { sql, params } = v;\n if (typeof sql !== \"string\" || sql.length === 0 || encoder.encode(sql).byteLength > MAX_SQL_BYTES)\n return null;\n if (params !== void 0 && !Array.isArray(params)) return null;\n return { sql, params: params ?? [] };\n}\nfunction requestBody(op, payload, limits) {\n if (op === \"batch\") {\n const statements = payload?.statements;\n if (!Array.isArray(statements) || statements.length === 0) {\n throw handleError(\"ACTION_INVALID_CALL\", \"batch needs a non-empty array of { sql, params }\");\n }\n if (statements.length > limits.batch_statements) {\n throw handleError(\n \"ACTION_LIMIT_EXCEEDED\",\n `a batch may hold at most ${limits.batch_statements} statements`\n );\n }\n const parsed = statements.map(statementOf);\n if (parsed.some((s) => s === null)) {\n throw handleError(\n \"ACTION_INVALID_CALL\",\n \"every batch entry needs a non-empty sql string and a params array\"\n );\n }\n const body = JSON.stringify({ statements: parsed });\n if (encoder.encode(body).byteLength > limits.batch_bytes) {\n throw handleError(\n \"ACTION_LIMIT_EXCEEDED\",\n `a batch may be at most ${limits.batch_bytes} bytes`\n );\n }\n return body;\n }\n const statement = statementOf(payload);\n if (!statement)\n throw handleError(\n \"ACTION_INVALID_CALL\",\n `${op} needs a non-empty sql string and a params array`\n );\n return JSON.stringify(statement);\n}\nfunction trackDataSeq(state, result) {\n const seq = result?.data_seq;\n if (typeof seq !== \"number\" || !Number.isInteger(seq)) return;\n state.dataSeq = state.dataSeq ? { from: Math.min(state.dataSeq.from, seq), to: Math.max(state.dataSeq.to, seq) } : { from: seq, to: seq };\n}\nasync function readCapped(res, maxBytes) {\n if (!res.body) return \"\";\n const reader = res.body.getReader();\n const chunks = [];\n let total = 0;\n for (; ; ) {\n const { done, value } = await reader.read();\n if (done) break;\n total += value.byteLength;\n if (total > maxBytes) {\n await reader.cancel();\n throw handleError(\n \"ACTION_RESULT_TOO_LARGE\",\n `a database result may be at most ${maxBytes} bytes`\n );\n }\n chunks.push(value);\n }\n const out = new Uint8Array(total);\n let off = 0;\n for (const c of chunks) {\n out.set(c, off);\n off += c.byteLength;\n }\n return new TextDecoder().decode(out);\n}\nfunction createDbCaller(cfg) {\n const fetchImpl = cfg.fetchImpl ?? fetch;\n const now = cfg.now ?? Date.now;\n const state = {\n revoked: false,\n calls: 0,\n limitHit: false,\n inflight: /* @__PURE__ */ new Set(),\n dataSeq: null,\n indeterminate: false\n };\n const origin = cfg.callbackOrigin.replace(/\\/+$/, \"\");\n async function send(op, body) {\n const headers = {\n \"Content-Type\": \"application/json\",\n \"User-Agent\": USER_AGENT,\n [TICKET_HEADER]: cfg.ticket,\n [INVOCATION_HEADER]: cfg.invocationId\n };\n if (cfg.instance !== \"default\") headers[SWIMLANE_HEADER] = cfg.instance;\n const remaining = Math.max(1, cfg.deadlineMs - now());\n let res;\n try {\n res = await fetchImpl(`${origin}/api/v1/mini-app-actions/db/${op}`, {\n method: \"POST\",\n headers,\n body,\n signal: AbortSignal.timeout(remaining)\n });\n } catch {\n if (op !== \"query\") state.indeterminate = true;\n throw handleError(\"ACTION_DB_UNAVAILABLE\", \"the database could not be reached\");\n }\n let parsed;\n try {\n const text = await readCapped(res, cfg.limits.result_bytes + 64 * 1024);\n parsed = text ? JSON.parse(text) : null;\n } catch (err) {\n if (op !== \"query\") state.indeterminate = true;\n if (err.code === \"ACTION_RESULT_TOO_LARGE\") throw err;\n throw handleError(\"ACTION_DB_UNAVAILABLE\", \"the database returned an unreadable response\");\n }\n if (!res.ok) {\n const env = parsed?.error;\n if (typeof env?.code !== \"string\") {\n if (op !== \"query\") state.indeterminate = true;\n throw handleError(`HTTP_${res.status}`, `database call failed (${res.status})`);\n }\n const message = typeof env.message === \"string\" ? env.message : `database call failed (${res.status})`;\n throw handleError(env.code, message);\n }\n trackDataSeq(state, parsed);\n return parsed;\n }\n async function call(op, payload) {\n if (state.revoked)\n throw handleError(\"ACTION_HANDLE_REVOKED\", \"this database handle is no longer valid\");\n if (now() >= cfg.deadlineMs)\n throw handleError(\"ACTION_DEADLINE\", \"the action ran past its deadline\");\n if (cfg.kind === \"read\" && op !== \"query\") {\n throw handleError(\"ACTION_READ_ONLY\", \"a read action can only query\");\n }\n state.calls++;\n if (state.calls > cfg.limits.db_calls) {\n state.limitHit = true;\n throw handleError(\n \"ACTION_LIMIT_EXCEEDED\",\n `an action may make at most ${cfg.limits.db_calls} database calls`\n );\n }\n const body = requestBody(op, payload, cfg.limits);\n const pending = send(op, body);\n state.inflight.add(pending);\n try {\n return await pending;\n } finally {\n state.inflight.delete(pending);\n }\n }\n return { state, call };\n}\nasync function settleCall(caller, op, payload) {\n try {\n return { ok: true, value: await caller.call(op, payload) };\n } catch (err) {\n const { code, message } = err ?? {};\n return {\n ok: false,\n error: {\n code: typeof code === \"string\" ? code : \"ACTION_DB_UNAVAILABLE\",\n message: typeof message === \"string\" ? message : \"the database call failed\"\n }\n };\n }\n}\nasync function settle(caller, deadlineMs, now = Date.now) {\n caller.state.revoked = true;\n const inflight = [...caller.state.inflight];\n if (inflight.length === 0) return true;\n const remaining = deadlineMs - now();\n if (remaining > 0) {\n let timer = null;\n await Promise.race([\n Promise.allSettled(inflight),\n new Promise((r) => {\n timer = setTimeout(r, remaining);\n })\n ]);\n if (timer !== null) clearTimeout(timer);\n }\n return caller.state.inflight.size === 0;\n}\n\n// ../actions-worker/src/handle.ts\nimport { RpcTarget } from \"cloudflare:workers\";\nvar ActionDb = class extends RpcTarget {\n #caller;\n constructor(caller) {\n super();\n this.#caller = caller;\n }\n query(sql, params) {\n return settleCall(this.#caller, \"query\", { sql, params });\n }\n exec(sql, params) {\n return settleCall(this.#caller, \"exec\", { sql, params });\n }\n batch(statements) {\n return settleCall(this.#caller, \"batch\", { statements });\n }\n};\nfunction makeHandle(caller) {\n return new ActionDb(caller);\n}\n\n// ../actions-worker/src/outcome.ts\nvar encoder2 = new TextEncoder();\nfunction truncateBytes(s, maxBytes) {\n const bytes = encoder2.encode(s);\n if (bytes.byteLength <= maxBytes) return s;\n return new TextDecoder().decode(bytes.subarray(0, maxBytes)).replace(/�+$/u, \"\");\n}\nfunction base(state) {\n return { db_calls: state.calls, data_seq: state.dataSeq };\n}\nfunction failed(state, error) {\n if (state.limitHit) {\n return {\n status: \"limit_exceeded\",\n error: { kind: \"limit\", message: \"the action made more database calls than allowed\" },\n ...base(state)\n };\n }\n return { status: \"failed\", error, ...base(state) };\n}\nfunction asString(v) {\n return typeof v === \"string\" ? v : \"\";\n}\nfunction outcomeFromResult(raw, limits, state) {\n if (typeof raw === \"object\" && raw !== null && !Array.isArray(raw)) {\n const r = raw;\n if (r.ok === true && typeof r.json === \"string\") {\n if (encoder2.encode(r.json).byteLength > limits.result_bytes) {\n return failed(state, {\n kind: \"unexpected\",\n message: `the action result is larger than ${limits.result_bytes} bytes`\n });\n }\n return { status: \"ok\", result_json: r.json, ...base(state) };\n }\n if (r.ok === false && typeof r.error === \"object\" && r.error !== null) {\n const e = r.error;\n if (e.kind === \"action_error\") {\n return failed(state, {\n kind: \"action_error\",\n message: truncateBytes(asString(e.message), limits.message_bytes)\n });\n }\n return failed(state, {\n kind: \"unexpected\",\n message: truncateBytes(asString(e.message), limits.message_bytes),\n stack: truncateBytes(asString(e.stack), limits.stack_bytes)\n });\n }\n }\n return failed(state, {\n kind: \"unexpected\",\n message: \"the action returned a result in an unknown shape\"\n });\n}\nvar CPU_LIMIT = /exceeded (its )?cpu|cpu time limit|exceeded resource limits/i;\nfunction isCpuLimitError(err) {\n const message = err instanceof Error ? err.message : String(err);\n return CPU_LIMIT.test(message);\n}\nfunction outcomeFromThrown(err, limits, state) {\n if (isCpuLimitError(err)) {\n return {\n status: \"limit_exceeded\",\n error: { kind: \"limit\", message: \"the action ran past its CPU time limit\" },\n ...base(state)\n };\n }\n const message = err instanceof Error ? `${err.name}: ${err.message}` : String(err);\n return failed(state, {\n kind: \"unexpected\",\n message: truncateBytes(message, limits.message_bytes)\n });\n}\nfunction timeoutOutcome(state) {\n return {\n status: \"timeout\",\n error: {\n kind: \"timeout\",\n message: \"the action ran past its deadline or lost a database answer; writes it started may have committed\"\n },\n ...base(state)\n };\n}\n\n// ../actions-worker/src/sandbox.ts\nvar COMPATIBILITY_DATE = \"2026-04-01\";\nvar COMPATIBILITY_FLAGS = [];\nvar ENTRYPOINT = \"ActionRunner\";\nvar PRELUDE = `// Runs before the author module (see actions-worker src/sandbox.ts).\nfor (const name of ['caches', 'WebSocket']) {\n try {\n delete globalThis[name];\n } catch {}\n if (name in globalThis) {\n Object.defineProperty(globalThis, name, { value: undefined, writable: false, configurable: false });\n }\n}\n`;\nvar ENTRY = `import './prelude.js';\nexport * from './author.js';\n`;\nfunction workerCode(authorSource) {\n return {\n compatibilityDate: COMPATIBILITY_DATE,\n compatibilityFlags: COMPATIBILITY_FLAGS,\n mainModule: \"entry.js\",\n modules: { \"entry.js\": ENTRY, \"prelude.js\": PRELUDE, \"author.js\": authorSource },\n env: {},\n globalOutbound: null\n };\n}\nvar runtimeVersion = null;\nfunction runtimeVersionOf() {\n if (!runtimeVersion) {\n const material = JSON.stringify([\n COMPATIBILITY_DATE,\n COMPATIBILITY_FLAGS,\n ENTRYPOINT,\n PRELUDE,\n ENTRY,\n \"env:{}\",\n \"outbound:null\"\n ]);\n runtimeVersion = crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(material)).then(\n (d) => Array.from(new Uint8Array(d).slice(0, 8), (b) => b.toString(16).padStart(2, \"0\")).join(\"\")\n );\n }\n return runtimeVersion;\n}\nfunction isolateId(instance, appId, sha256, runtime) {\n return `${instance}:${appId}:${sha256}:${runtime}`;\n}\n\n// ../actions-worker/src/run.ts\nvar DEADLINE_MARGIN_MS = 250;\nasync function runWithDeadline(call, budgetMs) {\n if (budgetMs <= 0) return { kind: \"timeout\" };\n let timer = null;\n const timedOut = new Promise((resolve) => {\n timer = setTimeout(() => resolve({ kind: \"timeout\" }), budgetMs);\n });\n try {\n return await Promise.race([\n call().then(\n (value) => ({ kind: \"result\", value }),\n (error) => ({ kind: \"thrown\", error })\n ),\n timedOut\n ]);\n } finally {\n if (timer !== null) clearTimeout(timer);\n }\n}\nasync function runInvocation(worker, req, callbackOrigin, loadFailure = () => null) {\n const effectiveDeadline = req.deadline_ms - DEADLINE_MARGIN_MS;\n const caller = createDbCaller({\n kind: req.kind,\n ticket: req.ticket,\n invocationId: req.invocation_id,\n instance: req.instance,\n callbackOrigin,\n deadlineMs: effectiveDeadline,\n limits: req.limits\n });\n const handle = makeHandle(caller);\n const entry = worker.getEntrypoint(ENTRYPOINT, { limits: { cpuMs: req.limits.cpu_ms } });\n const settled = await runWithDeadline(\n () => entry.run(\n {\n action: req.action,\n params: req.params,\n viewer: req.viewer,\n app: req.app,\n invocation_id: req.invocation_id\n },\n handle\n ),\n effectiveDeadline - Date.now()\n );\n const drained = await settle(caller, effectiveDeadline);\n if (settled.kind === \"timeout\" || !drained || caller.state.indeterminate) {\n return timeoutOutcome(caller.state);\n }\n if (settled.kind === \"thrown\") {\n return loadFailure() ?? outcomeFromThrown(settled.error, req.limits, caller.state);\n }\n return outcomeFromResult(settled.value, req.limits, caller.state);\n}\n\n// ../actions-worker/src/local.ts\nvar local_default = {\n async fetch(request, env) {\n let body;\n try {\n body = await request.json();\n } catch {\n return Response.json({ error: \"body is not JSON\" }, { status: 400 });\n }\n const req = parseInvokeRequest(body?.request, { unpublished: true });\n if (typeof req === \"string\") return Response.json({ error: `invalid ${req}` }, { status: 400 });\n if (typeof body.source !== \"string\" || typeof body.callback_origin !== \"string\") {\n return Response.json({ error: \"source and callback_origin are required\" }, { status: 400 });\n }\n const runtime = await runtimeVersionOf();\n const worker = env.LOADER.get(\n isolateId(req.instance, req.app.id, req.module.sha256, runtime),\n async () => workerCode(body.source)\n );\n return Response.json(await runInvocation(worker, req, body.callback_origin));\n }\n};\nexport {\n local_default as default\n};\n";
4
+ export const LOCAL_RUNNER_SOURCE = "// ../actions-worker/src/contract.ts\nvar INSTANCE = /^(default|pr-\\d{1,6})$/;\nvar APP_ID = /^app_[0-9a-z]{21}$/;\nvar SHA256 = /^[0-9a-f]{64}$/;\nvar ACTION_NAME = /^[a-zA-Z][a-zA-Z0-9_]{0,63}$/;\nvar INVOCATION_ID = /^[0-9A-Za-z_-]{1,64}$/;\nvar LIMIT_CEILINGS = {\n cpu_ms: 3e4,\n db_calls: 1e3,\n batch_statements: 1e3,\n batch_bytes: 8 * 1024 * 1024,\n result_bytes: 8 * 1024 * 1024,\n message_bytes: 64 * 1024,\n stack_bytes: 256 * 1024\n};\nvar CLIP_CALLS_CEILING = 100;\nfunction isRecord(v) {\n return typeof v === \"object\" && v !== null && !Array.isArray(v);\n}\nfunction positiveInt(v, max) {\n return typeof v === \"number\" && Number.isInteger(v) && v > 0 && v <= max;\n}\nfunction parseInvokeRequest(raw, opts = {}) {\n if (!isRecord(raw)) return \"body is not an object\";\n const {\n invocation_id,\n instance,\n app,\n module,\n action,\n kind,\n clip,\n viewer,\n ticket,\n deadline_ms,\n limits\n } = raw;\n if (typeof invocation_id !== \"string\" || !INVOCATION_ID.test(invocation_id))\n return \"invocation_id\";\n if (typeof instance !== \"string\" || !INSTANCE.test(instance)) return \"instance\";\n if (!isRecord(app) || typeof app.id !== \"string\" || !APP_ID.test(app.id)) return \"app.id\";\n if (!(opts.unpublished && app.version_seq === 0) && !positiveInt(app.version_seq, 2 ** 31))\n return \"app.version_seq\";\n if (!isRecord(module) || typeof module.sha256 !== \"string\" || !SHA256.test(module.sha256))\n return \"module.sha256\";\n if (typeof action !== \"string\" || !ACTION_NAME.test(action)) return \"action\";\n if (kind !== \"read\" && kind !== \"write\") return \"kind\";\n if (clip !== void 0 && clip !== false && !(clip === true && kind === \"write\")) return \"clip\";\n if (!(\"params\" in raw)) return \"params\";\n if (!isRecord(viewer) || typeof viewer.id !== \"string\" || typeof viewer.display_name !== \"string\" || typeof viewer.is_agent !== \"boolean\" || typeof viewer.role !== \"string\") {\n return \"viewer\";\n }\n if (typeof ticket !== \"string\" || ticket.length === 0 || ticket.length > 4096) return \"ticket\";\n if (typeof deadline_ms !== \"number\" || !Number.isFinite(deadline_ms)) return \"deadline_ms\";\n if (!isRecord(limits)) return \"limits\";\n for (const key of Object.keys(LIMIT_CEILINGS)) {\n if (!positiveInt(limits[key], LIMIT_CEILINGS[key])) return `limits.${key}`;\n }\n const clipCalls = limits.clip_calls ?? 0;\n if (clipCalls !== 0 && !positiveInt(clipCalls, CLIP_CALLS_CEILING)) return \"limits.clip_calls\";\n return {\n invocation_id,\n instance,\n app: { id: app.id, version_seq: app.version_seq },\n module: { sha256: module.sha256 },\n action,\n kind,\n clip: clip === true,\n params: raw.params,\n viewer: {\n id: viewer.id,\n display_name: viewer.display_name,\n is_agent: viewer.is_agent,\n role: viewer.role\n },\n ticket,\n deadline_ms,\n limits: { ...limits, clip_calls: clipCalls }\n };\n}\n\n// ../actions-worker/src/db-caller.ts\nvar USER_AGENT = \"parall-actions-worker/1\";\nvar TICKET_HEADER = \"X-Prll-Action-Ticket\";\nvar INVOCATION_HEADER = \"X-Prll-Action-Invocation\";\nvar SWIMLANE_HEADER = \"X-Prll-Swimlane\";\nvar MAX_SQL_BYTES = 256 * 1024;\nvar encoder = new TextEncoder();\nfunction handleError(code, message) {\n const err = new Error(message);\n err.name = \"ActionDbError\";\n err.code = code;\n return err;\n}\nfunction statementOf(v) {\n if (typeof v !== \"object\" || v === null) return null;\n const { sql, params } = v;\n if (typeof sql !== \"string\" || sql.length === 0 || encoder.encode(sql).byteLength > MAX_SQL_BYTES)\n return null;\n if (params !== void 0 && !Array.isArray(params)) return null;\n return { sql, params: params ?? [] };\n}\nfunction requestBody(op, payload, limits) {\n if (op === \"batch\") {\n const statements = payload?.statements;\n if (!Array.isArray(statements) || statements.length === 0) {\n throw handleError(\"ACTION_INVALID_CALL\", \"batch needs a non-empty array of { sql, params }\");\n }\n if (statements.length > limits.batch_statements) {\n throw handleError(\n \"ACTION_LIMIT_EXCEEDED\",\n `a batch may hold at most ${limits.batch_statements} statements`\n );\n }\n const parsed = statements.map(statementOf);\n if (parsed.some((s) => s === null)) {\n throw handleError(\n \"ACTION_INVALID_CALL\",\n \"every batch entry needs a non-empty sql string and a params array\"\n );\n }\n const body = JSON.stringify({ statements: parsed });\n if (encoder.encode(body).byteLength > limits.batch_bytes) {\n throw handleError(\n \"ACTION_LIMIT_EXCEEDED\",\n `a batch may be at most ${limits.batch_bytes} bytes`\n );\n }\n return body;\n }\n const statement = statementOf(payload);\n if (!statement)\n throw handleError(\n \"ACTION_INVALID_CALL\",\n `${op} needs a non-empty sql string and a params array`\n );\n return JSON.stringify(statement);\n}\nfunction trackDataSeq(state, result) {\n const seq = result?.data_seq;\n if (typeof seq !== \"number\" || !Number.isInteger(seq)) return;\n state.dataSeq = state.dataSeq ? { from: Math.min(state.dataSeq.from, seq), to: Math.max(state.dataSeq.to, seq) } : { from: seq, to: seq };\n}\nasync function readCapped(res, maxBytes) {\n if (!res.body) return \"\";\n const reader = res.body.getReader();\n const chunks = [];\n let total = 0;\n for (; ; ) {\n const { done, value } = await reader.read();\n if (done) break;\n total += value.byteLength;\n if (total > maxBytes) {\n await reader.cancel();\n throw handleError(\n \"ACTION_RESULT_TOO_LARGE\",\n `a database result may be at most ${maxBytes} bytes`\n );\n }\n chunks.push(value);\n }\n const out = new Uint8Array(total);\n let off = 0;\n for (const c of chunks) {\n out.set(c, off);\n off += c.byteLength;\n }\n return new TextDecoder().decode(out);\n}\nfunction createDbCaller(cfg) {\n const fetchImpl = cfg.fetchImpl ?? fetch;\n const now = cfg.now ?? Date.now;\n const state = {\n revoked: false,\n calls: 0,\n limitHit: false,\n inflight: /* @__PURE__ */ new Set(),\n dataSeq: null,\n indeterminate: false,\n clipCalls: 0,\n clipLimitHit: false\n };\n const origin = cfg.callbackOrigin.replace(/\\/+$/, \"\");\n async function send(op, body) {\n const headers = {\n \"Content-Type\": \"application/json\",\n \"User-Agent\": USER_AGENT,\n [TICKET_HEADER]: cfg.ticket,\n [INVOCATION_HEADER]: cfg.invocationId\n };\n if (cfg.instance !== \"default\") headers[SWIMLANE_HEADER] = cfg.instance;\n const remaining = Math.max(1, cfg.deadlineMs - now());\n let res;\n try {\n res = await fetchImpl(`${origin}/api/v1/mini-app-actions/db/${op}`, {\n method: \"POST\",\n headers,\n body,\n signal: AbortSignal.timeout(remaining)\n });\n } catch {\n if (op !== \"query\") state.indeterminate = true;\n throw handleError(\"ACTION_DB_UNAVAILABLE\", \"the database could not be reached\");\n }\n let parsed;\n try {\n const text = await readCapped(res, cfg.limits.result_bytes + 64 * 1024);\n parsed = text ? JSON.parse(text) : null;\n } catch (err) {\n if (op !== \"query\") state.indeterminate = true;\n if (err.code === \"ACTION_RESULT_TOO_LARGE\") throw err;\n throw handleError(\"ACTION_DB_UNAVAILABLE\", \"the database returned an unreadable response\");\n }\n if (!res.ok) {\n const env = parsed?.error;\n if (typeof env?.code !== \"string\") {\n if (op !== \"query\") state.indeterminate = true;\n throw handleError(`HTTP_${res.status}`, `database call failed (${res.status})`);\n }\n const message = typeof env.message === \"string\" ? env.message : `database call failed (${res.status})`;\n throw handleError(env.code, message);\n }\n trackDataSeq(state, parsed);\n return parsed;\n }\n async function call(op, payload) {\n if (state.revoked)\n throw handleError(\"ACTION_HANDLE_REVOKED\", \"this database handle is no longer valid\");\n if (now() >= cfg.deadlineMs)\n throw handleError(\"ACTION_DEADLINE\", \"the action ran past its deadline\");\n if (cfg.kind === \"read\" && op !== \"query\") {\n throw handleError(\"ACTION_READ_ONLY\", \"a read action can only query\");\n }\n state.calls++;\n if (state.calls > cfg.limits.db_calls) {\n state.limitHit = true;\n throw handleError(\n \"ACTION_LIMIT_EXCEEDED\",\n `an action may make at most ${cfg.limits.db_calls} database calls`\n );\n }\n const body = requestBody(op, payload, cfg.limits);\n const pending = send(op, body);\n state.inflight.add(pending);\n try {\n return await pending;\n } finally {\n state.inflight.delete(pending);\n }\n }\n return { state, call };\n}\nfunction settleCall(caller, op, payload) {\n return settleWith(\n () => caller.call(op, payload),\n \"ACTION_DB_UNAVAILABLE\",\n \"the database call failed\"\n );\n}\nasync function settleWith(run, fallbackCode, fallbackMessage) {\n try {\n return { ok: true, value: await run() };\n } catch (err) {\n const { code, message } = err ?? {};\n return {\n ok: false,\n error: {\n code: typeof code === \"string\" ? code : fallbackCode,\n message: typeof message === \"string\" ? message : fallbackMessage\n }\n };\n }\n}\nasync function settle(caller, deadlineMs, now = Date.now) {\n caller.state.revoked = true;\n const inflight = [...caller.state.inflight];\n if (inflight.length === 0) return true;\n const remaining = deadlineMs - now();\n if (remaining > 0) {\n let timer = null;\n await Promise.race([\n Promise.allSettled(inflight),\n new Promise((r) => {\n timer = setTimeout(r, remaining);\n })\n ]);\n if (timer !== null) clearTimeout(timer);\n }\n return caller.state.inflight.size === 0;\n}\n\n// ../actions-worker/src/clip-caller.ts\nvar ENVELOPE_BYTES = 64 * 1024;\nvar MAX_FIELD_BYTES = 256;\nvar encoder2 = new TextEncoder();\nfunction unknownOutcome() {\n return handleError(\n \"OUTCOME_UNKNOWN\",\n \"the Clip call\\u2019s answer was lost \\u2014 it may or may not have run; do not retry it blindly\"\n );\n}\nfunction field(v, required) {\n if (v === void 0 || v === null) return required ? null : void 0;\n if (typeof v !== \"string\" || encoder2.encode(v).byteLength > MAX_FIELD_BYTES) return null;\n if (required && v.trim() === \"\") return null;\n return v;\n}\nfunction requestBody2(req, seq, maxBytes) {\n const r = typeof req === \"object\" && req !== null ? req : {};\n const clip = field(r.clip, true);\n const command = field(r.command, true);\n const connection = field(r.connection, false);\n const profile = field(r.profile, false);\n const timeout = r.timeout_ms;\n if (clip === null || command === null || connection === null || profile === null) {\n throw handleError(\n \"ACTION_INVALID_CALL\",\n \"clip.exec needs a Clip name or id, a command, and string connection and profile options of at most 256 bytes\"\n );\n }\n if (timeout !== void 0 && (typeof timeout !== \"number\" || !Number.isInteger(timeout) || timeout <= 0 || timeout > 12e4)) {\n throw handleError(\n \"ACTION_INVALID_CALL\",\n \"timeoutMs must be a whole number of milliseconds from 1 to 120000\"\n );\n }\n let body;\n try {\n body = JSON.stringify({\n seq,\n clip,\n command,\n args: r.args,\n connection: connection ?? \"\",\n profile,\n timeout_ms: timeout\n });\n } catch {\n throw handleError(\"ACTION_INVALID_CALL\", \"the Clip arguments cannot be sent as JSON\");\n }\n if (encoder2.encode(body).byteLength > maxBytes) {\n throw handleError(\n \"ACTION_LIMIT_EXCEEDED\",\n `a Clip call's arguments may be at most ${maxBytes} bytes`\n );\n }\n return body;\n}\nfunction createClipCaller(cfg, state) {\n const fetchImpl = cfg.fetchImpl ?? fetch;\n const now = cfg.now ?? Date.now;\n const url = `${cfg.callbackOrigin.replace(/\\/+$/, \"\")}/api/v1/mini-app-actions/clip/exec`;\n async function send(body) {\n const headers = {\n \"Content-Type\": \"application/json\",\n \"User-Agent\": USER_AGENT,\n [TICKET_HEADER]: cfg.ticket,\n [INVOCATION_HEADER]: cfg.invocationId\n };\n if (cfg.instance !== \"default\") headers[SWIMLANE_HEADER] = cfg.instance;\n let res;\n try {\n res = await fetchImpl(url, {\n method: \"POST\",\n headers,\n body,\n signal: AbortSignal.timeout(Math.max(1, cfg.deadlineMs - now()))\n });\n } catch {\n throw unknownOutcome();\n }\n let parsed;\n try {\n const text = await readCapped(res, cfg.maxBytes + ENVELOPE_BYTES);\n parsed = text ? JSON.parse(text) : null;\n } catch {\n throw unknownOutcome();\n }\n if (res.ok) {\n const a = parsed;\n if (a?.ok === true) return a.value ?? null;\n if (a?.ok === false && typeof a.error?.code === \"string\") {\n throw handleError(\n a.error.code,\n typeof a.error.message === \"string\" ? a.error.message : a.error.code\n );\n }\n throw unknownOutcome();\n }\n const env = parsed?.error;\n if (typeof env?.code !== \"string\") throw unknownOutcome();\n throw handleError(\n env.code,\n typeof env.message === \"string\" ? env.message : `Clip call refused (${res.status})`\n );\n }\n async function call(req) {\n if (state.revoked) throw handleError(\"ACTION_HANDLE_REVOKED\", \"this handle is no longer valid\");\n if (!cfg.enabled) {\n throw handleError(\n \"CLIP_NOT_DECLARED\",\n \"this action does not declare clip, so it cannot call Clip\"\n );\n }\n if (now() >= cfg.deadlineMs)\n throw handleError(\"ACTION_DEADLINE\", \"the action ran past its deadline\");\n if (state.clipCalls >= cfg.maxCalls) {\n state.clipLimitHit = true;\n throw handleError(\n \"ACTION_LIMIT_EXCEEDED\",\n `an action may make at most ${cfg.maxCalls} Clip calls`\n );\n }\n const body = requestBody2(req, state.clipCalls + 1, cfg.maxBytes);\n state.clipCalls++;\n const pending = send(body);\n state.inflight.add(pending);\n try {\n return await pending;\n } finally {\n state.inflight.delete(pending);\n }\n }\n return { call };\n}\n\n// ../actions-worker/src/handle.ts\nimport { RpcTarget } from \"cloudflare:workers\";\nvar ActionHandle = class extends RpcTarget {\n #caller;\n #clip;\n constructor(caller, clip) {\n super();\n this.#caller = caller;\n this.#clip = clip;\n }\n query(sql, params) {\n return settleCall(this.#caller, \"query\", { sql, params });\n }\n exec(sql, params) {\n return settleCall(this.#caller, \"exec\", { sql, params });\n }\n batch(statements) {\n return settleCall(this.#caller, \"batch\", { statements });\n }\n clip(req) {\n return settleWith(() => this.#clip.call(req), \"CLIP_UNAVAILABLE\", \"the Clip call failed\");\n }\n};\nfunction makeHandle(caller, clip) {\n return new ActionHandle(caller, clip);\n}\n\n// ../actions-worker/src/outcome.ts\nvar encoder3 = new TextEncoder();\nfunction truncateBytes(s, maxBytes) {\n const bytes = encoder3.encode(s);\n if (bytes.byteLength <= maxBytes) return s;\n return new TextDecoder().decode(bytes.subarray(0, maxBytes)).replace(/�+$/u, \"\");\n}\nfunction base(state) {\n return { db_calls: state.calls, data_seq: state.dataSeq, clip_calls: state.clipCalls };\n}\nfunction failed(state, error) {\n if (state.limitHit || state.clipLimitHit) {\n return {\n status: \"limit_exceeded\",\n error: {\n kind: \"limit\",\n message: state.limitHit ? \"the action made more database calls than allowed\" : \"the action made more Clip calls than allowed\"\n },\n ...base(state)\n };\n }\n return { status: \"failed\", error, ...base(state) };\n}\nfunction asString(v) {\n return typeof v === \"string\" ? v : \"\";\n}\nfunction outcomeFromResult(raw, limits, state) {\n if (typeof raw === \"object\" && raw !== null && !Array.isArray(raw)) {\n const r = raw;\n if (r.ok === true && typeof r.json === \"string\") {\n if (encoder3.encode(r.json).byteLength > limits.result_bytes) {\n return failed(state, {\n kind: \"unexpected\",\n message: `the action result is larger than ${limits.result_bytes} bytes`\n });\n }\n return { status: \"ok\", result_json: r.json, ...base(state) };\n }\n if (r.ok === false && typeof r.error === \"object\" && r.error !== null) {\n const e = r.error;\n if (e.kind === \"action_error\") {\n return failed(state, {\n kind: \"action_error\",\n message: truncateBytes(asString(e.message), limits.message_bytes)\n });\n }\n return failed(state, {\n kind: \"unexpected\",\n message: truncateBytes(asString(e.message), limits.message_bytes),\n stack: truncateBytes(asString(e.stack), limits.stack_bytes)\n });\n }\n }\n return failed(state, {\n kind: \"unexpected\",\n message: \"the action returned a result in an unknown shape\"\n });\n}\nvar CPU_LIMIT = /exceeded (its )?cpu|cpu time limit|exceeded resource limits/i;\nfunction isCpuLimitError(err) {\n const message = err instanceof Error ? err.message : String(err);\n return CPU_LIMIT.test(message);\n}\nfunction outcomeFromThrown(err, limits, state) {\n if (isCpuLimitError(err)) {\n return {\n status: \"limit_exceeded\",\n error: { kind: \"limit\", message: \"the action ran past its CPU time limit\" },\n ...base(state)\n };\n }\n const message = err instanceof Error ? `${err.name}: ${err.message}` : String(err);\n return failed(state, {\n kind: \"unexpected\",\n message: truncateBytes(message, limits.message_bytes)\n });\n}\nfunction timeoutOutcome(state) {\n return {\n status: \"timeout\",\n error: {\n kind: \"timeout\",\n message: \"the action ran past its deadline or lost a database answer; writes it started may have committed\"\n },\n ...base(state)\n };\n}\n\n// ../actions-worker/src/sandbox.ts\nvar COMPATIBILITY_DATE = \"2026-04-01\";\nvar COMPATIBILITY_FLAGS = [];\nvar ENTRYPOINT = \"ActionRunner\";\nvar PRELUDE = `// Runs before the author module (see actions-worker src/sandbox.ts).\nfor (const name of ['caches', 'WebSocket']) {\n try {\n delete globalThis[name];\n } catch {}\n if (name in globalThis) {\n Object.defineProperty(globalThis, name, { value: undefined, writable: false, configurable: false });\n }\n}\n`;\nvar ENTRY = `import './prelude.js';\nexport * from './author.js';\n`;\nfunction workerCode(authorSource) {\n return {\n compatibilityDate: COMPATIBILITY_DATE,\n compatibilityFlags: COMPATIBILITY_FLAGS,\n mainModule: \"entry.js\",\n modules: { \"entry.js\": ENTRY, \"prelude.js\": PRELUDE, \"author.js\": authorSource },\n env: {},\n globalOutbound: null\n };\n}\nvar runtimeVersion = null;\nfunction runtimeVersionOf() {\n if (!runtimeVersion) {\n const material = JSON.stringify([\n COMPATIBILITY_DATE,\n COMPATIBILITY_FLAGS,\n ENTRYPOINT,\n PRELUDE,\n ENTRY,\n \"env:{}\",\n \"outbound:null\"\n ]);\n runtimeVersion = crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(material)).then(\n (d) => Array.from(new Uint8Array(d).slice(0, 8), (b) => b.toString(16).padStart(2, \"0\")).join(\"\")\n );\n }\n return runtimeVersion;\n}\nfunction isolateId(instance, appId, sha256, runtime) {\n return `${instance}:${appId}:${sha256}:${runtime}`;\n}\n\n// ../actions-worker/src/run.ts\nvar DEADLINE_MARGIN_MS = 250;\nasync function runWithDeadline(call, budgetMs) {\n if (budgetMs <= 0) return { kind: \"timeout\" };\n let timer = null;\n const timedOut = new Promise((resolve) => {\n timer = setTimeout(() => resolve({ kind: \"timeout\" }), budgetMs);\n });\n try {\n return await Promise.race([\n call().then(\n (value) => ({ kind: \"result\", value }),\n (error) => ({ kind: \"thrown\", error })\n ),\n timedOut\n ]);\n } finally {\n if (timer !== null) clearTimeout(timer);\n }\n}\nasync function runInvocation(worker, req, callbackOrigin, loadFailure = () => null) {\n const effectiveDeadline = req.deadline_ms - DEADLINE_MARGIN_MS;\n const caller = createDbCaller({\n kind: req.kind,\n ticket: req.ticket,\n invocationId: req.invocation_id,\n instance: req.instance,\n callbackOrigin,\n deadlineMs: effectiveDeadline,\n limits: req.limits\n });\n const clip = createClipCaller(\n {\n enabled: req.clip,\n ticket: req.ticket,\n invocationId: req.invocation_id,\n instance: req.instance,\n callbackOrigin,\n deadlineMs: effectiveDeadline,\n maxCalls: req.limits.clip_calls,\n maxBytes: req.limits.result_bytes\n },\n caller.state\n );\n const handle = makeHandle(caller, clip);\n const entry = worker.getEntrypoint(ENTRYPOINT, { limits: { cpuMs: req.limits.cpu_ms } });\n const settled = await runWithDeadline(\n () => entry.run(\n {\n action: req.action,\n params: req.params,\n viewer: req.viewer,\n app: req.app,\n invocation_id: req.invocation_id\n },\n handle\n ),\n effectiveDeadline - Date.now()\n );\n const drained = await settle(caller, effectiveDeadline);\n if (settled.kind === \"timeout\" || !drained || caller.state.indeterminate) {\n return timeoutOutcome(caller.state);\n }\n if (settled.kind === \"thrown\") {\n return loadFailure() ?? outcomeFromThrown(settled.error, req.limits, caller.state);\n }\n return outcomeFromResult(settled.value, req.limits, caller.state);\n}\n\n// ../actions-worker/src/local.ts\nvar local_default = {\n async fetch(request, env) {\n let body;\n try {\n body = await request.json();\n } catch {\n return Response.json({ error: \"body is not JSON\" }, { status: 400 });\n }\n const req = parseInvokeRequest(body?.request, { unpublished: true });\n if (typeof req === \"string\") return Response.json({ error: `invalid ${req}` }, { status: 400 });\n if (typeof body.source !== \"string\" || typeof body.callback_origin !== \"string\") {\n return Response.json({ error: \"source and callback_origin are required\" }, { status: 400 });\n }\n const runtime = await runtimeVersionOf();\n const worker = env.LOADER.get(\n isolateId(req.instance, req.app.id, req.module.sha256, runtime),\n async () => workerCode(body.source)\n );\n return Response.json(await runInvocation(worker, req, body.callback_origin));\n }\n};\nexport {\n local_default as default\n};\n";
@@ -1 +1 @@
1
- {"version":3,"file":"apps.d.ts","sourceRoot":"","sources":["../../src/commands/apps.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAUzC;;;;;;;;;qBASqB;AACrB,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,OAAO,QA6KnD"}
1
+ {"version":3,"file":"apps.d.ts","sourceRoot":"","sources":["../../src/commands/apps.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAUzC;;;;;;;;;qBASqB;AACrB,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,OAAO,QA8LnD"}
@@ -118,6 +118,21 @@ export function registerAppCommands(program) {
118
118
  printError(err);
119
119
  }
120
120
  });
121
+ app
122
+ .command('delete')
123
+ .description('Delete a Mini App (org owner/admin only, not its authors). It is gone at once — no one can open it or call its actions — its Database stays, and its versions and files are removed after 30 days')
124
+ .argument('<appId>', 'App ID')
125
+ .action(async (appId) => {
126
+ try {
127
+ const { client, orgId } = resolveCredentials();
128
+ const id = stripPrllScheme(appId);
129
+ await client.deleteMiniApp(orgId, id);
130
+ console.error(`Deleted ${id}`);
131
+ }
132
+ catch (err) {
133
+ printError(err);
134
+ }
135
+ });
121
136
  app
122
137
  .command('restore')
123
138
  .description("Restore an archived Mini App (the app's author or an org owner/admin)")
@@ -29,8 +29,7 @@ export interface DataPlaneBinding {
29
29
  * read role; exec runs one or more statements in a single transaction as
30
30
  * the write role, or as the owner role with a snapshot first when the SQL
31
31
  * is a schema change. Destructive DDL and restores issued by an agent are
32
- * refused with DB_DDL_APPROVAL_REQUIRED while the Database requires
33
- * org owner/admin approval. */
32
+ * always refused with DB_DDL_APPROVAL_REQUIRED. */
34
33
  export declare function registerDataPlaneCommands(group: Command, binding: DataPlaneBinding): void;
35
34
  /** Each --param is a JSON value when it parses as one, else the bare text.
36
35
  * The server binds every value as text and lets PostgreSQL parse it against
@@ -1 +1 @@
1
- {"version":3,"file":"db-plane.d.ts","sourceRoot":"","sources":["../../src/commands/db-plane.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAUV,eAAe,EAEhB,MAAM,aAAa,CAAC;AACrB,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACzC,OAAO,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAItD,KAAK,GAAG,GAAG,UAAU,CAAC,OAAO,kBAAkB,CAAC,CAAC;AAEjD;4EAC4E;AAC5E,MAAM,WAAW,eAAe;IAC9B,IAAI,EAAE,KAAK,GAAG,IAAI,CAAC;IACnB,EAAE,EAAE,MAAM,CAAC;CACZ;AAED;gEACgE;AAChE,MAAM,WAAW,gBAAgB;IAC/B,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,MAAM,CAAC;IACjB;qBACiB;IACjB,YAAY,CAAC,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IACrD,OAAO,CAAC,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,GAAG,OAAO,CAAC,eAAe,CAAC,CAAC;CACvF;AAED;;;;;;;;;+BAS+B;AAC/B,wBAAgB,yBAAyB,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,gBAAgB,QA2JlF;AAgED;;;4BAG4B;AAC5B,wBAAgB,WAAW,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,SAAS,GAAG,eAAe,EAAE,GAAG,SAAS,CASpF"}
1
+ {"version":3,"file":"db-plane.d.ts","sourceRoot":"","sources":["../../src/commands/db-plane.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAUV,eAAe,EAEhB,MAAM,aAAa,CAAC;AACrB,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACzC,OAAO,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAItD,KAAK,GAAG,GAAG,UAAU,CAAC,OAAO,kBAAkB,CAAC,CAAC;AAEjD;4EAC4E;AAC5E,MAAM,WAAW,eAAe;IAC9B,IAAI,EAAE,KAAK,GAAG,IAAI,CAAC;IACnB,EAAE,EAAE,MAAM,CAAC;CACZ;AAED;gEACgE;AAChE,MAAM,WAAW,gBAAgB;IAC/B,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,MAAM,CAAC;IACjB;qBACiB;IACjB,YAAY,CAAC,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IACrD,OAAO,CAAC,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,GAAG,OAAO,CAAC,eAAe,CAAC,CAAC;CACvF;AAED;;;;;;;;mDAQmD;AACnD,wBAAgB,yBAAyB,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,gBAAgB,QA2JlF;AAgED;;;4BAG4B;AAC5B,wBAAgB,WAAW,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,SAAS,GAAG,eAAe,EAAE,GAAG,SAAS,CASpF"}
@@ -10,8 +10,7 @@ import { resolveApiToken } from '../lib/wiki-shared.js';
10
10
  * read role; exec runs one or more statements in a single transaction as
11
11
  * the write role, or as the owner role with a snapshot first when the SQL
12
12
  * is a schema change. Destructive DDL and restores issued by an agent are
13
- * refused with DB_DDL_APPROVAL_REQUIRED while the Database requires
14
- * org owner/admin approval. */
13
+ * always refused with DB_DDL_APPROVAL_REQUIRED. */
15
14
  export function registerDataPlaneCommands(group, binding) {
16
15
  const withTarget = (cmd) => {
17
16
  cmd.requiredOption(binding.flag, binding.flagHelp);
@@ -1 +1 @@
1
- {"version":3,"file":"dbs.d.ts","sourceRoot":"","sources":["../../src/commands/dbs.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACzC,OAAO,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAOtD;;;;;;;;8EAQ8E;AAC9E,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,OAAO,QAsHlD;AASD;yBACyB;AACzB,wBAAsB,iBAAiB,CACrC,GAAG,EAAE,UAAU,CAAC,OAAO,kBAAkB,CAAC,EAC1C,QAAQ,EAAE,MAAM,GACf,OAAO,CAAC,MAAM,CAAC,CAYjB"}
1
+ {"version":3,"file":"dbs.d.ts","sourceRoot":"","sources":["../../src/commands/dbs.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACzC,OAAO,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAOtD;;;;;;;;8EAQ8E;AAC9E,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,OAAO,QAgGlD;AASD;yBACyB;AACzB,wBAAsB,iBAAiB,CACrC,GAAG,EAAE,UAAU,CAAC,OAAO,kBAAkB,CAAC,EAC1C,QAAQ,EAAE,MAAM,GACf,OAAO,CAAC,MAAM,CAAC,CAYjB"}
@@ -52,16 +52,12 @@ export function registerDbCommands(program) {
52
52
  .option('--project <projectId>', DEPRECATED_PROJECT)
53
53
  .requiredOption('--name <name>', 'Database name (unique in the organization)')
54
54
  .option('--description <text>', 'Description')
55
- .option('--agent-destructive-requires-approval <bool>', 'true (default) = destructive DDL and restores by an agent need org owner/admin approval')
56
55
  .action(async (opts) => {
57
56
  try {
58
57
  const { client, orgId } = resolveCredentials();
59
58
  const data = { name: opts.name };
60
59
  if (opts.description)
61
60
  data.description = opts.description;
62
- if (opts.agentDestructiveRequiresApproval !== undefined) {
63
- data.agent_destructive_requires_approval = parseBoolFlag('--agent-destructive-requires-approval', opts.agentDestructiveRequiresApproval);
64
- }
65
61
  const result = await client.createMiniAppDatabase(orgId, data);
66
62
  printJson(result);
67
63
  printRefHint(result.id);
@@ -76,7 +72,6 @@ export function registerDbCommands(program) {
76
72
  .option('--project <projectId>', DEPRECATED_PROJECT)
77
73
  .option('--name <name>', 'New name')
78
74
  .option('--description <text>', 'New description (empty string clears)')
79
- .option('--agent-destructive-requires-approval <bool>', 'true (default) = destructive DDL and restores by an agent need org owner/admin approval')
80
75
  .action(async (idOrName, opts) => {
81
76
  try {
82
77
  const ctx = resolveCredentials();
@@ -85,11 +80,8 @@ export function registerDbCommands(program) {
85
80
  data.name = opts.name;
86
81
  if (opts.description !== undefined)
87
82
  data.description = opts.description;
88
- if (opts.agentDestructiveRequiresApproval !== undefined) {
89
- data.agent_destructive_requires_approval = parseBoolFlag('--agent-destructive-requires-approval', opts.agentDestructiveRequiresApproval);
90
- }
91
83
  if (Object.keys(data).length === 0) {
92
- throw new Error('Nothing to update: pass at least one of --name, --description, --agent-destructive-requires-approval');
84
+ throw new Error('Nothing to update: pass --name or --description');
93
85
  }
94
86
  const id = await resolveDatabaseId(ctx, idOrName);
95
87
  printJson(await ctx.client.updateMiniAppDatabase(ctx.orgId, id, data));
@@ -132,9 +124,3 @@ export async function resolveDatabaseId(ctx, idOrName) {
132
124
  }
133
125
  return match.id;
134
126
  }
135
- function parseBoolFlag(flag, value) {
136
- if (value !== 'true' && value !== 'false') {
137
- throw new Error(`${flag} must be true or false`);
138
- }
139
- return value === 'true';
140
- }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@parall/cli",
3
- "version": "1.71.0",
3
+ "version": "1.73.0",
4
4
  "description": "CLI client for Parall — universal agent & human access to Parall API",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -42,8 +42,8 @@
42
42
  "node-diff3": "3.2.1",
43
43
  "tar-stream": "^3.2.1",
44
44
  "zod": "^4.3.6",
45
- "@parall/agent-core": "1.71.0",
46
- "@parall/sdk": "1.71.0"
45
+ "@parall/agent-core": "1.73.0",
46
+ "@parall/sdk": "1.73.0"
47
47
  },
48
48
  "devDependencies": {
49
49
  "@types/js-yaml": "^4.0.9",
@@ -51,7 +51,7 @@
51
51
  "@types/tar-stream": "^3.1.4",
52
52
  "esbuild": "^0.25.0",
53
53
  "typescript": "^5.7.0",
54
- "@parall/agent-core": "1.71.0"
54
+ "@parall/agent-core": "1.73.0"
55
55
  },
56
56
  "scripts": {
57
57
  "build": "node scripts/generate-miniapp-sdk.mjs --check && node scripts/generate-local-runner.mjs --check && tsc",