@parall/cli 1.75.0 → 1.76.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.
- package/dist/commands/approvals.d.ts.map +1 -1
- package/dist/commands/approvals.js +40 -13
- package/dist/commands/apps-action-local.d.ts +6 -1
- package/dist/commands/apps-action-local.d.ts.map +1 -1
- package/dist/commands/apps-action-local.js +11 -2
- package/dist/commands/apps-actions-sdk.generated.d.ts +1 -1
- package/dist/commands/apps-actions-sdk.generated.d.ts.map +1 -1
- package/dist/commands/apps-actions-sdk.generated.js +1 -1
- package/dist/commands/apps-actions.d.ts.map +1 -1
- package/dist/commands/apps-actions.js +13 -15
- package/dist/commands/apps-add.js +2 -2
- package/dist/commands/apps-args.d.ts +22 -0
- package/dist/commands/apps-args.d.ts.map +1 -0
- package/dist/commands/apps-args.js +62 -0
- package/dist/commands/apps-check.d.ts.map +1 -1
- package/dist/commands/apps-check.js +8 -3
- package/dist/commands/apps-db.d.ts +3 -1
- package/dist/commands/apps-db.d.ts.map +1 -1
- package/dist/commands/apps-db.js +4 -7
- package/dist/commands/apps-dev-server.d.ts +3 -0
- package/dist/commands/apps-dev-server.d.ts.map +1 -1
- package/dist/commands/apps-dev-server.js +4 -0
- package/dist/commands/apps-dev-vars.d.ts +38 -0
- package/dist/commands/apps-dev-vars.d.ts.map +1 -0
- package/dist/commands/apps-dev-vars.js +107 -0
- package/dist/commands/apps-dev.d.ts.map +1 -1
- package/dist/commands/apps-dev.js +2 -1
- package/dist/commands/apps-local-runner.generated.d.ts +2 -1
- package/dist/commands/apps-local-runner.generated.d.ts.map +1 -1
- package/dist/commands/apps-local-runner.generated.js +2 -1
- package/dist/commands/apps-publish.d.ts +3 -1
- package/dist/commands/apps-publish.d.ts.map +1 -1
- package/dist/commands/apps-publish.js +27 -23
- package/dist/commands/apps-templates.gen.js +3 -3
- package/dist/commands/apps.d.ts.map +1 -1
- package/dist/commands/apps.js +35 -40
- package/dist/commands/comments.d.ts.map +1 -1
- package/dist/commands/comments.js +3 -2
- package/dist/commands/db-plane.d.ts +5 -14
- package/dist/commands/db-plane.d.ts.map +1 -1
- package/dist/commands/db-plane.js +63 -32
- package/dist/commands/db-target.d.ts +22 -0
- package/dist/commands/db-target.d.ts.map +1 -0
- package/dist/commands/db-target.js +43 -0
- package/dist/commands/dbs.d.ts +3 -6
- package/dist/commands/dbs.d.ts.map +1 -1
- package/dist/commands/dbs.js +28 -34
- package/dist/commands/secrets.d.ts +3 -0
- package/dist/commands/secrets.d.ts.map +1 -0
- package/dist/commands/secrets.js +66 -0
- package/dist/index.js +18 -2
- package/dist/lib/approvers.d.ts +12 -0
- package/dist/lib/approvers.d.ts.map +1 -0
- package/dist/lib/approvers.js +48 -0
- package/dist/lib/output.d.ts +19 -0
- package/dist/lib/output.d.ts.map +1 -1
- package/dist/lib/output.js +59 -2
- package/dist/lib/update-check.d.ts +4 -0
- package/dist/lib/update-check.d.ts.map +1 -1
- package/dist/lib/update-check.js +3 -1
- package/package.json +4 -4
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"approvals.d.ts","sourceRoot":"","sources":["../../src/commands/approvals.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;
|
|
1
|
+
{"version":3,"file":"approvals.d.ts","sourceRoot":"","sources":["../../src/commands/approvals.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAiBpC,wBAAgB,wBAAwB,CAAC,OAAO,EAAE,OAAO,QA8KxD"}
|
|
@@ -1,5 +1,16 @@
|
|
|
1
|
+
import { printApprovers, printFiledApproval } from '../lib/approvers.js';
|
|
1
2
|
import { resolveCredentials } from '../lib/client.js';
|
|
2
|
-
import { printJson, printError,
|
|
3
|
+
import { printJson, printError, stripPrllScheme } from '../lib/output.js';
|
|
4
|
+
const PAYLOAD_HELP = 'Frozen action payload as a JSON object (run `parall approvals actions` for the exact keys an action expects)';
|
|
5
|
+
function parsePayload(raw) {
|
|
6
|
+
if (!raw)
|
|
7
|
+
return undefined;
|
|
8
|
+
const parsed = JSON.parse(raw);
|
|
9
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
|
10
|
+
throw new Error('--payload must be a JSON object');
|
|
11
|
+
}
|
|
12
|
+
return parsed;
|
|
13
|
+
}
|
|
3
14
|
export function registerApprovalCommands(program) {
|
|
4
15
|
const approvals = program.command('approvals').description('Manage approval requests');
|
|
5
16
|
approvals
|
|
@@ -10,28 +21,43 @@ export function registerApprovalCommands(program) {
|
|
|
10
21
|
.requiredOption('--chat <chatId>', 'Chat to post the approval card in (e.g. prll://cht_456)')
|
|
11
22
|
.requiredOption('--title <title>', 'Human-readable title for the request')
|
|
12
23
|
.option('--reason <text>', 'Why this action is needed')
|
|
13
|
-
.option('--payload <json>',
|
|
24
|
+
.option('--payload <json>', PAYLOAD_HELP)
|
|
14
25
|
.action(async (opts) => {
|
|
15
26
|
try {
|
|
16
27
|
const { client, orgId } = resolveCredentials();
|
|
17
|
-
let actionPayload;
|
|
18
|
-
if (opts.payload) {
|
|
19
|
-
const parsed = JSON.parse(opts.payload);
|
|
20
|
-
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
|
21
|
-
throw new Error('--payload must be a JSON object');
|
|
22
|
-
}
|
|
23
|
-
actionPayload = parsed;
|
|
24
|
-
}
|
|
25
28
|
const result = await client.requestApproval(orgId, {
|
|
26
29
|
action_type: opts.action,
|
|
27
30
|
resource_uri: opts.resource,
|
|
28
|
-
action_payload:
|
|
31
|
+
action_payload: parsePayload(opts.payload),
|
|
29
32
|
chat_id: stripPrllScheme(opts.chat),
|
|
30
33
|
title: opts.title,
|
|
31
34
|
reason: opts.reason,
|
|
32
35
|
});
|
|
33
36
|
printJson(result);
|
|
34
|
-
|
|
37
|
+
printFiledApproval(result, result.deduplicated ? 'Already waiting' : 'Created');
|
|
38
|
+
}
|
|
39
|
+
catch (err) {
|
|
40
|
+
printError(err);
|
|
41
|
+
}
|
|
42
|
+
});
|
|
43
|
+
approvals
|
|
44
|
+
.command('approvers')
|
|
45
|
+
.description('Who can approve an action, and whether they are in a chat — check before requesting')
|
|
46
|
+
.requiredOption('--action <type>', 'Action type (e.g. chat.archive)')
|
|
47
|
+
.requiredOption('--resource <uri>', 'Resource URI (e.g. prll://cht_123)')
|
|
48
|
+
.option('--chat <chatId>', 'Chat you would post the card in; marks who is in it')
|
|
49
|
+
.option('--payload <json>', PAYLOAD_HELP)
|
|
50
|
+
.action(async (opts) => {
|
|
51
|
+
try {
|
|
52
|
+
const { client, orgId } = resolveCredentials();
|
|
53
|
+
const result = await client.listApprovers(orgId, {
|
|
54
|
+
action_type: opts.action,
|
|
55
|
+
resource_uri: opts.resource,
|
|
56
|
+
action_payload: parsePayload(opts.payload),
|
|
57
|
+
...(opts.chat ? { chat_id: stripPrllScheme(opts.chat) } : {}),
|
|
58
|
+
});
|
|
59
|
+
printJson(result);
|
|
60
|
+
printApprovers(result.approvers, result.warnings);
|
|
35
61
|
}
|
|
36
62
|
catch (err) {
|
|
37
63
|
printError(err);
|
|
@@ -44,8 +70,9 @@ export function registerApprovalCommands(program) {
|
|
|
44
70
|
.action(async (approvalId) => {
|
|
45
71
|
try {
|
|
46
72
|
const { client } = resolveCredentials();
|
|
47
|
-
const result = await client.
|
|
73
|
+
const result = await client.getApprovalWithApprovers(stripPrllScheme(approvalId));
|
|
48
74
|
printJson(result);
|
|
75
|
+
printApprovers(result.approvers, result.warnings, result.id);
|
|
49
76
|
}
|
|
50
77
|
catch (err) {
|
|
51
78
|
printError(err);
|
|
@@ -12,7 +12,12 @@ import type { resolveCredentials } from '../lib/client.js';
|
|
|
12
12
|
*
|
|
13
13
|
* The module is never loaded in this process: it holds the caller's
|
|
14
14
|
* credentials, and the module's top-level code is to run only in the
|
|
15
|
-
* sandbox.
|
|
15
|
+
* sandbox.
|
|
16
|
+
*
|
|
17
|
+
* Outbound requests (ctx.fetch) follow the deployed rules — the dispatch's
|
|
18
|
+
* limits, the loaders' address list — but leave straight from this machine,
|
|
19
|
+
* with no record; ctx.env is the project's .dev.vars
|
|
20
|
+
* (docs/engineering-design/mini-app-network-design.md §7.6). */
|
|
16
21
|
export interface LocalAction {
|
|
17
22
|
/** The action's entry in the build's manifest, as declared. */
|
|
18
23
|
declaration: unknown;
|
|
@@ -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;
|
|
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;AAU3D;;;;;;;;;;;;;;;;;gEAiBgE;AAEhE,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,CAyEpC"}
|
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import { createRequire } from 'node:module';
|
|
2
|
-
import { join } from 'node:path';
|
|
2
|
+
import { dirname, join } from 'node:path';
|
|
3
3
|
import { pathToFileURL } from 'node:url';
|
|
4
4
|
import { ApiError, } from '@parall/sdk';
|
|
5
5
|
import { readActionModule } from './apps-check.js';
|
|
6
|
+
import { DEV_VARS_FILE, readDevVars } from './apps-dev-vars.js';
|
|
7
|
+
import { LOCAL_RUNNER_BLOCKED_HOSTS, LOCAL_RUNNER_COMPATIBILITY_DATE, LOCAL_RUNNER_SOURCE, } from './apps-local-runner.generated.js';
|
|
6
8
|
import { MINIFLARE_RANGE } from './apps-scaffold-actions.js';
|
|
7
|
-
import { LOCAL_RUNNER_COMPATIBILITY_DATE, LOCAL_RUNNER_SOURCE, } from './apps-local-runner.generated.js';
|
|
8
9
|
/** The action as the local build declares it. Whether the module implements
|
|
9
10
|
* it shows when it runs; `parall app check` compares the two. */
|
|
10
11
|
export async function readLocalAction(dist, name) {
|
|
@@ -31,11 +32,18 @@ const RUNNER_GRACE_MS = 5_000;
|
|
|
31
32
|
* ApiError a deployed call raises, with the details an author sees. */
|
|
32
33
|
export async function runLocalAction(client, orgId, appId, apiUrl, dist, name, action, params, observe = {}) {
|
|
33
34
|
const Miniflare = await loadMiniflare(dist);
|
|
35
|
+
// Read on every run, so an edit takes effect without a restart. The
|
|
36
|
+
// project is the build's parent directory, where miniflare is found too.
|
|
37
|
+
const devVars = await readDevVars(dirname(dist));
|
|
38
|
+
for (const note of devVars.skipped) {
|
|
39
|
+
process.stderr.write(`${DEV_VARS_FILE}: skipped ${note}\n`);
|
|
40
|
+
}
|
|
34
41
|
const mf = new Miniflare({
|
|
35
42
|
modules: true,
|
|
36
43
|
script: LOCAL_RUNNER_SOURCE,
|
|
37
44
|
compatibilityDate: LOCAL_RUNNER_COMPATIBILITY_DATE,
|
|
38
45
|
workerLoaders: { LOADER: {} },
|
|
46
|
+
bindings: { NET_BLOCKED_HOSTS: LOCAL_RUNNER_BLOCKED_HOSTS },
|
|
39
47
|
// The action's console output: stderr, so stdout stays the result.
|
|
40
48
|
handleRuntimeStdio(stdout, stderr) {
|
|
41
49
|
stdout.pipe(process.stderr);
|
|
@@ -68,6 +76,7 @@ export async function runLocalAction(client, orgId, appId, apiUrl, dist, name, a
|
|
|
68
76
|
ticket: dev.ticket,
|
|
69
77
|
deadline_ms: dev.deadline_ms,
|
|
70
78
|
limits: dev.limits,
|
|
79
|
+
env: devVars.env,
|
|
71
80
|
};
|
|
72
81
|
const answered = mf.dispatchFetch('http://local/run', {
|
|
73
82
|
method: 'POST',
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export declare const ACTIONS_SDK_SOURCE = "/**\n * @parall/miniapp-sdk/actions \u2014 the action side of a Mini App\n * (docs/engineering-design/mini-app-action-design.md \u00A72): `defineActions`\n * turns the author's functions into the module entry the action loader\n * calls; `ActionError` is the error whose message the caller may see.\n *\n * This file runs inside the Cloudflare isolate, not in the page. It is the\n * only part of the SDK that imports `cloudflare:workers`, and an action\n * module is built from it into one file whose sole external import is that\n * one. Export the result as `ActionRunner` \u2014 the loader looks it up by name:\n *\n * export const ActionRunner = defineActions({\n * async addNote(ctx, { text }) {\n * const { rows } = await ctx.db.exec(\n * 'INSERT INTO notes (text, created_by) VALUES ($1, $2) RETURNING id',\n * [text, ctx.viewer.id],\n * );\n * return rows[0];\n * },\n * });\n *\n * Security does not depend on this wrapper: the loader accepts only the two\n * result shapes run() returns, whatever produced them (design \u00A73.1).\n *\n * An action that declares `\"clip\": true` in the manifest (write actions only)\n * may call Clip as the person who called the action\n * (docs/engineering-design/mini-app-clip-design.md):\n *\n * const profile = await ctx.clip.exec('linkedin', 'get-profile', { id }, { connection: 'sales-li' });\n */\n\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";
|
|
1
|
+
export declare const ACTIONS_SDK_SOURCE = "/**\n * @parall/miniapp-sdk/actions \u2014 the action side of a Mini App\n * (docs/engineering-design/mini-app-action-design.md \u00A72): `defineActions`\n * turns the author's functions into the module entry the action loader\n * calls; `ActionError` is the error whose message the caller may see.\n *\n * This file runs inside the Cloudflare isolate, not in the page. It is the\n * only part of the SDK that imports `cloudflare:workers`, and an action\n * module is built from it into one file whose sole external import is that\n * one. Export the result as `ActionRunner` \u2014 the loader looks it up by name:\n *\n * export const ActionRunner = defineActions({\n * async addNote(ctx, { text }) {\n * const { rows } = await ctx.db.exec(\n * 'INSERT INTO notes (text, created_by) VALUES ($1, $2) RETURNING id',\n * [text, ctx.viewer.id],\n * );\n * return rows[0];\n * },\n * });\n *\n * Security does not depend on this wrapper: the loader accepts only the two\n * result shapes run() returns, whatever produced them (design \u00A73.1).\n *\n * An action that declares `\"clip\": true` in the manifest (write actions only)\n * may call Clip as the person who called the action\n * (docs/engineering-design/mini-app-clip-design.md):\n *\n * const profile = await ctx.clip.exec('linkedin', 'get-profile', { id }, { connection: 'sales-li' });\n *\n * `ctx.fetch` requests a public HTTP(S) address and returns a standard\n * `Response`; `ctx.env` holds the app's secrets by name\n * (docs/engineering-design/mini-app-network-design.md):\n *\n * const res = await ctx.fetch('https://api.example.com/v1/items', {\n * headers: { Authorization: `Bearer ${ctx.env.EXAMPLE_API_KEY}` },\n * });\n * if (!res.ok) throw new ActionError(`the items API answered ${res.status}`);\n * return res.json();\n */\n\nimport { WorkerEntrypoint } from 'cloudflare:workers';\n\n/** An error whose message reaches every caller as is (ACTION_FAILED with\n * error_kind action_error). Anything else thrown is an unexpected failure. */\nexport class ActionError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ActionError';\n }\n}\n\n/** A database call that was refused or failed. `code` is the platform's:\n * SQL_ERROR, SQL_REJECTED, ACTION_READ_ONLY, ACTION_LIMIT_EXCEEDED, \u2026 */\nexport class ActionDbError extends Error {\n readonly code: string;\n\n constructor(code: string, message: string) {\n super(message);\n this.name = 'ActionDbError';\n this.code = code;\n }\n}\n\n/** A Clip call that was refused or failed. `code` is the platform's \u2014 the\n * same codes the caller gets running `parall clip exec` themselves\n * (CONNECTION_NOT_ALLOWED, SCRIPT_ERROR, MCP_TOOL_FAILED, \u2026) \u2014 or the\n * action's own: CLIP_NOT_DECLARED, ACTION_LIMIT_EXCEEDED, ACTION_DEADLINE.\n * OUTCOME_UNKNOWN means the command may have run: never retry it blindly. */\nexport class ClipError extends Error {\n readonly code: string;\n\n constructor(code: string, message: string) {\n super(message);\n this.name = 'ClipError';\n this.code = code;\n }\n}\n\n/** An outbound request (ctx.fetch) that was refused or failed \u2014 an HTTP\n * error status is not one: it comes back as a Response. `code` is the\n * platform's:\n *\n * - not sent: ACTION_INVALID_CALL (the URL, method, headers or body),\n * NET_ADDRESS_BLOCKED (private and loopback addresses, IP literals, the\n * platform's own hosts), ACTION_LIMIT_EXCEEDED (too many requests, or one\n * too large), ACTION_DEADLINE (too little time left), NET_BUSY (the\n * platform is busy; try again shortly), NET_UNAVAILABLE, USER_DISABLED,\n * ACTION_HANDLE_REVOKED;\n * - sent, so it may have reached the server: NET_TIMEOUT, NET_FAILED,\n * NET_RESPONSE_TOO_LARGE (answers are at most 1 MiB).\n *\n * The platform never retries; send an idempotency key where the other side\n * supports one. */\nexport class NetError extends Error {\n readonly code: string;\n\n constructor(code: string, message: string) {\n super(message);\n this.name = 'NetError';\n this.code = code;\n }\n}\n\n/** The caller, as the platform vouches for it (design \u00A72.2). */\nexport interface ActionViewer {\n id: string;\n display_name: string;\n is_agent: boolean;\n /** Organization role: owner, admin or member. */\n role: string;\n}\n\nexport interface ActionApp {\n id: string;\n version_seq: number;\n}\n\n/** A row as an object keyed by column name, in select-list order. */\nexport type ActionRow = Record<string, unknown>;\n\nexport interface ActionQueryResult {\n rows: ActionRow[];\n truncated: boolean;\n}\n\nexport interface ActionStatementResult {\n rows: ActionRow[];\n rows_affected: number;\n truncated: boolean;\n}\n\nexport interface ActionExecResult extends ActionStatementResult {\n data_seq: number;\n}\n\nexport interface ActionBatchStatement {\n sql: string;\n params?: unknown[];\n}\n\nexport interface ActionBatchResult {\n results: ActionStatementResult[];\n data_seq: number;\n}\n\n/** ctx.db: one statement per query / exec; a batch is one transaction. */\nexport interface ActionDb {\n query(sql: string, params?: unknown[]): Promise<ActionQueryResult>;\n /** Write actions only. */\n exec(sql: string, params?: unknown[]): Promise<ActionExecResult>;\n /** Write actions only; at most 50 statements, counted as one call. */\n batch(statements: ActionBatchStatement[]): Promise<ActionBatchResult>;\n}\n\nexport interface ActionClipOptions {\n /** The connection to run on: its alias or ccn_ id. The caller must be\n * allowed to use it, exactly as for their own `parall clip exec`. */\n connection: string;\n profile?: string;\n /** The command's timeout; 30 s by default, cut to what the action's\n * deadline leaves. */\n timeoutMs?: number;\n}\n\n/** ctx.clip: Clip calls as the action's caller; actions that declare clip only. */\nexport interface ActionClip {\n /** Runs a command of a Clip (its name or crg_ id) and returns the Clip's\n * data; throws ClipError. */\n exec(clip: string, command: string, args: unknown, options: ActionClipOptions): Promise<unknown>;\n}\n\n/** ctx.fetch's options: the standard ones \u2014 method, headers, body, signal,\n * redirect \u2014 and the request's timeout. Others (cache, credentials, mode,\n * the Workers `cf`) are not looked at: every request is uncached and carries\n * only what the code sets. */\nexport interface ActionFetchInit extends RequestInit {\n /** This request's timeout; 30 s by default, cut to what the action's\n * deadline leaves. With redirects, each hop has it. */\n timeoutMs?: number;\n}\n\n/** ctx.fetch: a public HTTP(S) request from the platform, recorded in the\n * app's call record (host, method, status, size and time \u2014 never the query\n * string, headers or bodies). Redirects are followed up to 5 times: within\n * the same origin as Fetch does; to another origin with only Accept,\n * Accept-Language, Content-Language and User-Agent kept, and not at all when\n * the next request would carry the body (307, 308, and 301 / 302 for a\n * method other than GET, HEAD or POST) or when it would go from https: to\n * http: \u2014 then the redirect itself comes back. Each hop is a request of its\n * own. At most a few requests run at once; more wait their turn. */\nexport type ActionFetch = (\n input: string | URL | Request,\n init?: ActionFetchInit,\n) => Promise<Response>;\n\nexport interface ActionContext {\n viewer: ActionViewer;\n app: ActionApp;\n db: ActionDb;\n clip: ActionClip;\n fetch: ActionFetch;\n /** The app's secrets by name, as people with the app's publish right set\n * them; read-only. A local run (`parall app action run --local`) reads\n * them from the project's .dev.vars instead. Never pass them as params or\n * write them to the Database or a result. */\n env: Readonly<Record<string, string>>;\n}\n\n// biome-ignore lint/suspicious/noExplicitAny: the platform validates params against the declared schema before the call\nexport type ActionFunction = (ctx: ActionContext, params: any) => unknown;\n\n/** What the loader passes run() (ts/actions-worker src/run.ts). A loader\n * before the network sends neither env nor net_in_flight. */\nexport interface ActionRunRequest {\n action: string;\n params: unknown;\n viewer: ActionViewer;\n app: ActionApp;\n env?: Record<string, string>;\n /** How many requests the handle takes at once. */\n net_in_flight?: number;\n}\n\n/** The only two shapes the loader accepts back (ts/actions-worker src/outcome.ts). */\nexport type ActionRunResult =\n | { ok: true; json: string }\n | { ok: false; error: { kind: 'action_error' | 'unexpected'; message: string; stack?: string } };\n\n/** What a handle method resolves to. Failures travel as values because\n * Workers RPC keeps only an exception's name and message (design \u00A76). */\nexport type ActionHandleResult =\n | { ok: true; value: unknown }\n | { ok: false; error: { code: string; message: string } };\n\n/** What the handle's clip method takes. */\nexport interface ActionHandleClipRequest {\n clip: string;\n command: string;\n args?: unknown;\n connection: string;\n profile?: string;\n timeout_ms?: number;\n}\n\n/** What the handle's request method takes: one request, rebuilt by the\n * loader from exactly these fields. */\nexport interface ActionHandleNetRequest {\n url: string;\n method: string;\n headers: [string, string][];\n body: ArrayBuffer | null;\n timeout_ms?: number;\n}\n\n/** What it answers with on success: the answer, never followed. */\nexport interface ActionHandleNetAnswer {\n status: number;\n status_text: string;\n headers: [string, string][];\n body: ArrayBuffer | null;\n}\n\n/** The per-invocation handle the loader passes run(). A loader before Clip\n * calls has no clip method; one before the network has no request method. */\nexport interface ActionHandle {\n query(sql: string, params: unknown[]): Promise<ActionHandleResult>;\n exec(sql: string, params: unknown[]): Promise<ActionHandleResult>;\n batch(statements: ActionBatchStatement[]): Promise<ActionHandleResult>;\n clip?(req: ActionHandleClipRequest): Promise<ActionHandleResult>;\n request?(req: ActionHandleNetRequest): Promise<ActionHandleResult>;\n}\n\n/** What defineActions returns; export it as `ActionRunner`. */\nexport interface ActionRunnerClass {\n /** The actions the module implements, sorted; `parall app check` compares\n * them with the manifest. */\n readonly actions: readonly string[];\n new (\n ctx: unknown,\n env: unknown,\n ): { run(req: ActionRunRequest, handle: ActionHandle): Promise<ActionRunResult> };\n}\n\nfunction unwrap(result: ActionHandleResult): unknown {\n if (result?.ok === true) return result.value;\n if (result?.ok === false) throw new ActionDbError(result.error.code, result.error.message);\n throw new ActionDbError(\n 'ACTION_DB_UNAVAILABLE',\n 'the database handle answered in an unknown shape',\n );\n}\n\nfunction unwrapClip(result: ActionHandleResult): unknown {\n if (result?.ok === true) return result.value;\n if (result?.ok === false) throw new ClipError(result.error.code, result.error.message);\n throw new ClipError(\n 'OUTCOME_UNKNOWN',\n 'the Clip call answered in an unknown shape; it may or may not have run',\n );\n}\n\nfunction unwrapNet(result: ActionHandleResult): ActionHandleNetAnswer {\n if (result?.ok === false) throw new NetError(result.error.code, result.error.message);\n const a = (result?.ok === true ? result.value : null) as ActionHandleNetAnswer | null;\n if (\n !a ||\n typeof a.status !== 'number' ||\n !Array.isArray(a.headers) ||\n (a.body !== null && !(a.body instanceof ArrayBuffer))\n ) {\n throw new NetError(\n 'NET_FAILED',\n 'the request answered in an unknown shape; it may have reached the server',\n );\n }\n return a;\n}\n\n// Statuses whose Response has no body (Fetch's null body status).\nconst NULL_BODY_STATUS = new Set([101, 103, 204, 205, 304]);\nconst REDIRECT_STATUS = new Set([301, 302, 303, 307, 308]);\n// What a redirect to another origin keeps of the author's headers\n// (mini-app-network-design.md \u00A74): a key may be in any other one.\nconst CROSS_ORIGIN_HEADERS = new Set([\n 'accept',\n 'accept-language',\n 'content-language',\n 'user-agent',\n]);\n// Dropped with the body when a redirect turns the request into a GET.\nconst BODY_HEADERS = new Set([\n 'content-encoding',\n 'content-language',\n 'content-location',\n 'content-type',\n]);\nconst MAX_REDIRECTS = 5;\nconst DEFAULT_IN_FLIGHT = 4;\n\n/** One request of a ctx.fetch: the first, or a redirect's next hop. */\ninterface Hop {\n url: string;\n method: string;\n headers: [string, string][];\n body: ArrayBuffer | null;\n}\n\nfunction headerPairs(headers: Headers): [string, string][] {\n const out: [string, string][] = [];\n headers.forEach((value, name) => {\n out.push([name, value]);\n });\n return out;\n}\n\n/** The first hop, as a standard Request reads the input and init \u2014 only\n * the method, headers and body are taken from them. */\nasync function firstHop(input: string | URL | Request, init: ActionFetchInit | undefined) {\n let request: Request;\n try {\n request = new Request(input, {\n method: init?.method,\n headers: init?.headers,\n body: init?.body,\n });\n } catch (err) {\n throw new NetError(\n 'ACTION_INVALID_CALL',\n `ctx.fetch: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n const hop: Hop = {\n url: request.url,\n method: request.method,\n headers: headerPairs(request.headers),\n body: request.body ? await request.arrayBuffer() : null,\n };\n const fromInput = typeof input === 'object' && 'redirect' in input ? input.redirect : undefined;\n return {\n hop,\n redirect: (init?.redirect ?? fromInput ?? 'follow') as RequestRedirect,\n signal: init?.signal ?? (input instanceof Request ? input.signal : null),\n };\n}\n\n/** The next hop for a redirect, or null when it is not to be followed\n * (mini-app-network-design.md \u00A74). The handle checks the address of every\n * hop: one into a private network or the platform is refused there. */\nfunction nextHop(hop: Hop, status: number, location: string | undefined): Hop | null {\n if (!REDIRECT_STATUS.has(status) || location === undefined) return null;\n let from: URL;\n let to: URL;\n try {\n from = new URL(hop.url);\n to = new URL(location, hop.url);\n } catch {\n return null;\n }\n if (from.protocol === 'https:' && to.protocol === 'http:') return null;\n const sameOrigin = to.origin === from.origin && to.origin !== 'null';\n const toGet =\n (status === 303 && hop.method !== 'GET' && hop.method !== 'HEAD') ||\n ((status === 301 || status === 302) && hop.method === 'POST');\n if (!sameOrigin) {\n // The next request would carry the body to another origin.\n if (status === 307 || status === 308) return null;\n if ((status === 301 || status === 302) && !['GET', 'HEAD', 'POST'].includes(hop.method)) {\n return null;\n }\n }\n let { method, headers, body } = hop;\n if (toGet) {\n method = 'GET';\n body = null;\n headers = headers.filter(([name]) => !BODY_HEADERS.has(name.toLowerCase()));\n }\n if (!sameOrigin)\n headers = headers.filter(([name]) => CROSS_ORIGIN_HEADERS.has(name.toLowerCase()));\n return { url: to.href, method, headers, body };\n}\n\nfunction toResponse(answer: ActionHandleNetAnswer, hop: Hop, redirected: boolean): Response {\n if (answer.status < 200 || answer.status > 599) {\n throw new NetError('NET_FAILED', `the server answered with status ${answer.status}`);\n }\n // As Fetch does: no body for a HEAD request or a null body status.\n const body = hop.method === 'HEAD' || NULL_BODY_STATUS.has(answer.status) ? null : answer.body;\n let res: Response;\n try {\n res = new Response(body, {\n status: answer.status,\n statusText: answer.status_text,\n headers: answer.headers,\n });\n } catch {\n try {\n res = new Response(body, { status: answer.status, headers: answer.headers });\n } catch {\n throw new NetError('NET_FAILED', 'the answer could not be read');\n }\n }\n // As a fetch Response: the URL that answered, and whether it was reached\n // through a redirect.\n Object.defineProperty(res, 'url', { value: hop.url });\n if (redirected) Object.defineProperty(res, 'redirected', { value: true });\n return res;\n}\n\n/** p, or the signal's reason as soon as it aborts. A request already at\n * the handle runs on, and the loader waits for it before answering; one\n * still waiting for its turn is never sent. */\nfunction abortable<T>(p: Promise<T>, signal: AbortSignal | null | undefined): Promise<T> {\n if (!signal) return p;\n if (signal.aborted) return Promise.reject(signal.reason);\n return new Promise<T>((resolve, reject) => {\n const onAbort = () => reject(signal.reason);\n signal.addEventListener('abort', onAbort, { once: true });\n p.then(\n (v) => {\n signal.removeEventListener('abort', onAbort);\n resolve(v);\n },\n (e) => {\n signal.removeEventListener('abort', onAbort);\n reject(e);\n },\n );\n });\n}\n\n/** ctx.env: the secrets as a frozen object of strings. */\nfunction envOf(raw: unknown): Readonly<Record<string, string>> {\n const entries =\n raw && typeof raw === 'object' && !Array.isArray(raw)\n ? Object.entries(raw).filter((e): e is [string, string] => typeof e[1] === 'string')\n : [];\n return Object.freeze(Object.fromEntries(entries));\n}\n\nfunction failure(err: unknown): ActionRunResult {\n if (err instanceof ActionError || (err instanceof Error && err.name === 'ActionError')) {\n return { ok: false, error: { kind: 'action_error', message: err.message } };\n }\n const e = err instanceof Error ? err : new Error(String(err));\n const label =\n e instanceof ActionDbError || e instanceof ClipError || e instanceof NetError\n ? `${e.name} ${e.code}`\n : e.name;\n return {\n ok: false,\n error: { kind: 'unexpected', message: `${label}: ${e.message}`, stack: e.stack ?? '' },\n };\n}\n\n/** A database call as the author's code holds it. It notes whether the code\n * attached a rejection handler anywhere along its chain \u2014 `await`,\n * `try`/`catch`, `.catch()`, `.then(f).catch(g)`, `Promise.all` all do \u2014 so\n * a failure nobody looked at fails the action instead of being lost.\n * Promises derived from a call point back to it. */\nclass DbCall<T> extends Promise<T> {\n handled = false;\n origin?: DbCall<unknown>;\n #inFinally = false;\n\n override then<R1 = T, R2 = never>(\n onFulfilled?: ((value: T) => R1 | PromiseLike<R1>) | null,\n onRejected?: ((reason: unknown) => R2 | PromiseLike<R2>) | null,\n ): Promise<R1 | R2> {\n const origin = this.origin ?? this;\n if (typeof onRejected === 'function' && !this.#inFinally) origin.handled = true;\n const derived = super.then(onFulfilled, onRejected) as DbCall<R1 | R2>;\n derived.origin = origin;\n return derived;\n }\n\n // finally() calls then() with a rejection handler that throws the failure\n // on: it handles nothing. A catch on what it returns still counts.\n override finally(onFinally?: (() => void) | null): Promise<T> {\n this.#inFinally = true;\n try {\n return super.finally(onFinally);\n } finally {\n this.#inFinally = false;\n }\n }\n}\n\n// The wrapper's own bookkeeping on a DbCall, which must not count as the\n// author handling it.\nconst observe = Promise.prototype.then as <T>(\n this: Promise<T>,\n onFulfilled: (value: T) => unknown,\n onRejected?: (reason: unknown) => unknown,\n) => Promise<unknown>;\n\n/** Wraps the author's functions into the module entry the loader calls. */\nexport function defineActions(actions: Record<string, ActionFunction>): ActionRunnerClass {\n const names = Object.keys(actions).sort();\n // Not named ActionRunner: the author's export usually is, and a bundler\n // would rename this class to tell the two apart.\n class ActionEntrypoint extends WorkerEntrypoint {\n static readonly actions: readonly string[] = names;\n\n async run(req: ActionRunRequest, handle: ActionHandle): Promise<ActionRunResult> {\n // Database calls still in flight are waited for before answering \u2014 a\n // write the author forgot to await commits before the caller has the\n // result. Calls started from a finishing call are waited for too; the\n // loader refuses any that arrive after run() returns.\n const pending = new Set<Promise<unknown>>();\n const failed = new Map<DbCall<unknown>, unknown>();\n const track = <T>(\n call: Promise<ActionHandleResult>,\n open: (result: ActionHandleResult) => unknown = unwrap,\n ): Promise<T> => {\n const dbCall = new DbCall<T>((resolve, reject) => {\n call.then(open).then(resolve as (value: unknown) => void, reject);\n });\n const settled = observe.call(\n dbCall,\n () => undefined,\n (err) => {\n failed.set(dbCall, err);\n },\n );\n pending.add(settled);\n observe.call(settled, () => pending.delete(settled));\n return dbCall;\n };\n const drain = async () => {\n while (pending.size > 0) await Promise.allSettled([...pending]);\n };\n const db: ActionDb = {\n query: (sql, params = []) => track(handle.query(sql, params)),\n exec: (sql, params = []) => track(handle.exec(sql, params)),\n batch: (statements) => track(handle.batch(statements)),\n };\n // Clip calls are tracked like database calls: waited for before the\n // answer, and a failure nobody looked at fails the action.\n const clip: ActionClip = {\n exec: (clipName, command, args, options) => {\n const request: ActionHandleClipRequest = {\n clip: clipName,\n command,\n args,\n connection: options?.connection,\n profile: options?.profile,\n timeout_ms: options?.timeoutMs,\n };\n const sent =\n typeof handle.clip === 'function'\n ? handle.clip(request)\n : Promise.resolve<ActionHandleResult>({\n ok: false,\n error: { code: 'CLIP_UNAVAILABLE', message: 'this runtime cannot call Clip yet' },\n });\n return track(sent, unwrapClip);\n },\n };\n // Outbound requests: one handle call per hop, at most net_in_flight at\n // once (more wait their turn), tracked like database calls.\n const limit = Math.max(1, req.net_in_flight || DEFAULT_IN_FLIGHT);\n let active = 0;\n const waiting: (() => void)[] = [];\n const send = async (hop: Hop, timeoutMs: number | undefined, signal: AbortSignal | null) => {\n while (active >= limit) await new Promise<void>((resume) => waiting.push(resume));\n active++;\n try {\n // Aborted while it waited for its turn (the code has already had\n // the abort): it is never sent, and the turn passes on.\n if (signal?.aborted) throw signal.reason;\n if (typeof handle.request !== 'function') {\n throw new NetError('NET_UNAVAILABLE', 'this runtime cannot make requests yet');\n }\n return unwrapNet(\n await handle.request({\n ...hop,\n ...(timeoutMs === undefined ? {} : { timeout_ms: timeoutMs }),\n }),\n );\n } finally {\n active--;\n waiting.shift()?.();\n }\n };\n const request = async (input: string | URL | Request, init?: ActionFetchInit) => {\n const first = await firstHop(input, init);\n const { redirect, signal } = first;\n let hop = first.hop;\n for (let followed = 0; ; followed++) {\n // Aborted before this hop: it is never asked for.\n if (signal?.aborted) throw signal.reason;\n const answer = await abortable(send(hop, init?.timeoutMs, signal), signal);\n if (redirect !== 'manual' && REDIRECT_STATUS.has(answer.status)) {\n if (redirect === 'error') {\n throw new NetError(\n 'NET_FAILED',\n `the server redirected (${answer.status}) and redirect is \"error\"`,\n );\n }\n const location = answer.headers.find(\n ([name]) => name.toLowerCase() === 'location',\n )?.[1];\n const next = nextHop(hop, answer.status, location);\n if (next) {\n if (followed >= MAX_REDIRECTS) {\n throw new NetError(\n 'ACTION_LIMIT_EXCEEDED',\n `ctx.fetch follows at most ${MAX_REDIRECTS} redirects`,\n );\n }\n hop = next;\n continue;\n }\n }\n return toResponse(answer, hop, followed > 0);\n }\n };\n const ctxFetch: ActionFetch = (input, init) =>\n track<Response>(\n request(input, init).then((res) => ({ ok: true, value: res }) as ActionHandleResult),\n (result) => (result as { value: unknown }).value,\n );\n const env = envOf(req.env);\n try {\n const fn = Object.hasOwn(actions, req.action) ? actions[req.action] : undefined;\n if (typeof fn !== 'function') {\n throw new Error(\n `this module does not implement the action ${JSON.stringify(req.action)}`,\n );\n }\n const value = await fn(\n { viewer: req.viewer, app: req.app, db, clip, fetch: ctxFetch, env },\n req.params,\n );\n await drain();\n // A call that failed while the code never looked at it (a forgotten\n // await) fails the action: answering ok would claim a write that did\n // not happen.\n for (const [dbCall, err] of failed) if (!dbCall.handled) throw err;\n const json = JSON.stringify(value === undefined ? null : value);\n if (typeof json !== 'string') {\n throw new TypeError('the action returned a value JSON cannot represent');\n }\n return { ok: true, json };\n } catch (err) {\n await drain();\n return failure(err);\n }\n }\n }\n return ActionEntrypoint;\n}\n";
|
|
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,
|
|
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,wi0BAA+7zB,CAAC"}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// Generated from ts/miniapp-sdk/src/actions.ts by scripts/generate-miniapp-sdk.mjs. Do not edit.
|
|
2
2
|
// biome-ignore format: generated copy
|
|
3
|
-
export const ACTIONS_SDK_SOURCE = "/**\n * @parall/miniapp-sdk/actions — the action side of a Mini App\n * (docs/engineering-design/mini-app-action-design.md §2): `defineActions`\n * turns the author's functions into the module entry the action loader\n * calls; `ActionError` is the error whose message the caller may see.\n *\n * This file runs inside the Cloudflare isolate, not in the page. It is the\n * only part of the SDK that imports `cloudflare:workers`, and an action\n * module is built from it into one file whose sole external import is that\n * one. Export the result as `ActionRunner` — the loader looks it up by name:\n *\n * export const ActionRunner = defineActions({\n * async addNote(ctx, { text }) {\n * const { rows } = await ctx.db.exec(\n * 'INSERT INTO notes (text, created_by) VALUES ($1, $2) RETURNING id',\n * [text, ctx.viewer.id],\n * );\n * return rows[0];\n * },\n * });\n *\n * Security does not depend on this wrapper: the loader accepts only the two\n * result shapes run() returns, whatever produced them (design §3.1).\n *\n * An action that declares `\"clip\": true` in the manifest (write actions only)\n * may call Clip as the person who called the action\n * (docs/engineering-design/mini-app-clip-design.md):\n *\n * const profile = await ctx.clip.exec('linkedin', 'get-profile', { id }, { connection: 'sales-li' });\n */\n\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";
|
|
3
|
+
export const ACTIONS_SDK_SOURCE = "/**\n * @parall/miniapp-sdk/actions — the action side of a Mini App\n * (docs/engineering-design/mini-app-action-design.md §2): `defineActions`\n * turns the author's functions into the module entry the action loader\n * calls; `ActionError` is the error whose message the caller may see.\n *\n * This file runs inside the Cloudflare isolate, not in the page. It is the\n * only part of the SDK that imports `cloudflare:workers`, and an action\n * module is built from it into one file whose sole external import is that\n * one. Export the result as `ActionRunner` — the loader looks it up by name:\n *\n * export const ActionRunner = defineActions({\n * async addNote(ctx, { text }) {\n * const { rows } = await ctx.db.exec(\n * 'INSERT INTO notes (text, created_by) VALUES ($1, $2) RETURNING id',\n * [text, ctx.viewer.id],\n * );\n * return rows[0];\n * },\n * });\n *\n * Security does not depend on this wrapper: the loader accepts only the two\n * result shapes run() returns, whatever produced them (design §3.1).\n *\n * An action that declares `\"clip\": true` in the manifest (write actions only)\n * may call Clip as the person who called the action\n * (docs/engineering-design/mini-app-clip-design.md):\n *\n * const profile = await ctx.clip.exec('linkedin', 'get-profile', { id }, { connection: 'sales-li' });\n *\n * `ctx.fetch` requests a public HTTP(S) address and returns a standard\n * `Response`; `ctx.env` holds the app's secrets by name\n * (docs/engineering-design/mini-app-network-design.md):\n *\n * const res = await ctx.fetch('https://api.example.com/v1/items', {\n * headers: { Authorization: `Bearer ${ctx.env.EXAMPLE_API_KEY}` },\n * });\n * if (!res.ok) throw new ActionError(`the items API answered ${res.status}`);\n * return res.json();\n */\n\nimport { WorkerEntrypoint } from 'cloudflare:workers';\n\n/** An error whose message reaches every caller as is (ACTION_FAILED with\n * error_kind action_error). Anything else thrown is an unexpected failure. */\nexport class ActionError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ActionError';\n }\n}\n\n/** A database call that was refused or failed. `code` is the platform's:\n * SQL_ERROR, SQL_REJECTED, ACTION_READ_ONLY, ACTION_LIMIT_EXCEEDED, … */\nexport class ActionDbError extends Error {\n readonly code: string;\n\n constructor(code: string, message: string) {\n super(message);\n this.name = 'ActionDbError';\n this.code = code;\n }\n}\n\n/** A Clip call that was refused or failed. `code` is the platform's — the\n * same codes the caller gets running `parall clip exec` themselves\n * (CONNECTION_NOT_ALLOWED, SCRIPT_ERROR, MCP_TOOL_FAILED, …) — or the\n * action's own: CLIP_NOT_DECLARED, ACTION_LIMIT_EXCEEDED, ACTION_DEADLINE.\n * OUTCOME_UNKNOWN means the command may have run: never retry it blindly. */\nexport class ClipError extends Error {\n readonly code: string;\n\n constructor(code: string, message: string) {\n super(message);\n this.name = 'ClipError';\n this.code = code;\n }\n}\n\n/** An outbound request (ctx.fetch) that was refused or failed — an HTTP\n * error status is not one: it comes back as a Response. `code` is the\n * platform's:\n *\n * - not sent: ACTION_INVALID_CALL (the URL, method, headers or body),\n * NET_ADDRESS_BLOCKED (private and loopback addresses, IP literals, the\n * platform's own hosts), ACTION_LIMIT_EXCEEDED (too many requests, or one\n * too large), ACTION_DEADLINE (too little time left), NET_BUSY (the\n * platform is busy; try again shortly), NET_UNAVAILABLE, USER_DISABLED,\n * ACTION_HANDLE_REVOKED;\n * - sent, so it may have reached the server: NET_TIMEOUT, NET_FAILED,\n * NET_RESPONSE_TOO_LARGE (answers are at most 1 MiB).\n *\n * The platform never retries; send an idempotency key where the other side\n * supports one. */\nexport class NetError extends Error {\n readonly code: string;\n\n constructor(code: string, message: string) {\n super(message);\n this.name = 'NetError';\n this.code = code;\n }\n}\n\n/** The caller, as the platform vouches for it (design §2.2). */\nexport interface ActionViewer {\n id: string;\n display_name: string;\n is_agent: boolean;\n /** Organization role: owner, admin or member. */\n role: string;\n}\n\nexport interface ActionApp {\n id: string;\n version_seq: number;\n}\n\n/** A row as an object keyed by column name, in select-list order. */\nexport type ActionRow = Record<string, unknown>;\n\nexport interface ActionQueryResult {\n rows: ActionRow[];\n truncated: boolean;\n}\n\nexport interface ActionStatementResult {\n rows: ActionRow[];\n rows_affected: number;\n truncated: boolean;\n}\n\nexport interface ActionExecResult extends ActionStatementResult {\n data_seq: number;\n}\n\nexport interface ActionBatchStatement {\n sql: string;\n params?: unknown[];\n}\n\nexport interface ActionBatchResult {\n results: ActionStatementResult[];\n data_seq: number;\n}\n\n/** ctx.db: one statement per query / exec; a batch is one transaction. */\nexport interface ActionDb {\n query(sql: string, params?: unknown[]): Promise<ActionQueryResult>;\n /** Write actions only. */\n exec(sql: string, params?: unknown[]): Promise<ActionExecResult>;\n /** Write actions only; at most 50 statements, counted as one call. */\n batch(statements: ActionBatchStatement[]): Promise<ActionBatchResult>;\n}\n\nexport interface ActionClipOptions {\n /** The connection to run on: its alias or ccn_ id. The caller must be\n * allowed to use it, exactly as for their own `parall clip exec`. */\n connection: string;\n profile?: string;\n /** The command's timeout; 30 s by default, cut to what the action's\n * deadline leaves. */\n timeoutMs?: number;\n}\n\n/** ctx.clip: Clip calls as the action's caller; actions that declare clip only. */\nexport interface ActionClip {\n /** Runs a command of a Clip (its name or crg_ id) and returns the Clip's\n * data; throws ClipError. */\n exec(clip: string, command: string, args: unknown, options: ActionClipOptions): Promise<unknown>;\n}\n\n/** ctx.fetch's options: the standard ones — method, headers, body, signal,\n * redirect — and the request's timeout. Others (cache, credentials, mode,\n * the Workers `cf`) are not looked at: every request is uncached and carries\n * only what the code sets. */\nexport interface ActionFetchInit extends RequestInit {\n /** This request's timeout; 30 s by default, cut to what the action's\n * deadline leaves. With redirects, each hop has it. */\n timeoutMs?: number;\n}\n\n/** ctx.fetch: a public HTTP(S) request from the platform, recorded in the\n * app's call record (host, method, status, size and time — never the query\n * string, headers or bodies). Redirects are followed up to 5 times: within\n * the same origin as Fetch does; to another origin with only Accept,\n * Accept-Language, Content-Language and User-Agent kept, and not at all when\n * the next request would carry the body (307, 308, and 301 / 302 for a\n * method other than GET, HEAD or POST) or when it would go from https: to\n * http: — then the redirect itself comes back. Each hop is a request of its\n * own. At most a few requests run at once; more wait their turn. */\nexport type ActionFetch = (\n input: string | URL | Request,\n init?: ActionFetchInit,\n) => Promise<Response>;\n\nexport interface ActionContext {\n viewer: ActionViewer;\n app: ActionApp;\n db: ActionDb;\n clip: ActionClip;\n fetch: ActionFetch;\n /** The app's secrets by name, as people with the app's publish right set\n * them; read-only. A local run (`parall app action run --local`) reads\n * them from the project's .dev.vars instead. Never pass them as params or\n * write them to the Database or a result. */\n env: Readonly<Record<string, string>>;\n}\n\n// biome-ignore lint/suspicious/noExplicitAny: the platform validates params against the declared schema before the call\nexport type ActionFunction = (ctx: ActionContext, params: any) => unknown;\n\n/** What the loader passes run() (ts/actions-worker src/run.ts). A loader\n * before the network sends neither env nor net_in_flight. */\nexport interface ActionRunRequest {\n action: string;\n params: unknown;\n viewer: ActionViewer;\n app: ActionApp;\n env?: Record<string, string>;\n /** How many requests the handle takes at once. */\n net_in_flight?: number;\n}\n\n/** The only two shapes the loader accepts back (ts/actions-worker src/outcome.ts). */\nexport type ActionRunResult =\n | { ok: true; json: string }\n | { ok: false; error: { kind: 'action_error' | 'unexpected'; message: string; stack?: string } };\n\n/** What a handle method resolves to. Failures travel as values because\n * Workers RPC keeps only an exception's name and message (design §6). */\nexport type ActionHandleResult =\n | { ok: true; value: unknown }\n | { ok: false; error: { code: string; message: string } };\n\n/** What the handle's clip method takes. */\nexport interface ActionHandleClipRequest {\n clip: string;\n command: string;\n args?: unknown;\n connection: string;\n profile?: string;\n timeout_ms?: number;\n}\n\n/** What the handle's request method takes: one request, rebuilt by the\n * loader from exactly these fields. */\nexport interface ActionHandleNetRequest {\n url: string;\n method: string;\n headers: [string, string][];\n body: ArrayBuffer | null;\n timeout_ms?: number;\n}\n\n/** What it answers with on success: the answer, never followed. */\nexport interface ActionHandleNetAnswer {\n status: number;\n status_text: string;\n headers: [string, string][];\n body: ArrayBuffer | null;\n}\n\n/** The per-invocation handle the loader passes run(). A loader before Clip\n * calls has no clip method; one before the network has no request method. */\nexport interface ActionHandle {\n query(sql: string, params: unknown[]): Promise<ActionHandleResult>;\n exec(sql: string, params: unknown[]): Promise<ActionHandleResult>;\n batch(statements: ActionBatchStatement[]): Promise<ActionHandleResult>;\n clip?(req: ActionHandleClipRequest): Promise<ActionHandleResult>;\n request?(req: ActionHandleNetRequest): Promise<ActionHandleResult>;\n}\n\n/** What defineActions returns; export it as `ActionRunner`. */\nexport interface ActionRunnerClass {\n /** The actions the module implements, sorted; `parall app check` compares\n * them with the manifest. */\n readonly actions: readonly string[];\n new (\n ctx: unknown,\n env: unknown,\n ): { run(req: ActionRunRequest, handle: ActionHandle): Promise<ActionRunResult> };\n}\n\nfunction unwrap(result: ActionHandleResult): unknown {\n if (result?.ok === true) return result.value;\n if (result?.ok === false) throw new ActionDbError(result.error.code, result.error.message);\n throw new ActionDbError(\n 'ACTION_DB_UNAVAILABLE',\n 'the database handle answered in an unknown shape',\n );\n}\n\nfunction unwrapClip(result: ActionHandleResult): unknown {\n if (result?.ok === true) return result.value;\n if (result?.ok === false) throw new ClipError(result.error.code, result.error.message);\n throw new ClipError(\n 'OUTCOME_UNKNOWN',\n 'the Clip call answered in an unknown shape; it may or may not have run',\n );\n}\n\nfunction unwrapNet(result: ActionHandleResult): ActionHandleNetAnswer {\n if (result?.ok === false) throw new NetError(result.error.code, result.error.message);\n const a = (result?.ok === true ? result.value : null) as ActionHandleNetAnswer | null;\n if (\n !a ||\n typeof a.status !== 'number' ||\n !Array.isArray(a.headers) ||\n (a.body !== null && !(a.body instanceof ArrayBuffer))\n ) {\n throw new NetError(\n 'NET_FAILED',\n 'the request answered in an unknown shape; it may have reached the server',\n );\n }\n return a;\n}\n\n// Statuses whose Response has no body (Fetch's null body status).\nconst NULL_BODY_STATUS = new Set([101, 103, 204, 205, 304]);\nconst REDIRECT_STATUS = new Set([301, 302, 303, 307, 308]);\n// What a redirect to another origin keeps of the author's headers\n// (mini-app-network-design.md §4): a key may be in any other one.\nconst CROSS_ORIGIN_HEADERS = new Set([\n 'accept',\n 'accept-language',\n 'content-language',\n 'user-agent',\n]);\n// Dropped with the body when a redirect turns the request into a GET.\nconst BODY_HEADERS = new Set([\n 'content-encoding',\n 'content-language',\n 'content-location',\n 'content-type',\n]);\nconst MAX_REDIRECTS = 5;\nconst DEFAULT_IN_FLIGHT = 4;\n\n/** One request of a ctx.fetch: the first, or a redirect's next hop. */\ninterface Hop {\n url: string;\n method: string;\n headers: [string, string][];\n body: ArrayBuffer | null;\n}\n\nfunction headerPairs(headers: Headers): [string, string][] {\n const out: [string, string][] = [];\n headers.forEach((value, name) => {\n out.push([name, value]);\n });\n return out;\n}\n\n/** The first hop, as a standard Request reads the input and init — only\n * the method, headers and body are taken from them. */\nasync function firstHop(input: string | URL | Request, init: ActionFetchInit | undefined) {\n let request: Request;\n try {\n request = new Request(input, {\n method: init?.method,\n headers: init?.headers,\n body: init?.body,\n });\n } catch (err) {\n throw new NetError(\n 'ACTION_INVALID_CALL',\n `ctx.fetch: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n const hop: Hop = {\n url: request.url,\n method: request.method,\n headers: headerPairs(request.headers),\n body: request.body ? await request.arrayBuffer() : null,\n };\n const fromInput = typeof input === 'object' && 'redirect' in input ? input.redirect : undefined;\n return {\n hop,\n redirect: (init?.redirect ?? fromInput ?? 'follow') as RequestRedirect,\n signal: init?.signal ?? (input instanceof Request ? input.signal : null),\n };\n}\n\n/** The next hop for a redirect, or null when it is not to be followed\n * (mini-app-network-design.md §4). The handle checks the address of every\n * hop: one into a private network or the platform is refused there. */\nfunction nextHop(hop: Hop, status: number, location: string | undefined): Hop | null {\n if (!REDIRECT_STATUS.has(status) || location === undefined) return null;\n let from: URL;\n let to: URL;\n try {\n from = new URL(hop.url);\n to = new URL(location, hop.url);\n } catch {\n return null;\n }\n if (from.protocol === 'https:' && to.protocol === 'http:') return null;\n const sameOrigin = to.origin === from.origin && to.origin !== 'null';\n const toGet =\n (status === 303 && hop.method !== 'GET' && hop.method !== 'HEAD') ||\n ((status === 301 || status === 302) && hop.method === 'POST');\n if (!sameOrigin) {\n // The next request would carry the body to another origin.\n if (status === 307 || status === 308) return null;\n if ((status === 301 || status === 302) && !['GET', 'HEAD', 'POST'].includes(hop.method)) {\n return null;\n }\n }\n let { method, headers, body } = hop;\n if (toGet) {\n method = 'GET';\n body = null;\n headers = headers.filter(([name]) => !BODY_HEADERS.has(name.toLowerCase()));\n }\n if (!sameOrigin)\n headers = headers.filter(([name]) => CROSS_ORIGIN_HEADERS.has(name.toLowerCase()));\n return { url: to.href, method, headers, body };\n}\n\nfunction toResponse(answer: ActionHandleNetAnswer, hop: Hop, redirected: boolean): Response {\n if (answer.status < 200 || answer.status > 599) {\n throw new NetError('NET_FAILED', `the server answered with status ${answer.status}`);\n }\n // As Fetch does: no body for a HEAD request or a null body status.\n const body = hop.method === 'HEAD' || NULL_BODY_STATUS.has(answer.status) ? null : answer.body;\n let res: Response;\n try {\n res = new Response(body, {\n status: answer.status,\n statusText: answer.status_text,\n headers: answer.headers,\n });\n } catch {\n try {\n res = new Response(body, { status: answer.status, headers: answer.headers });\n } catch {\n throw new NetError('NET_FAILED', 'the answer could not be read');\n }\n }\n // As a fetch Response: the URL that answered, and whether it was reached\n // through a redirect.\n Object.defineProperty(res, 'url', { value: hop.url });\n if (redirected) Object.defineProperty(res, 'redirected', { value: true });\n return res;\n}\n\n/** p, or the signal's reason as soon as it aborts. A request already at\n * the handle runs on, and the loader waits for it before answering; one\n * still waiting for its turn is never sent. */\nfunction abortable<T>(p: Promise<T>, signal: AbortSignal | null | undefined): Promise<T> {\n if (!signal) return p;\n if (signal.aborted) return Promise.reject(signal.reason);\n return new Promise<T>((resolve, reject) => {\n const onAbort = () => reject(signal.reason);\n signal.addEventListener('abort', onAbort, { once: true });\n p.then(\n (v) => {\n signal.removeEventListener('abort', onAbort);\n resolve(v);\n },\n (e) => {\n signal.removeEventListener('abort', onAbort);\n reject(e);\n },\n );\n });\n}\n\n/** ctx.env: the secrets as a frozen object of strings. */\nfunction envOf(raw: unknown): Readonly<Record<string, string>> {\n const entries =\n raw && typeof raw === 'object' && !Array.isArray(raw)\n ? Object.entries(raw).filter((e): e is [string, string] => typeof e[1] === 'string')\n : [];\n return Object.freeze(Object.fromEntries(entries));\n}\n\nfunction failure(err: unknown): ActionRunResult {\n if (err instanceof ActionError || (err instanceof Error && err.name === 'ActionError')) {\n return { ok: false, error: { kind: 'action_error', message: err.message } };\n }\n const e = err instanceof Error ? err : new Error(String(err));\n const label =\n e instanceof ActionDbError || e instanceof ClipError || e instanceof NetError\n ? `${e.name} ${e.code}`\n : e.name;\n return {\n ok: false,\n error: { kind: 'unexpected', message: `${label}: ${e.message}`, stack: e.stack ?? '' },\n };\n}\n\n/** A database call as the author's code holds it. It notes whether the code\n * attached a rejection handler anywhere along its chain — `await`,\n * `try`/`catch`, `.catch()`, `.then(f).catch(g)`, `Promise.all` all do — so\n * a failure nobody looked at fails the action instead of being lost.\n * Promises derived from a call point back to it. */\nclass DbCall<T> extends Promise<T> {\n handled = false;\n origin?: DbCall<unknown>;\n #inFinally = false;\n\n override then<R1 = T, R2 = never>(\n onFulfilled?: ((value: T) => R1 | PromiseLike<R1>) | null,\n onRejected?: ((reason: unknown) => R2 | PromiseLike<R2>) | null,\n ): Promise<R1 | R2> {\n const origin = this.origin ?? this;\n if (typeof onRejected === 'function' && !this.#inFinally) origin.handled = true;\n const derived = super.then(onFulfilled, onRejected) as DbCall<R1 | R2>;\n derived.origin = origin;\n return derived;\n }\n\n // finally() calls then() with a rejection handler that throws the failure\n // on: it handles nothing. A catch on what it returns still counts.\n override finally(onFinally?: (() => void) | null): Promise<T> {\n this.#inFinally = true;\n try {\n return super.finally(onFinally);\n } finally {\n this.#inFinally = false;\n }\n }\n}\n\n// The wrapper's own bookkeeping on a DbCall, which must not count as the\n// author handling it.\nconst observe = Promise.prototype.then as <T>(\n this: Promise<T>,\n onFulfilled: (value: T) => unknown,\n onRejected?: (reason: unknown) => unknown,\n) => Promise<unknown>;\n\n/** Wraps the author's functions into the module entry the loader calls. */\nexport function defineActions(actions: Record<string, ActionFunction>): ActionRunnerClass {\n const names = Object.keys(actions).sort();\n // Not named ActionRunner: the author's export usually is, and a bundler\n // would rename this class to tell the two apart.\n class ActionEntrypoint extends WorkerEntrypoint {\n static readonly actions: readonly string[] = names;\n\n async run(req: ActionRunRequest, handle: ActionHandle): Promise<ActionRunResult> {\n // Database calls still in flight are waited for before answering — a\n // write the author forgot to await commits before the caller has the\n // result. Calls started from a finishing call are waited for too; the\n // loader refuses any that arrive after run() returns.\n const pending = new Set<Promise<unknown>>();\n const failed = new Map<DbCall<unknown>, unknown>();\n const track = <T>(\n call: Promise<ActionHandleResult>,\n open: (result: ActionHandleResult) => unknown = unwrap,\n ): Promise<T> => {\n const dbCall = new DbCall<T>((resolve, reject) => {\n call.then(open).then(resolve as (value: unknown) => void, reject);\n });\n const settled = observe.call(\n dbCall,\n () => undefined,\n (err) => {\n failed.set(dbCall, err);\n },\n );\n pending.add(settled);\n observe.call(settled, () => pending.delete(settled));\n return dbCall;\n };\n const drain = async () => {\n while (pending.size > 0) await Promise.allSettled([...pending]);\n };\n const db: ActionDb = {\n query: (sql, params = []) => track(handle.query(sql, params)),\n exec: (sql, params = []) => track(handle.exec(sql, params)),\n batch: (statements) => track(handle.batch(statements)),\n };\n // Clip calls are tracked like database calls: waited for before the\n // answer, and a failure nobody looked at fails the action.\n const clip: ActionClip = {\n exec: (clipName, command, args, options) => {\n const request: ActionHandleClipRequest = {\n clip: clipName,\n command,\n args,\n connection: options?.connection,\n profile: options?.profile,\n timeout_ms: options?.timeoutMs,\n };\n const sent =\n typeof handle.clip === 'function'\n ? handle.clip(request)\n : Promise.resolve<ActionHandleResult>({\n ok: false,\n error: { code: 'CLIP_UNAVAILABLE', message: 'this runtime cannot call Clip yet' },\n });\n return track(sent, unwrapClip);\n },\n };\n // Outbound requests: one handle call per hop, at most net_in_flight at\n // once (more wait their turn), tracked like database calls.\n const limit = Math.max(1, req.net_in_flight || DEFAULT_IN_FLIGHT);\n let active = 0;\n const waiting: (() => void)[] = [];\n const send = async (hop: Hop, timeoutMs: number | undefined, signal: AbortSignal | null) => {\n while (active >= limit) await new Promise<void>((resume) => waiting.push(resume));\n active++;\n try {\n // Aborted while it waited for its turn (the code has already had\n // the abort): it is never sent, and the turn passes on.\n if (signal?.aborted) throw signal.reason;\n if (typeof handle.request !== 'function') {\n throw new NetError('NET_UNAVAILABLE', 'this runtime cannot make requests yet');\n }\n return unwrapNet(\n await handle.request({\n ...hop,\n ...(timeoutMs === undefined ? {} : { timeout_ms: timeoutMs }),\n }),\n );\n } finally {\n active--;\n waiting.shift()?.();\n }\n };\n const request = async (input: string | URL | Request, init?: ActionFetchInit) => {\n const first = await firstHop(input, init);\n const { redirect, signal } = first;\n let hop = first.hop;\n for (let followed = 0; ; followed++) {\n // Aborted before this hop: it is never asked for.\n if (signal?.aborted) throw signal.reason;\n const answer = await abortable(send(hop, init?.timeoutMs, signal), signal);\n if (redirect !== 'manual' && REDIRECT_STATUS.has(answer.status)) {\n if (redirect === 'error') {\n throw new NetError(\n 'NET_FAILED',\n `the server redirected (${answer.status}) and redirect is \"error\"`,\n );\n }\n const location = answer.headers.find(\n ([name]) => name.toLowerCase() === 'location',\n )?.[1];\n const next = nextHop(hop, answer.status, location);\n if (next) {\n if (followed >= MAX_REDIRECTS) {\n throw new NetError(\n 'ACTION_LIMIT_EXCEEDED',\n `ctx.fetch follows at most ${MAX_REDIRECTS} redirects`,\n );\n }\n hop = next;\n continue;\n }\n }\n return toResponse(answer, hop, followed > 0);\n }\n };\n const ctxFetch: ActionFetch = (input, init) =>\n track<Response>(\n request(input, init).then((res) => ({ ok: true, value: res }) as ActionHandleResult),\n (result) => (result as { value: unknown }).value,\n );\n const env = envOf(req.env);\n try {\n const fn = Object.hasOwn(actions, req.action) ? actions[req.action] : undefined;\n if (typeof fn !== 'function') {\n throw new Error(\n `this module does not implement the action ${JSON.stringify(req.action)}`,\n );\n }\n const value = await fn(\n { viewer: req.viewer, app: req.app, db, clip, fetch: ctxFetch, env },\n req.params,\n );\n await drain();\n // A call that failed while the code never looked at it (a forgotten\n // await) fails the action: answering ok would claim a write that did\n // not happen.\n for (const [dbCall, err] of failed) if (!dbCall.handled) throw err;\n const json = JSON.stringify(value === undefined ? null : value);\n if (typeof json !== 'string') {\n throw new TypeError('the action returned a value JSON cannot represent');\n }\n return { ok: true, json };\n } catch (err) {\n await drain();\n return failure(err);\n }\n }\n }\n return ActionEntrypoint;\n}\n";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"apps-actions.d.ts","sourceRoot":"","sources":["../../src/commands/apps-actions.ts"],"names":[],"mappings":"AAEA,OAAO,EAGL,KAAK,mBAAmB,EAEzB,MAAM,aAAa,CAAC;AACrB,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;
|
|
1
|
+
{"version":3,"file":"apps-actions.d.ts","sourceRoot":"","sources":["../../src/commands/apps-actions.ts"],"names":[],"mappings":"AAEA,OAAO,EAGL,KAAK,mBAAmB,EAEzB,MAAM,aAAa,CAAC;AACrB,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAOzC;;;;;iEAKiE;AACjE,wBAAgB,yBAAyB,CAAC,GAAG,EAAE,OAAO,QAsIrD;AAaD,UAAU,YAAY;IACpB,KAAK,CAAC,EAAE,MAAM,EAAE,CAAC;IACjB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB;AAED;;0EAE0E;AAC1E,wBAAsB,WAAW,CAC/B,MAAM,EAAE,mBAAmB,GAAG,IAAI,EAClC,IAAI,EAAE,YAAY,GACjB,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAkBlC"}
|
|
@@ -2,8 +2,9 @@ import { promises as fs } from 'node:fs';
|
|
|
2
2
|
import { resolve } from 'node:path';
|
|
3
3
|
import { ApiError, } from '@parall/sdk';
|
|
4
4
|
import { resolveCredentials } from '../lib/client.js';
|
|
5
|
-
import { parsePositiveInt, printError, printJson
|
|
5
|
+
import { parsePositiveInt, printError, printJson } from '../lib/output.js';
|
|
6
6
|
import { readLocalAction, runLocalAction } from './apps-action-local.js';
|
|
7
|
+
import { appAndArg, appIdFrom, withApp } from './apps-args.js';
|
|
7
8
|
import { mapActionStack } from './apps-action-stack.js';
|
|
8
9
|
/** `parall app action list | run | log`
|
|
9
10
|
* (docs/engineering-design/mini-app-action-design.md §3, §5.3, §10): the
|
|
@@ -15,15 +16,13 @@ export function registerAppActionCommands(app) {
|
|
|
15
16
|
const action = app
|
|
16
17
|
.command('action')
|
|
17
18
|
.description("List, run and audit an app's server-side actions");
|
|
18
|
-
action
|
|
19
|
-
.command('list')
|
|
20
|
-
.description('List the actions of the version a call would run')
|
|
21
|
-
.argument('<appId>', 'App ID')
|
|
19
|
+
withApp(action.command('list').description('List the actions of the version a call would run'))
|
|
22
20
|
.option('--v <seq>', 'Version seq (default: the current one)')
|
|
23
21
|
.action(async (appId, opts) => {
|
|
24
22
|
try {
|
|
23
|
+
const id = appIdFrom(appId, opts.app);
|
|
25
24
|
const { client, orgId } = resolveCredentials();
|
|
26
|
-
printJson(await client.getMiniAppActions(orgId,
|
|
25
|
+
printJson(await client.getMiniAppActions(orgId, id, version(opts.v)));
|
|
27
26
|
}
|
|
28
27
|
catch (err) {
|
|
29
28
|
printError(err);
|
|
@@ -32,19 +31,20 @@ export function registerAppActionCommands(app) {
|
|
|
32
31
|
action
|
|
33
32
|
.command('run')
|
|
34
33
|
.description('Run one action and print its result')
|
|
35
|
-
.argument('
|
|
36
|
-
.argument('
|
|
34
|
+
.argument('[appId]', 'App ID (app_… or prll://app_…); or pass --app')
|
|
35
|
+
.argument('[name]', 'Action name')
|
|
36
|
+
.option('--app <appId>', 'App ID, in place of the first argument')
|
|
37
37
|
.option('--param <key=value>', 'One param; the value is converted to the declared type (repeatable)', collect, [])
|
|
38
38
|
.option('--params <json>', 'All params as a JSON object (--param entries override)')
|
|
39
39
|
.option('--params-file <file>', 'All params from a JSON file (--param entries override)')
|
|
40
40
|
.option('--v <seq>', 'Version seq (default: the current one)')
|
|
41
41
|
.option('--local', "Run the local build's action in workerd on this machine, against the app's real Database (writes are real; needs miniflare in the project)")
|
|
42
42
|
.option('--dist <dir>', 'Local build: what --local runs, and the map for a failure stack', 'dist')
|
|
43
|
-
.action(async (
|
|
43
|
+
.action(async (first, second, opts) => {
|
|
44
44
|
let invoked;
|
|
45
45
|
try {
|
|
46
|
+
const [id, name] = appAndArg(first, second, opts.app, 'action name');
|
|
46
47
|
const { client, orgId } = resolveCredentials();
|
|
47
|
-
const id = stripPrllScheme(appId);
|
|
48
48
|
if (opts.local) {
|
|
49
49
|
if (opts.v !== undefined)
|
|
50
50
|
throw new Error('--local runs the local build; it takes no --v');
|
|
@@ -90,10 +90,7 @@ export function registerAppActionCommands(app) {
|
|
|
90
90
|
printError(err);
|
|
91
91
|
}
|
|
92
92
|
});
|
|
93
|
-
action
|
|
94
|
-
.command('log')
|
|
95
|
-
.description("List the app's audited invocations, newest first")
|
|
96
|
-
.argument('<appId>', 'App ID')
|
|
93
|
+
withApp(action.command('log').description("List the app's audited invocations, newest first"))
|
|
97
94
|
.option('--limit <n>', 'Entries to return (default 50, at most 200)')
|
|
98
95
|
.option('--before <rfc3339>', "Page: the previous page's last started_at")
|
|
99
96
|
.option('--before-id <invocationId>', "Page: the previous page's last invocation_id")
|
|
@@ -104,6 +101,7 @@ export function registerAppActionCommands(app) {
|
|
|
104
101
|
.option('--invocation <invocationId>', 'Only this invocation (aci_…)')
|
|
105
102
|
.action(async (appId, opts) => {
|
|
106
103
|
try {
|
|
104
|
+
const id = appIdFrom(appId, opts.app);
|
|
107
105
|
// By presence, not value: --status '' still counts as given.
|
|
108
106
|
if (opts.failed && opts.status !== undefined) {
|
|
109
107
|
throw new Error('Use --failed or --status, not both');
|
|
@@ -115,7 +113,7 @@ export function registerAppActionCommands(app) {
|
|
|
115
113
|
? ['failed', 'timeout', 'limit_exceeded']
|
|
116
114
|
: opts.status?.split(',');
|
|
117
115
|
const { client, orgId } = resolveCredentials();
|
|
118
|
-
printJson(await client.getMiniAppActionLog(orgId,
|
|
116
|
+
printJson(await client.getMiniAppActionLog(orgId, id, {
|
|
119
117
|
limit: parsePositiveInt(opts.limit),
|
|
120
118
|
before: opts.before,
|
|
121
119
|
before_id: opts.beforeId,
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { relative, resolve } from 'node:path';
|
|
2
|
-
import { printError, printJson } from '../lib/output.js';
|
|
2
|
+
import { printError, printJson, printProgress } from '../lib/output.js';
|
|
3
3
|
import { applyBlock, blockNames, conflictMessage, findBlock, listBlocks, planBlock, } from './apps-blocks.js';
|
|
4
4
|
/** `parall app add <block…>` copies @parall blocks into a Mini App project
|
|
5
5
|
* (apps-blocks.ts). It writes local files only: the block's tables are
|
|
@@ -60,7 +60,7 @@ export function registerAppAddCommand(app) {
|
|
|
60
60
|
sql: plan.sql,
|
|
61
61
|
})),
|
|
62
62
|
});
|
|
63
|
-
|
|
63
|
+
printProgress(nextSteps(dir, plans, Boolean(opts.dryRun)));
|
|
64
64
|
}
|
|
65
65
|
catch (err) {
|
|
66
66
|
printError(err);
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { Command } from 'commander';
|
|
2
|
+
/** How the Mini App commands take their app and their output path. Agents
|
|
3
|
+
* reach for both spellings of each — publish and rollback name the app
|
|
4
|
+
* with --app while the other commands take it as the first argument, and
|
|
5
|
+
* --out / --output are both common — so each command accepts either form,
|
|
6
|
+
* and both when they agree. publish is the exception: its argument is the
|
|
7
|
+
* build directory, so its app stays --app. The forms each command
|
|
8
|
+
* documented first keep working unchanged. */
|
|
9
|
+
/** Adds the app as an optional first argument and as --app. */
|
|
10
|
+
export declare function withApp(cmd: Command): Command;
|
|
11
|
+
/** The app a command names, as the argument or --app. */
|
|
12
|
+
export declare function appIdFrom(positional: string | undefined, flag: string | undefined): string;
|
|
13
|
+
/** The app and the argument after it (`authors add <app> <user>`, `action
|
|
14
|
+
* run <app> <name>`). With --app, a lone argument is the second one — even
|
|
15
|
+
* when it reads like the app: an action may be named like its app's ID. */
|
|
16
|
+
export declare function appAndArg(first: string | undefined, second: string | undefined, flag: string | undefined, what: string): [string, string];
|
|
17
|
+
/** --out and --output name the same path. */
|
|
18
|
+
export declare function outputPath(opts: {
|
|
19
|
+
out?: string;
|
|
20
|
+
output?: string;
|
|
21
|
+
}): string | undefined;
|
|
22
|
+
//# sourceMappingURL=apps-args.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"apps-args.d.ts","sourceRoot":"","sources":["../../src/commands/apps-args.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAGzC;;;;;;8CAM8C;AAE9C,+DAA+D;AAC/D,wBAAgB,OAAO,CAAC,GAAG,EAAE,OAAO,GAAG,OAAO,CAI7C;AASD,yDAAyD;AACzD,wBAAgB,SAAS,CAAC,UAAU,EAAE,MAAM,GAAG,SAAS,EAAE,IAAI,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,CAS1F;AAED;;2EAE2E;AAC3E,wBAAgB,SAAS,CACvB,KAAK,EAAE,MAAM,GAAG,SAAS,EACzB,MAAM,EAAE,MAAM,GAAG,SAAS,EAC1B,IAAI,EAAE,MAAM,GAAG,SAAS,EACxB,IAAI,EAAE,MAAM,GACX,CAAC,MAAM,EAAE,MAAM,CAAC,CAiBlB;AAED,6CAA6C;AAC7C,wBAAgB,UAAU,CAAC,IAAI,EAAE;IAAE,GAAG,CAAC,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,CAAA;CAAE,GAAG,MAAM,GAAG,SAAS,CAKtF"}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { stripPrllScheme } from '../lib/output.js';
|
|
2
|
+
/** How the Mini App commands take their app and their output path. Agents
|
|
3
|
+
* reach for both spellings of each — publish and rollback name the app
|
|
4
|
+
* with --app while the other commands take it as the first argument, and
|
|
5
|
+
* --out / --output are both common — so each command accepts either form,
|
|
6
|
+
* and both when they agree. publish is the exception: its argument is the
|
|
7
|
+
* build directory, so its app stays --app. The forms each command
|
|
8
|
+
* documented first keep working unchanged. */
|
|
9
|
+
/** Adds the app as an optional first argument and as --app. */
|
|
10
|
+
export function withApp(cmd) {
|
|
11
|
+
return cmd
|
|
12
|
+
.argument('[appId]', 'App ID (app_… or prll://app_…); or pass --app')
|
|
13
|
+
.option('--app <appId>', 'App ID, in place of the argument');
|
|
14
|
+
}
|
|
15
|
+
function clean(value) {
|
|
16
|
+
const id = value === undefined ? '' : stripPrllScheme(value.trim());
|
|
17
|
+
return id === '' ? undefined : id;
|
|
18
|
+
}
|
|
19
|
+
const NAME_THE_APP = 'Name the app: as the first argument (app_… or prll://app_…) or with --app';
|
|
20
|
+
/** The app a command names, as the argument or --app. */
|
|
21
|
+
export function appIdFrom(positional, flag) {
|
|
22
|
+
const arg = clean(positional);
|
|
23
|
+
const opt = clean(flag);
|
|
24
|
+
if (arg && opt && arg !== opt) {
|
|
25
|
+
throw new Error(`Name the app once: the argument says ${arg}, --app says ${opt}`);
|
|
26
|
+
}
|
|
27
|
+
const id = arg ?? opt;
|
|
28
|
+
if (!id)
|
|
29
|
+
throw new Error(NAME_THE_APP);
|
|
30
|
+
return id;
|
|
31
|
+
}
|
|
32
|
+
/** The app and the argument after it (`authors add <app> <user>`, `action
|
|
33
|
+
* run <app> <name>`). With --app, a lone argument is the second one — even
|
|
34
|
+
* when it reads like the app: an action may be named like its app's ID. */
|
|
35
|
+
export function appAndArg(first, second, flag, what) {
|
|
36
|
+
const opt = clean(flag);
|
|
37
|
+
if (!opt) {
|
|
38
|
+
const app = clean(first);
|
|
39
|
+
if (!app)
|
|
40
|
+
throw new Error(NAME_THE_APP);
|
|
41
|
+
if (second === undefined || second === '')
|
|
42
|
+
throw new Error(`Pass the ${what} after the app`);
|
|
43
|
+
return [app, second];
|
|
44
|
+
}
|
|
45
|
+
if (second !== undefined) {
|
|
46
|
+
// Two arguments: the first is the app, and must be the same one.
|
|
47
|
+
if (clean(first) !== opt) {
|
|
48
|
+
throw new Error(`Name the app once: the argument says ${clean(first)}, --app says ${opt}`);
|
|
49
|
+
}
|
|
50
|
+
return [opt, second];
|
|
51
|
+
}
|
|
52
|
+
if (first === undefined || first === '')
|
|
53
|
+
throw new Error(`Pass the ${what}`);
|
|
54
|
+
return [opt, first];
|
|
55
|
+
}
|
|
56
|
+
/** --out and --output name the same path. */
|
|
57
|
+
export function outputPath(opts) {
|
|
58
|
+
if (opts.out !== undefined && opts.output !== undefined && opts.out !== opts.output) {
|
|
59
|
+
throw new Error('Pass --out or --output, not both');
|
|
60
|
+
}
|
|
61
|
+
return opts.out ?? opts.output;
|
|
62
|
+
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"apps-check.d.ts","sourceRoot":"","sources":["../../src/commands/apps-check.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAGzC;;;;;4BAK4B;AAC5B,wBAAgB,uBAAuB,CAAC,GAAG,EAAE,OAAO,
|
|
1
|
+
{"version":3,"file":"apps-check.d.ts","sourceRoot":"","sources":["../../src/commands/apps-check.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAGzC;;;;;4BAK4B;AAC5B,wBAAgB,uBAAuB,CAAC,GAAG,EAAE,OAAO,QAsBnD;AAED,MAAM,WAAW,WAAW;IAC1B,4EAA4E;IAC5E,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,sDAAsD;IACtD,OAAO,EAAE,MAAM,EAAE,CAAC;CACnB;AAWD;;+EAE+E;AAC/E,MAAM,WAAW,YAAY;IAC3B,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,8CAA8C;IAC9C,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACpC;AAED,wBAAsB,YAAY,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,WAAW,CAAC,CAiBrE;AAED;cACc;AACd,wBAAsB,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,YAAY,GAAG,IAAI,CAAC,CAkDjF;AAED;;gDAEgD;AAChD,wBAAgB,aAAa,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,CAWtD"}
|
|
@@ -14,10 +14,15 @@ export function registerAppCheckCommand(app) {
|
|
|
14
14
|
app
|
|
15
15
|
.command('check')
|
|
16
16
|
.description("Check a built bundle's action module against its manifest")
|
|
17
|
-
.argument('[dir]', 'The built bundle directory
|
|
18
|
-
.
|
|
17
|
+
.argument('[dir]', 'The built bundle directory (default: dist)')
|
|
18
|
+
.option('--dist <dir>', 'The built bundle directory, in place of the argument')
|
|
19
|
+
.option('--app <appId>', 'Not needed: the check reads only the local build (accepted so a publish command line works here)')
|
|
20
|
+
.action(async (dir, opts) => {
|
|
19
21
|
try {
|
|
20
|
-
|
|
22
|
+
if (dir !== undefined && opts.dist !== undefined && resolve(dir) !== resolve(opts.dist)) {
|
|
23
|
+
throw new Error(`Name the build once: the argument says ${dir}, --dist says ${opts.dist}`);
|
|
24
|
+
}
|
|
25
|
+
printJson({ ok: true, ...(await checkActions(resolve(dir ?? opts.dist ?? 'dist'))) });
|
|
21
26
|
}
|
|
22
27
|
catch (err) {
|
|
23
28
|
printError(err);
|
|
@@ -3,6 +3,8 @@ export { parseParams } from './db-plane.js';
|
|
|
3
3
|
/** `parall app db …`: the app alias of the data plane — the same operations
|
|
4
4
|
* as `parall db …` on the app's Database, with the app recorded on every
|
|
5
5
|
* log row; the same construction-surface rule applies (attached-app author
|
|
6
|
-
* or org owner/admin). Writes through an archived app are refused.
|
|
6
|
+
* or org owner/admin). Writes through an archived app are refused. Both
|
|
7
|
+
* groups take the same target forms (db-target.ts): an app given here runs
|
|
8
|
+
* through the app, a Database ID or name on the Database. */
|
|
7
9
|
export declare function registerAppDBCommands(app: Command): void;
|
|
8
10
|
//# sourceMappingURL=apps-db.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"apps-db.d.ts","sourceRoot":"","sources":["../../src/commands/apps-db.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;
|
|
1
|
+
{"version":3,"file":"apps-db.d.ts","sourceRoot":"","sources":["../../src/commands/apps-db.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAGzC,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAE5C;;;;;6DAK6D;AAC7D,wBAAgB,qBAAqB,CAAC,GAAG,EAAE,OAAO,QAKjD"}
|