@parall/cli 1.69.0 → 1.71.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/dist/commands/apps-action-local.d.ts +44 -0
  2. package/dist/commands/apps-action-local.d.ts.map +1 -0
  3. package/dist/commands/apps-action-local.js +153 -0
  4. package/dist/commands/apps-action-stack.d.ts +14 -0
  5. package/dist/commands/apps-action-stack.d.ts.map +1 -0
  6. package/dist/commands/apps-action-stack.js +63 -0
  7. package/dist/commands/apps-actions-sdk.generated.d.ts +2 -0
  8. package/dist/commands/apps-actions-sdk.generated.d.ts.map +1 -0
  9. package/dist/commands/apps-actions-sdk.generated.js +3 -0
  10. package/dist/commands/apps-actions.d.ts +20 -0
  11. package/dist/commands/apps-actions.d.ts.map +1 -0
  12. package/dist/commands/apps-actions.js +266 -0
  13. package/dist/commands/apps-check.d.ts +34 -0
  14. package/dist/commands/apps-check.d.ts.map +1 -0
  15. package/dist/commands/apps-check.js +155 -0
  16. package/dist/commands/apps-dev-page.d.ts +26 -0
  17. package/dist/commands/apps-dev-page.d.ts.map +1 -0
  18. package/dist/commands/apps-dev-page.js +259 -0
  19. package/dist/commands/apps-dev-server.d.ts +42 -0
  20. package/dist/commands/apps-dev-server.d.ts.map +1 -0
  21. package/dist/commands/apps-dev-server.js +328 -0
  22. package/dist/commands/apps-dev.d.ts +8 -0
  23. package/dist/commands/apps-dev.d.ts.map +1 -0
  24. package/dist/commands/apps-dev.js +126 -0
  25. package/dist/commands/apps-local-runner.generated.d.ts +3 -0
  26. package/dist/commands/apps-local-runner.generated.d.ts.map +1 -0
  27. package/dist/commands/apps-local-runner.generated.js +4 -0
  28. package/dist/commands/apps-page-sdk.generated.d.ts +2 -0
  29. package/dist/commands/apps-page-sdk.generated.d.ts.map +1 -0
  30. package/dist/commands/apps-page-sdk.generated.js +3 -0
  31. package/dist/commands/apps-publish.d.ts.map +1 -1
  32. package/dist/commands/apps-publish.js +6 -0
  33. package/dist/commands/apps-scaffold-actions.d.ts +11 -0
  34. package/dist/commands/apps-scaffold-actions.d.ts.map +1 -0
  35. package/dist/commands/apps-scaffold-actions.js +163 -0
  36. package/dist/commands/apps-scaffold.d.ts +4 -6
  37. package/dist/commands/apps-scaffold.d.ts.map +1 -1
  38. package/dist/commands/apps-scaffold.js +22 -222
  39. package/dist/commands/apps.d.ts +3 -2
  40. package/dist/commands/apps.d.ts.map +1 -1
  41. package/dist/commands/apps.js +9 -2
  42. package/dist/commands/db-plane.d.ts.map +1 -1
  43. package/dist/commands/db-plane.js +2 -0
  44. package/dist/commands/dbs.d.ts.map +1 -1
  45. package/dist/commands/dbs.js +1 -8
  46. package/dist/commands/messages.d.ts.map +1 -1
  47. package/dist/commands/messages.js +6 -11
  48. package/dist/commands/msteams.d.ts +10 -0
  49. package/dist/commands/msteams.d.ts.map +1 -0
  50. package/dist/commands/msteams.js +41 -0
  51. package/dist/commands/wiki.d.ts.map +1 -1
  52. package/dist/commands/wiki.js +20 -8
  53. package/dist/index.js +7 -5
  54. package/dist/lib/client.d.ts +2 -1
  55. package/dist/lib/client.d.ts.map +1 -1
  56. package/dist/lib/mini-app-discovery.d.ts +6 -0
  57. package/dist/lib/mini-app-discovery.d.ts.map +1 -0
  58. package/dist/lib/mini-app-discovery.js +32 -0
  59. package/dist/lib/output.d.ts +3 -1
  60. package/dist/lib/output.d.ts.map +1 -1
  61. package/dist/lib/output.js +5 -1
  62. package/dist/lib/wiki-index.d.ts +2 -0
  63. package/dist/lib/wiki-index.d.ts.map +1 -1
  64. package/dist/lib/wiki-index.js +28 -73
  65. package/dist/lib/wiki-search-text.d.ts +37 -0
  66. package/dist/lib/wiki-search-text.d.ts.map +1 -0
  67. package/dist/lib/wiki-search-text.js +170 -0
  68. package/package.json +9 -5
@@ -0,0 +1,44 @@
1
+ import { type MiniAppActionInvokeResult, type MiniAppActionKind, type MiniAppActionSchema } from '@parall/sdk';
2
+ import type { resolveCredentials } from '../lib/client.js';
3
+ /** `parall app action run --local`
4
+ * (docs/engineering-design/mini-app-action-design.md §10.3): runs one action
5
+ * of the local build in workerd on this machine — the loader's own sandbox,
6
+ * database handle and outcome rules (ts/actions-worker src/local.ts, embedded
7
+ * at build time) under the project's miniflare. api-server issues the run's
8
+ * ticket (an acd_ invocation), so its database calls reach the app's real
9
+ * Database through the same callback, rules, deadline and limits as a
10
+ * deployed invocation: writes are real. api-server also validates the
11
+ * params against the local declaration, as it does an invocation's.
12
+ *
13
+ * The module is never loaded in this process: it holds the caller's
14
+ * credentials, and the module's top-level code is to run only in the
15
+ * sandbox. */
16
+ export interface LocalAction {
17
+ /** The action's entry in the build's manifest, as declared. */
18
+ declaration: unknown;
19
+ kind: MiniAppActionKind;
20
+ params: MiniAppActionSchema | null;
21
+ /** The built module, as the loader would read it. */
22
+ source: string;
23
+ sha256: string;
24
+ }
25
+ /** The action as the local build declares it. Whether the module implements
26
+ * it shows when it runs; `parall app check` compares the two. */
27
+ export declare function readLocalAction(dist: string, name: string): Promise<LocalAction>;
28
+ type Client = ReturnType<typeof resolveCredentials>['client'];
29
+ /** What a caller may follow of a run besides its answer (the dev host shows
30
+ * both next to the page). */
31
+ export interface LocalRunObserver {
32
+ /** The action's console output, as the runner prints it. */
33
+ console?: (text: string) => void;
34
+ /** The data_seq range its writes committed under. */
35
+ committed?: (dataSeq: {
36
+ from: number;
37
+ to: number;
38
+ }) => void;
39
+ }
40
+ /** Runs the action and returns what a deployed call returns; a failure is the
41
+ * ApiError a deployed call raises, with the details an author sees. */
42
+ export declare function runLocalAction(client: Client, orgId: string, appId: string, apiUrl: string, dist: string, name: string, action: LocalAction, params: Record<string, unknown>, observe?: LocalRunObserver): Promise<MiniAppActionInvokeResult>;
43
+ export {};
44
+ //# sourceMappingURL=apps-action-local.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"apps-action-local.d.ts","sourceRoot":"","sources":["../../src/commands/apps-action-local.ts"],"names":[],"mappings":"AAGA,OAAO,EAEL,KAAK,yBAAyB,EAC9B,KAAK,iBAAiB,EACtB,KAAK,mBAAmB,EACzB,MAAM,aAAa,CAAC;AACrB,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAQ3D;;;;;;;;;;;;cAYc;AAEd,MAAM,WAAW,WAAW;IAC1B,+DAA+D;IAC/D,WAAW,EAAE,OAAO,CAAC;IACrB,IAAI,EAAE,iBAAiB,CAAC;IACxB,MAAM,EAAE,mBAAmB,GAAG,IAAI,CAAC;IACnC,qDAAqD;IACrD,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;CAChB;AAED;iEACiE;AACjE,wBAAsB,eAAe,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,WAAW,CAAC,CAiBtF;AAED,KAAK,MAAM,GAAG,UAAU,CAAC,OAAO,kBAAkB,CAAC,CAAC,QAAQ,CAAC,CAAC;AAU9D;6BAC6B;AAC7B,MAAM,WAAW,gBAAgB;IAC/B,4DAA4D;IAC5D,OAAO,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;IACjC,qDAAqD;IACrD,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,EAAE,EAAE,MAAM,CAAA;KAAE,KAAK,IAAI,CAAC;CAC7D;AAMD;uEACuE;AACvE,wBAAsB,cAAc,CAClC,MAAM,EAAE,MAAM,EACd,KAAK,EAAE,MAAM,EACb,KAAK,EAAE,MAAM,EACb,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,WAAW,EACnB,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC/B,OAAO,GAAE,gBAAqB,GAC7B,OAAO,CAAC,yBAAyB,CAAC,CAgEpC"}
@@ -0,0 +1,153 @@
1
+ import { createRequire } from 'node:module';
2
+ import { join } from 'node:path';
3
+ import { pathToFileURL } from 'node:url';
4
+ import { ApiError, } from '@parall/sdk';
5
+ import { readActionModule } from './apps-check.js';
6
+ import { MINIFLARE_RANGE } from './apps-scaffold-actions.js';
7
+ import { LOCAL_RUNNER_COMPATIBILITY_DATE, LOCAL_RUNNER_SOURCE, } from './apps-local-runner.generated.js';
8
+ /** The action as the local build declares it. Whether the module implements
9
+ * it shows when it runs; `parall app check` compares the two. */
10
+ export async function readLocalAction(dist, name) {
11
+ const module = await readActionModule(dist);
12
+ if (!module)
13
+ throw new Error(`${dist}/manifest.json declares no actions`);
14
+ const declared = module.functions[name];
15
+ if (!declared || typeof declared !== 'object') {
16
+ const names = Object.keys(module.functions).sort().join(', ') || 'none';
17
+ throw new Error(`the local build has no action ${JSON.stringify(name)} (it has: ${names})`);
18
+ }
19
+ return {
20
+ declaration: declared,
21
+ kind: declared.kind === 'write' ? 'write' : 'read',
22
+ params: declared.params ?? null,
23
+ source: module.source,
24
+ sha256: module.sha256,
25
+ };
26
+ }
27
+ // How long past the run's deadline the runner may take to answer before the
28
+ // CLI gives up on it (it reports its own timeout before the deadline).
29
+ const RUNNER_GRACE_MS = 5_000;
30
+ /** Runs the action and returns what a deployed call returns; a failure is the
31
+ * ApiError a deployed call raises, with the details an author sees. */
32
+ export async function runLocalAction(client, orgId, appId, apiUrl, dist, name, action, params, observe = {}) {
33
+ const Miniflare = await loadMiniflare(dist);
34
+ const mf = new Miniflare({
35
+ modules: true,
36
+ script: LOCAL_RUNNER_SOURCE,
37
+ compatibilityDate: LOCAL_RUNNER_COMPATIBILITY_DATE,
38
+ workerLoaders: { LOADER: {} },
39
+ // The action's console output: stderr, so stdout stays the result.
40
+ handleRuntimeStdio(stdout, stderr) {
41
+ stdout.pipe(process.stderr);
42
+ stderr.pipe(process.stderr);
43
+ const follow = observe.console;
44
+ if (follow) {
45
+ for (const stream of [stdout, stderr])
46
+ stream.on('data', (chunk) => follow(String(chunk)));
47
+ }
48
+ },
49
+ });
50
+ try {
51
+ await mf.ready;
52
+ // The ticket last: its deadline starts when it is issued.
53
+ const dev = await client.createMiniAppDevInvocation(orgId, appId, {
54
+ action: name,
55
+ declaration: action.declaration,
56
+ params,
57
+ });
58
+ const request = {
59
+ invocation_id: dev.invocation_id,
60
+ instance: dev.instance,
61
+ app: { id: appId, version_seq: 0 },
62
+ module: { sha256: action.sha256 },
63
+ action: name,
64
+ kind: action.kind,
65
+ params: dev.params,
66
+ viewer: dev.viewer,
67
+ ticket: dev.ticket,
68
+ deadline_ms: dev.deadline_ms,
69
+ limits: dev.limits,
70
+ };
71
+ const answered = mf.dispatchFetch('http://local/run', {
72
+ method: 'POST',
73
+ body: JSON.stringify({ source: action.source, callback_origin: apiUrl, request }),
74
+ });
75
+ // A runner that never answers is a timeout: the writes it started may
76
+ // have committed.
77
+ let timer;
78
+ const gaveUp = new Promise((_, reject) => {
79
+ timer = setTimeout(() => reject(timeoutError(dev.invocation_id, action.kind)), Math.max(dev.deadline_ms - Date.now(), 0) + RUNNER_GRACE_MS);
80
+ });
81
+ let res;
82
+ try {
83
+ res = await Promise.race([answered, gaveUp]);
84
+ }
85
+ finally {
86
+ clearTimeout(timer);
87
+ }
88
+ if (!res.ok)
89
+ throw new Error(`the local runner refused the run: ${await res.text()}`);
90
+ const out = (await res.json());
91
+ if (out.data_seq)
92
+ observe.committed?.(out.data_seq);
93
+ return outcomeResult(dev.invocation_id, action.kind, out);
94
+ }
95
+ finally {
96
+ await mf.dispose();
97
+ }
98
+ }
99
+ /** The answer a deployed call gives for the outcome, as api-server maps it
100
+ * for a caller with app.publish (server mini_app_action_outcome.go). */
101
+ function outcomeResult(invocationId, kind, out) {
102
+ if (out.status === 'ok') {
103
+ return { invocation_id: invocationId, result: JSON.parse(out.result_json ?? 'null') };
104
+ }
105
+ const details = { invocation_id: invocationId };
106
+ const message = out.error?.message;
107
+ let err;
108
+ if (out.status === 'limit_exceeded') {
109
+ err = new ApiError(422, message || 'The action exceeded its limits', 'ACTION_LIMIT_EXCEEDED');
110
+ }
111
+ else if (out.status === 'timeout') {
112
+ throw timeoutError(invocationId, kind);
113
+ }
114
+ else if (out.error?.kind === 'action_error') {
115
+ details.error_kind = 'action_error';
116
+ err = new ApiError(422, message || 'The action failed', 'ACTION_FAILED');
117
+ }
118
+ else {
119
+ details.error_kind = 'unexpected';
120
+ if (out.error?.stack)
121
+ details.stack = out.error.stack;
122
+ err = new ApiError(422, message || 'The action failed unexpectedly', 'ACTION_FAILED');
123
+ }
124
+ err.extras = { details };
125
+ throw err;
126
+ }
127
+ function timeoutError(invocationId, kind) {
128
+ const err = new ApiError(422, kind === 'write'
129
+ ? 'The action did not finish within its deadline or lost a database answer; writes it started may have committed'
130
+ : 'The action did not finish within its deadline', 'ACTION_TIMEOUT');
131
+ err.extras = { details: { invocation_id: invocationId } };
132
+ return err;
133
+ }
134
+ /** miniflare from the app project (the --actions scaffold has it as a dev
135
+ * dependency): the CLI does not carry workerd. */
136
+ async function loadMiniflare(dist) {
137
+ let resolved;
138
+ for (const from of [join(dist, 'noop.js'), join(process.cwd(), 'noop.js')]) {
139
+ try {
140
+ resolved = createRequire(from).resolve('miniflare');
141
+ break;
142
+ }
143
+ catch { }
144
+ }
145
+ if (!resolved) {
146
+ throw new Error(`a local run needs miniflare in the app project: run \`pnpm add -D miniflare@${MINIFLARE_RANGE}\` there (\`parall app init --actions\` adds it)`);
147
+ }
148
+ const mod = (await import(pathToFileURL(resolved).href));
149
+ const Miniflare = mod.Miniflare ?? mod.default?.Miniflare;
150
+ if (typeof Miniflare !== 'function')
151
+ throw new Error(`${resolved} does not export Miniflare`);
152
+ return Miniflare;
153
+ }
@@ -0,0 +1,14 @@
1
+ /** Maps a stack from the action isolate back to source
2
+ * (docs/engineering-design/mini-app-action-design.md §10.2). The loader
3
+ * mounts the module as author.js (ts/actions-worker src/sandbox.ts), so
4
+ * frames read `at fn (author.js:LINE:COL)`. The local build's source map
5
+ * only applies when the local module is byte for byte the one that ran:
6
+ * its sha256 must equal the version's action_module_sha256. */
7
+ export interface MappedStack {
8
+ stack: string;
9
+ mapped: boolean;
10
+ /** Why the stack was left as the isolate reported it. */
11
+ note?: string;
12
+ }
13
+ export declare function mapActionStack(stack: string, dist: string, moduleSha256: string | undefined): Promise<MappedStack>;
14
+ //# sourceMappingURL=apps-action-stack.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"apps-action-stack.d.ts","sourceRoot":"","sources":["../../src/commands/apps-action-stack.ts"],"names":[],"mappings":"AAMA;;;;;+DAK+D;AAC/D,MAAM,WAAW,WAAW;IAC1B,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,OAAO,CAAC;IAChB,yDAAyD;IACzD,IAAI,CAAC,EAAE,MAAM,CAAC;CACf;AAID,wBAAsB,cAAc,CAClC,KAAK,EAAE,MAAM,EACb,IAAI,EAAE,MAAM,EACZ,YAAY,EAAE,MAAM,GAAG,SAAS,GAC/B,OAAO,CAAC,WAAW,CAAC,CA6CtB"}
@@ -0,0 +1,63 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { promises as fs } from 'node:fs';
3
+ import { SourceMap } from 'node:module';
4
+ import { dirname, join, relative, resolve } from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+ const FRAME = /\bauthor\.js:(\d+):(\d+)/g;
7
+ export async function mapActionStack(stack, dist, moduleSha256) {
8
+ const unmapped = (note) => ({ stack, mapped: false, note });
9
+ if (!moduleSha256)
10
+ return unmapped('the version records no action module digest');
11
+ let entry;
12
+ try {
13
+ entry = JSON.parse(await fs.readFile(join(dist, 'manifest.json'), 'utf8'))?.actions?.entry;
14
+ }
15
+ catch {
16
+ return unmapped(`no built bundle at ${dist}`);
17
+ }
18
+ if (typeof entry !== 'string')
19
+ return unmapped(`${dist}/manifest.json declares no actions`);
20
+ const modulePath = join(dist, entry);
21
+ let module;
22
+ try {
23
+ module = await fs.readFile(modulePath);
24
+ }
25
+ catch {
26
+ return unmapped(`${modulePath} is missing`);
27
+ }
28
+ if (createHash('sha256').update(module).digest('hex') !== moduleSha256) {
29
+ return unmapped(`${modulePath} is not the module that ran; build the version's source to map the stack`);
30
+ }
31
+ const mapPath = await sourceMapPath(modulePath, module.toString('utf8'));
32
+ let map;
33
+ try {
34
+ map = new SourceMap(JSON.parse(await fs.readFile(mapPath, 'utf8')));
35
+ }
36
+ catch {
37
+ return unmapped(`no readable source map at ${mapPath}`);
38
+ }
39
+ let hits = 0;
40
+ const mapped = stack.replace(FRAME, (frame, line, column) => {
41
+ const at = map.findEntry(Number(line) - 1, Number(column) - 1);
42
+ if (!at.originalSource || at.originalLine === undefined || at.originalColumn === undefined) {
43
+ return frame;
44
+ }
45
+ hits++;
46
+ return `${sourcePath(at.originalSource, mapPath)}:${at.originalLine + 1}:${at.originalColumn + 1}`;
47
+ });
48
+ return hits > 0
49
+ ? { stack: mapped, mapped: true }
50
+ : unmapped('no frame of the stack is in the module');
51
+ }
52
+ async function sourceMapPath(modulePath, source) {
53
+ const comment = source.match(/\/\/# sourceMappingURL=([^\s'"]+)\s*$/);
54
+ if (comment && !comment[1].startsWith('data:'))
55
+ return resolve(dirname(modulePath), comment[1]);
56
+ return `${modulePath}.map`;
57
+ }
58
+ function sourcePath(source, mapPath) {
59
+ const absolute = source.startsWith('file://')
60
+ ? fileURLToPath(source)
61
+ : resolve(dirname(mapPath), source);
62
+ return relative(process.cwd(), absolute) || absolute;
63
+ }
@@ -0,0 +1,2 @@
1
+ export declare const ACTIONS_SDK_SOURCE = "/**\n * @parall/miniapp-sdk/actions \u2014 the action side of a Mini App\n * (docs/engineering-design/mini-app-action-design.md \u00A72): `defineActions`\n * turns the author's functions into the module entry the action loader\n * calls; `ActionError` is the error whose message the caller may see.\n *\n * This file runs inside the Cloudflare isolate, not in the page. It is the\n * only part of the SDK that imports `cloudflare:workers`, and an action\n * module is built from it into one file whose sole external import is that\n * one. Export the result as `ActionRunner` \u2014 the loader looks it up by name:\n *\n * export const ActionRunner = defineActions({\n * async addNote(ctx, { text }) {\n * const { rows } = await ctx.db.exec(\n * 'INSERT INTO notes (text, created_by) VALUES ($1, $2) RETURNING id',\n * [text, ctx.viewer.id],\n * );\n * return rows[0];\n * },\n * });\n *\n * Security does not depend on this wrapper: the loader accepts only the two\n * result shapes run() returns, whatever produced them (design \u00A73.1).\n */\n\nimport { WorkerEntrypoint } from 'cloudflare:workers';\n\n/** An error whose message reaches every caller as is (ACTION_FAILED with\n * error_kind action_error). Anything else thrown is an unexpected failure. */\nexport class ActionError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ActionError';\n }\n}\n\n/** A database call that was refused or failed. `code` is the platform's:\n * SQL_ERROR, SQL_REJECTED, ACTION_READ_ONLY, ACTION_LIMIT_EXCEEDED, \u2026 */\nexport class ActionDbError extends Error {\n readonly code: string;\n\n constructor(code: string, message: string) {\n super(message);\n this.name = 'ActionDbError';\n this.code = code;\n }\n}\n\n/** The caller, as the platform vouches for it (design \u00A72.2). */\nexport interface ActionViewer {\n id: string;\n display_name: string;\n is_agent: boolean;\n /** Organization role: owner, admin or member. */\n role: string;\n}\n\nexport interface ActionApp {\n id: string;\n version_seq: number;\n}\n\n/** A row as an object keyed by column name, in select-list order. */\nexport type ActionRow = Record<string, unknown>;\n\nexport interface ActionQueryResult {\n rows: ActionRow[];\n truncated: boolean;\n}\n\nexport interface ActionStatementResult {\n rows: ActionRow[];\n rows_affected: number;\n truncated: boolean;\n}\n\nexport interface ActionExecResult extends ActionStatementResult {\n data_seq: number;\n}\n\nexport interface ActionBatchStatement {\n sql: string;\n params?: unknown[];\n}\n\nexport interface ActionBatchResult {\n results: ActionStatementResult[];\n data_seq: number;\n}\n\n/** ctx.db: one statement per query / exec; a batch is one transaction. */\nexport interface ActionDb {\n query(sql: string, params?: unknown[]): Promise<ActionQueryResult>;\n /** Write actions only. */\n exec(sql: string, params?: unknown[]): Promise<ActionExecResult>;\n /** Write actions only; at most 50 statements, counted as one call. */\n batch(statements: ActionBatchStatement[]): Promise<ActionBatchResult>;\n}\n\nexport interface ActionContext {\n viewer: ActionViewer;\n app: ActionApp;\n db: ActionDb;\n}\n\n// biome-ignore lint/suspicious/noExplicitAny: the platform validates params against the declared schema before the call\nexport type ActionFunction = (ctx: ActionContext, params: any) => unknown;\n\n/** What the loader passes run() (ts/actions-worker src/invoke.ts). */\nexport interface ActionRunRequest {\n action: string;\n params: unknown;\n viewer: ActionViewer;\n app: ActionApp;\n}\n\n/** The only two shapes the loader accepts back (ts/actions-worker src/outcome.ts). */\nexport type ActionRunResult =\n | { ok: true; json: string }\n | { ok: false; error: { kind: 'action_error' | 'unexpected'; message: string; stack?: string } };\n\n/** What a handle method resolves to. Failures travel as values because\n * Workers RPC keeps only an exception's name and message (design \u00A76). */\nexport type ActionHandleResult =\n | { ok: true; value: unknown }\n | { ok: false; error: { code: string; message: string } };\n\n/** The per-invocation database handle the loader passes run(). */\nexport interface ActionHandle {\n query(sql: string, params: unknown[]): Promise<ActionHandleResult>;\n exec(sql: string, params: unknown[]): Promise<ActionHandleResult>;\n batch(statements: ActionBatchStatement[]): Promise<ActionHandleResult>;\n}\n\n/** What defineActions returns; export it as `ActionRunner`. */\nexport interface ActionRunnerClass {\n /** The actions the module implements, sorted; `parall app check` compares\n * them with the manifest. */\n readonly actions: readonly string[];\n new (\n ctx: unknown,\n env: unknown,\n ): { run(req: ActionRunRequest, handle: ActionHandle): Promise<ActionRunResult> };\n}\n\nfunction unwrap(result: ActionHandleResult): unknown {\n if (result?.ok === true) return result.value;\n if (result?.ok === false) throw new ActionDbError(result.error.code, result.error.message);\n throw new ActionDbError(\n 'ACTION_DB_UNAVAILABLE',\n 'the database handle answered in an unknown shape',\n );\n}\n\nfunction failure(err: unknown): ActionRunResult {\n if (err instanceof ActionError || (err instanceof Error && err.name === 'ActionError')) {\n return { ok: false, error: { kind: 'action_error', message: err.message } };\n }\n const e = err instanceof Error ? err : new Error(String(err));\n const label = e instanceof ActionDbError ? `${e.name} ${e.code}` : e.name;\n return {\n ok: false,\n error: { kind: 'unexpected', message: `${label}: ${e.message}`, stack: e.stack ?? '' },\n };\n}\n\n/** A database call as the author's code holds it. It notes whether the code\n * attached a rejection handler anywhere along its chain \u2014 `await`,\n * `try`/`catch`, `.catch()`, `.then(f).catch(g)`, `Promise.all` all do \u2014 so\n * a failure nobody looked at fails the action instead of being lost.\n * Promises derived from a call point back to it. */\nclass DbCall<T> extends Promise<T> {\n handled = false;\n origin?: DbCall<unknown>;\n #inFinally = false;\n\n override then<R1 = T, R2 = never>(\n onFulfilled?: ((value: T) => R1 | PromiseLike<R1>) | null,\n onRejected?: ((reason: unknown) => R2 | PromiseLike<R2>) | null,\n ): Promise<R1 | R2> {\n const origin = this.origin ?? this;\n if (typeof onRejected === 'function' && !this.#inFinally) origin.handled = true;\n const derived = super.then(onFulfilled, onRejected) as DbCall<R1 | R2>;\n derived.origin = origin;\n return derived;\n }\n\n // finally() calls then() with a rejection handler that throws the failure\n // on: it handles nothing. A catch on what it returns still counts.\n override finally(onFinally?: (() => void) | null): Promise<T> {\n this.#inFinally = true;\n try {\n return super.finally(onFinally);\n } finally {\n this.#inFinally = false;\n }\n }\n}\n\n// The wrapper's own bookkeeping on a DbCall, which must not count as the\n// author handling it.\nconst observe = Promise.prototype.then as <T>(\n this: Promise<T>,\n onFulfilled: (value: T) => unknown,\n onRejected?: (reason: unknown) => unknown,\n) => Promise<unknown>;\n\n/** Wraps the author's functions into the module entry the loader calls. */\nexport function defineActions(actions: Record<string, ActionFunction>): ActionRunnerClass {\n const names = Object.keys(actions).sort();\n // Not named ActionRunner: the author's export usually is, and a bundler\n // would rename this class to tell the two apart.\n class ActionEntrypoint extends WorkerEntrypoint {\n static readonly actions: readonly string[] = names;\n\n async run(req: ActionRunRequest, handle: ActionHandle): Promise<ActionRunResult> {\n // Database calls still in flight are waited for before answering \u2014 a\n // write the author forgot to await commits before the caller has the\n // result. Calls started from a finishing call are waited for too; the\n // loader refuses any that arrive after run() returns.\n const pending = new Set<Promise<unknown>>();\n const failed = new Map<DbCall<unknown>, unknown>();\n const track = <T>(call: Promise<ActionHandleResult>): Promise<T> => {\n const dbCall = new DbCall<T>((resolve, reject) => {\n call.then(unwrap).then(resolve as (value: unknown) => void, reject);\n });\n const settled = observe.call(\n dbCall,\n () => undefined,\n (err) => {\n failed.set(dbCall, err);\n },\n );\n pending.add(settled);\n observe.call(settled, () => pending.delete(settled));\n return dbCall;\n };\n const drain = async () => {\n while (pending.size > 0) await Promise.allSettled([...pending]);\n };\n const db: ActionDb = {\n query: (sql, params = []) => track(handle.query(sql, params)),\n exec: (sql, params = []) => track(handle.exec(sql, params)),\n batch: (statements) => track(handle.batch(statements)),\n };\n try {\n const fn = Object.hasOwn(actions, req.action) ? actions[req.action] : undefined;\n if (typeof fn !== 'function') {\n throw new Error(\n `this module does not implement the action ${JSON.stringify(req.action)}`,\n );\n }\n const value = await fn({ viewer: req.viewer, app: req.app, db }, req.params);\n await drain();\n // A call that failed while the code never looked at it (a forgotten\n // await) fails the action: answering ok would claim a write that did\n // not happen.\n for (const [dbCall, err] of failed) if (!dbCall.handled) throw err;\n const json = JSON.stringify(value === undefined ? null : value);\n if (typeof json !== 'string') {\n throw new TypeError('the action returned a value JSON cannot represent');\n }\n return { ok: true, json };\n } catch (err) {\n await drain();\n return failure(err);\n }\n }\n }\n return ActionEntrypoint;\n}\n";
2
+ //# sourceMappingURL=apps-actions-sdk.generated.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"apps-actions-sdk.generated.d.ts","sourceRoot":"","sources":["../../src/commands/apps-actions-sdk.generated.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,kBAAkB,49TAA06T,CAAC"}
@@ -0,0 +1,3 @@
1
+ // Generated from ts/miniapp-sdk/src/actions.ts by scripts/generate-miniapp-sdk.mjs. Do not edit.
2
+ // biome-ignore format: generated copy
3
+ export const ACTIONS_SDK_SOURCE = "/**\n * @parall/miniapp-sdk/actions — the action side of a Mini App\n * (docs/engineering-design/mini-app-action-design.md §2): `defineActions`\n * turns the author's functions into the module entry the action loader\n * calls; `ActionError` is the error whose message the caller may see.\n *\n * This file runs inside the Cloudflare isolate, not in the page. It is the\n * only part of the SDK that imports `cloudflare:workers`, and an action\n * module is built from it into one file whose sole external import is that\n * one. Export the result as `ActionRunner` — the loader looks it up by name:\n *\n * export const ActionRunner = defineActions({\n * async addNote(ctx, { text }) {\n * const { rows } = await ctx.db.exec(\n * 'INSERT INTO notes (text, created_by) VALUES ($1, $2) RETURNING id',\n * [text, ctx.viewer.id],\n * );\n * return rows[0];\n * },\n * });\n *\n * Security does not depend on this wrapper: the loader accepts only the two\n * result shapes run() returns, whatever produced them (design §3.1).\n */\n\nimport { WorkerEntrypoint } from 'cloudflare:workers';\n\n/** An error whose message reaches every caller as is (ACTION_FAILED with\n * error_kind action_error). Anything else thrown is an unexpected failure. */\nexport class ActionError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ActionError';\n }\n}\n\n/** A database call that was refused or failed. `code` is the platform's:\n * SQL_ERROR, SQL_REJECTED, ACTION_READ_ONLY, ACTION_LIMIT_EXCEEDED, … */\nexport class ActionDbError extends Error {\n readonly code: string;\n\n constructor(code: string, message: string) {\n super(message);\n this.name = 'ActionDbError';\n this.code = code;\n }\n}\n\n/** The caller, as the platform vouches for it (design §2.2). */\nexport interface ActionViewer {\n id: string;\n display_name: string;\n is_agent: boolean;\n /** Organization role: owner, admin or member. */\n role: string;\n}\n\nexport interface ActionApp {\n id: string;\n version_seq: number;\n}\n\n/** A row as an object keyed by column name, in select-list order. */\nexport type ActionRow = Record<string, unknown>;\n\nexport interface ActionQueryResult {\n rows: ActionRow[];\n truncated: boolean;\n}\n\nexport interface ActionStatementResult {\n rows: ActionRow[];\n rows_affected: number;\n truncated: boolean;\n}\n\nexport interface ActionExecResult extends ActionStatementResult {\n data_seq: number;\n}\n\nexport interface ActionBatchStatement {\n sql: string;\n params?: unknown[];\n}\n\nexport interface ActionBatchResult {\n results: ActionStatementResult[];\n data_seq: number;\n}\n\n/** ctx.db: one statement per query / exec; a batch is one transaction. */\nexport interface ActionDb {\n query(sql: string, params?: unknown[]): Promise<ActionQueryResult>;\n /** Write actions only. */\n exec(sql: string, params?: unknown[]): Promise<ActionExecResult>;\n /** Write actions only; at most 50 statements, counted as one call. */\n batch(statements: ActionBatchStatement[]): Promise<ActionBatchResult>;\n}\n\nexport interface ActionContext {\n viewer: ActionViewer;\n app: ActionApp;\n db: ActionDb;\n}\n\n// biome-ignore lint/suspicious/noExplicitAny: the platform validates params against the declared schema before the call\nexport type ActionFunction = (ctx: ActionContext, params: any) => unknown;\n\n/** What the loader passes run() (ts/actions-worker src/invoke.ts). */\nexport interface ActionRunRequest {\n action: string;\n params: unknown;\n viewer: ActionViewer;\n app: ActionApp;\n}\n\n/** The only two shapes the loader accepts back (ts/actions-worker src/outcome.ts). */\nexport type ActionRunResult =\n | { ok: true; json: string }\n | { ok: false; error: { kind: 'action_error' | 'unexpected'; message: string; stack?: string } };\n\n/** What a handle method resolves to. Failures travel as values because\n * Workers RPC keeps only an exception's name and message (design §6). */\nexport type ActionHandleResult =\n | { ok: true; value: unknown }\n | { ok: false; error: { code: string; message: string } };\n\n/** The per-invocation database handle the loader passes run(). */\nexport interface ActionHandle {\n query(sql: string, params: unknown[]): Promise<ActionHandleResult>;\n exec(sql: string, params: unknown[]): Promise<ActionHandleResult>;\n batch(statements: ActionBatchStatement[]): Promise<ActionHandleResult>;\n}\n\n/** What defineActions returns; export it as `ActionRunner`. */\nexport interface ActionRunnerClass {\n /** The actions the module implements, sorted; `parall app check` compares\n * them with the manifest. */\n readonly actions: readonly string[];\n new (\n ctx: unknown,\n env: unknown,\n ): { run(req: ActionRunRequest, handle: ActionHandle): Promise<ActionRunResult> };\n}\n\nfunction unwrap(result: ActionHandleResult): unknown {\n if (result?.ok === true) return result.value;\n if (result?.ok === false) throw new ActionDbError(result.error.code, result.error.message);\n throw new ActionDbError(\n 'ACTION_DB_UNAVAILABLE',\n 'the database handle answered in an unknown shape',\n );\n}\n\nfunction failure(err: unknown): ActionRunResult {\n if (err instanceof ActionError || (err instanceof Error && err.name === 'ActionError')) {\n return { ok: false, error: { kind: 'action_error', message: err.message } };\n }\n const e = err instanceof Error ? err : new Error(String(err));\n const label = e instanceof ActionDbError ? `${e.name} ${e.code}` : e.name;\n return {\n ok: false,\n error: { kind: 'unexpected', message: `${label}: ${e.message}`, stack: e.stack ?? '' },\n };\n}\n\n/** A database call as the author's code holds it. It notes whether the code\n * attached a rejection handler anywhere along its chain — `await`,\n * `try`/`catch`, `.catch()`, `.then(f).catch(g)`, `Promise.all` all do — so\n * a failure nobody looked at fails the action instead of being lost.\n * Promises derived from a call point back to it. */\nclass DbCall<T> extends Promise<T> {\n handled = false;\n origin?: DbCall<unknown>;\n #inFinally = false;\n\n override then<R1 = T, R2 = never>(\n onFulfilled?: ((value: T) => R1 | PromiseLike<R1>) | null,\n onRejected?: ((reason: unknown) => R2 | PromiseLike<R2>) | null,\n ): Promise<R1 | R2> {\n const origin = this.origin ?? this;\n if (typeof onRejected === 'function' && !this.#inFinally) origin.handled = true;\n const derived = super.then(onFulfilled, onRejected) as DbCall<R1 | R2>;\n derived.origin = origin;\n return derived;\n }\n\n // finally() calls then() with a rejection handler that throws the failure\n // on: it handles nothing. A catch on what it returns still counts.\n override finally(onFinally?: (() => void) | null): Promise<T> {\n this.#inFinally = true;\n try {\n return super.finally(onFinally);\n } finally {\n this.#inFinally = false;\n }\n }\n}\n\n// The wrapper's own bookkeeping on a DbCall, which must not count as the\n// author handling it.\nconst observe = Promise.prototype.then as <T>(\n this: Promise<T>,\n onFulfilled: (value: T) => unknown,\n onRejected?: (reason: unknown) => unknown,\n) => Promise<unknown>;\n\n/** Wraps the author's functions into the module entry the loader calls. */\nexport function defineActions(actions: Record<string, ActionFunction>): ActionRunnerClass {\n const names = Object.keys(actions).sort();\n // Not named ActionRunner: the author's export usually is, and a bundler\n // would rename this class to tell the two apart.\n class ActionEntrypoint extends WorkerEntrypoint {\n static readonly actions: readonly string[] = names;\n\n async run(req: ActionRunRequest, handle: ActionHandle): Promise<ActionRunResult> {\n // Database calls still in flight are waited for before answering — a\n // write the author forgot to await commits before the caller has the\n // result. Calls started from a finishing call are waited for too; the\n // loader refuses any that arrive after run() returns.\n const pending = new Set<Promise<unknown>>();\n const failed = new Map<DbCall<unknown>, unknown>();\n const track = <T>(call: Promise<ActionHandleResult>): Promise<T> => {\n const dbCall = new DbCall<T>((resolve, reject) => {\n call.then(unwrap).then(resolve as (value: unknown) => void, reject);\n });\n const settled = observe.call(\n dbCall,\n () => undefined,\n (err) => {\n failed.set(dbCall, err);\n },\n );\n pending.add(settled);\n observe.call(settled, () => pending.delete(settled));\n return dbCall;\n };\n const drain = async () => {\n while (pending.size > 0) await Promise.allSettled([...pending]);\n };\n const db: ActionDb = {\n query: (sql, params = []) => track(handle.query(sql, params)),\n exec: (sql, params = []) => track(handle.exec(sql, params)),\n batch: (statements) => track(handle.batch(statements)),\n };\n try {\n const fn = Object.hasOwn(actions, req.action) ? actions[req.action] : undefined;\n if (typeof fn !== 'function') {\n throw new Error(\n `this module does not implement the action ${JSON.stringify(req.action)}`,\n );\n }\n const value = await fn({ viewer: req.viewer, app: req.app, db }, req.params);\n await drain();\n // A call that failed while the code never looked at it (a forgotten\n // await) fails the action: answering ok would claim a write that did\n // not happen.\n for (const [dbCall, err] of failed) if (!dbCall.handled) throw err;\n const json = JSON.stringify(value === undefined ? null : value);\n if (typeof json !== 'string') {\n throw new TypeError('the action returned a value JSON cannot represent');\n }\n return { ok: true, json };\n } catch (err) {\n await drain();\n return failure(err);\n }\n }\n }\n return ActionEntrypoint;\n}\n";
@@ -0,0 +1,20 @@
1
+ import { type MiniAppActionSchema } from '@parall/sdk';
2
+ import type { Command } from 'commander';
3
+ /** `parall app action list | run | log`
4
+ * (docs/engineering-design/mini-app-action-design.md §3, §5.3, §10): the
5
+ * same endpoints the page calls, for agents and authors. Anyone who can open
6
+ * the app lists and runs its actions; `--v` names a version other than the
7
+ * current one, and `--local` runs the local build (apps-action-local.ts),
8
+ * both of which take the app's authors or an org owner/admin. */
9
+ export declare function registerAppActionCommands(app: Command): void;
10
+ interface ParamOptions {
11
+ param?: string[];
12
+ params?: string;
13
+ paramsFile?: string;
14
+ }
15
+ /** The params object of a call: --params-file or --params as the base, then
16
+ * each --param converted to the type its property declares. A key the
17
+ * schema does not declare is refused here unless it allows extra keys. */
18
+ export declare function buildParams(schema: MiniAppActionSchema | null, opts: ParamOptions): Promise<Record<string, unknown>>;
19
+ export {};
20
+ //# sourceMappingURL=apps-actions.d.ts.map
@@ -0,0 +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;AAMzC;;;;;iEAKiE;AACjE,wBAAgB,yBAAyB,CAAC,GAAG,EAAE,OAAO,QAyIrD;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"}
@@ -0,0 +1,266 @@
1
+ import { promises as fs } from 'node:fs';
2
+ import { resolve } from 'node:path';
3
+ import { ApiError, } from '@parall/sdk';
4
+ import { resolveCredentials } from '../lib/client.js';
5
+ import { parsePositiveInt, printError, printJson, stripPrllScheme } from '../lib/output.js';
6
+ import { readLocalAction, runLocalAction } from './apps-action-local.js';
7
+ import { mapActionStack } from './apps-action-stack.js';
8
+ /** `parall app action list | run | log`
9
+ * (docs/engineering-design/mini-app-action-design.md §3, §5.3, §10): the
10
+ * same endpoints the page calls, for agents and authors. Anyone who can open
11
+ * the app lists and runs its actions; `--v` names a version other than the
12
+ * current one, and `--local` runs the local build (apps-action-local.ts),
13
+ * both of which take the app's authors or an org owner/admin. */
14
+ export function registerAppActionCommands(app) {
15
+ const action = app
16
+ .command('action')
17
+ .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')
22
+ .option('--v <seq>', 'Version seq (default: the current one)')
23
+ .action(async (appId, opts) => {
24
+ try {
25
+ const { client, orgId } = resolveCredentials();
26
+ printJson(await client.getMiniAppActions(orgId, stripPrllScheme(appId), version(opts.v)));
27
+ }
28
+ catch (err) {
29
+ printError(err);
30
+ }
31
+ });
32
+ action
33
+ .command('run')
34
+ .description('Run one action and print its result')
35
+ .argument('<appId>', 'App ID')
36
+ .argument('<name>', 'Action name')
37
+ .option('--param <key=value>', 'One param; the value is converted to the declared type (repeatable)', collect, [])
38
+ .option('--params <json>', 'All params as a JSON object (--param entries override)')
39
+ .option('--params-file <file>', 'All params from a JSON file (--param entries override)')
40
+ .option('--v <seq>', 'Version seq (default: the current one)')
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
+ .option('--dist <dir>', 'Local build: what --local runs, and the map for a failure stack', 'dist')
43
+ .action(async (appId, name, opts) => {
44
+ let invoked;
45
+ try {
46
+ const { client, orgId } = resolveCredentials();
47
+ const id = stripPrllScheme(appId);
48
+ if (opts.local) {
49
+ if (opts.v !== undefined)
50
+ throw new Error('--local runs the local build; it takes no --v');
51
+ const dist = resolve(opts.dist);
52
+ const local = await readLocalAction(dist, name);
53
+ const params = await buildParams(local.params, opts);
54
+ invoked = {
55
+ client,
56
+ orgId,
57
+ appId: id,
58
+ seq: 0,
59
+ kind: local.kind,
60
+ dist: opts.dist,
61
+ localSha256: local.sha256,
62
+ };
63
+ const apiUrl = process.env.PRLL_API_URL ?? '';
64
+ printJson(await runLocalAction(client, orgId, id, apiUrl, dist, name, local, params));
65
+ return;
66
+ }
67
+ // The listing pins the version: the call runs exactly the one whose
68
+ // schema converted the params (and whose module maps the stack).
69
+ const list = await client.getMiniAppActions(orgId, id, version(opts.v));
70
+ const declared = list.data.find((a) => a.name === name);
71
+ if (!declared) {
72
+ const names = list.data.map((a) => a.name).join(', ') || 'none';
73
+ throw new Error(`version ${list.version_seq} has no action ${JSON.stringify(name)} (it has: ${names})`);
74
+ }
75
+ const params = await buildParams(declared.params, opts);
76
+ invoked = {
77
+ client,
78
+ orgId,
79
+ appId: id,
80
+ seq: list.version_seq,
81
+ kind: declared.kind,
82
+ dist: opts.dist,
83
+ };
84
+ printJson(await client.invokeMiniAppAction(orgId, id, name, params, list.version_seq));
85
+ }
86
+ catch (err) {
87
+ if (err instanceof ApiError && invoked) {
88
+ printError(err, undefined, await explainFailure(err, invoked));
89
+ }
90
+ printError(err);
91
+ }
92
+ });
93
+ action
94
+ .command('log')
95
+ .description("List the app's audited invocations, newest first")
96
+ .argument('<appId>', 'App ID')
97
+ .option('--limit <n>', 'Entries to return (default 50, at most 200)')
98
+ .option('--before <rfc3339>', "Page: the previous page's last started_at")
99
+ .option('--before-id <invocationId>', "Page: the previous page's last invocation_id")
100
+ .option('--failed', 'Only failures: failed, timeout and limit_exceeded')
101
+ .option('--status <list>', 'Only these results, comma-separated (ok, failed, timeout, limit_exceeded)')
102
+ .option('--action <name>', 'Only this action')
103
+ .option('--actor <userId>', 'Only this caller (usr_…)')
104
+ .option('--invocation <invocationId>', 'Only this invocation (aci_…)')
105
+ .action(async (appId, opts) => {
106
+ try {
107
+ // By presence, not value: --status '' still counts as given.
108
+ if (opts.failed && opts.status !== undefined) {
109
+ throw new Error('Use --failed or --status, not both');
110
+ }
111
+ if (opts.status !== undefined && opts.status.trim() === '') {
112
+ throw new Error('--status needs at least one result');
113
+ }
114
+ const status = opts.failed
115
+ ? ['failed', 'timeout', 'limit_exceeded']
116
+ : opts.status?.split(',');
117
+ const { client, orgId } = resolveCredentials();
118
+ printJson(await client.getMiniAppActionLog(orgId, stripPrllScheme(appId), {
119
+ limit: parsePositiveInt(opts.limit),
120
+ before: opts.before,
121
+ before_id: opts.beforeId,
122
+ status,
123
+ action: opts.action,
124
+ actor_id: opts.actor,
125
+ invocation_id: opts.invocation,
126
+ }));
127
+ }
128
+ catch (err) {
129
+ printError(err);
130
+ }
131
+ });
132
+ }
133
+ function collect(value, previous) {
134
+ return [...previous, value];
135
+ }
136
+ function version(raw) {
137
+ if (raw === undefined)
138
+ return undefined;
139
+ const seq = parsePositiveInt(raw);
140
+ if (seq === undefined)
141
+ throw new Error('--v must be a positive version seq');
142
+ return seq;
143
+ }
144
+ /** The params object of a call: --params-file or --params as the base, then
145
+ * each --param converted to the type its property declares. A key the
146
+ * schema does not declare is refused here unless it allows extra keys. */
147
+ export async function buildParams(schema, opts) {
148
+ let base = {};
149
+ if (opts.paramsFile !== undefined) {
150
+ base = parseJson(await fs.readFile(resolve(opts.paramsFile), 'utf8'), '--params-file');
151
+ }
152
+ else if (opts.params !== undefined) {
153
+ base = parseJson(opts.params, '--params');
154
+ }
155
+ if (typeof base !== 'object' || base === null || Array.isArray(base)) {
156
+ throw new Error('params must be a JSON object');
157
+ }
158
+ const params = { ...base };
159
+ for (const entry of opts.param ?? []) {
160
+ const eq = entry.indexOf('=');
161
+ if (eq <= 0)
162
+ throw new Error(`--param ${JSON.stringify(entry)} must be key=value`);
163
+ const key = entry.slice(0, eq);
164
+ params[key] = convertParam(schema, key, entry.slice(eq + 1));
165
+ }
166
+ return params;
167
+ }
168
+ function convertParam(schema, key, raw) {
169
+ const property = schema?.properties?.[key];
170
+ if (!property) {
171
+ if (schema?.additionalProperties !== true) {
172
+ const declared = Object.keys(schema?.properties ?? {}).join(', ') || 'none';
173
+ throw new Error(`the action declares no param ${JSON.stringify(key)} (declared: ${declared})`);
174
+ }
175
+ return parseOr(raw, raw);
176
+ }
177
+ switch (property.type) {
178
+ case 'string':
179
+ return raw;
180
+ case 'integer': {
181
+ const n = Number(raw);
182
+ if (!/^-?\d+$/.test(raw))
183
+ throw new Error(`--param ${key} must be an integer`);
184
+ // Past 2^53 a JSON number no longer holds the value typed: an id
185
+ // would silently become a neighbouring one.
186
+ if (!Number.isSafeInteger(n)) {
187
+ throw new Error(`--param ${key} is too large to send exactly as an integer`);
188
+ }
189
+ return n;
190
+ }
191
+ case 'number': {
192
+ const n = Number(raw);
193
+ if (raw.trim() === '' || !Number.isFinite(n))
194
+ throw new Error(`--param ${key} must be a number`);
195
+ return n;
196
+ }
197
+ case 'boolean':
198
+ if (raw !== 'true' && raw !== 'false')
199
+ throw new Error(`--param ${key} must be true or false`);
200
+ return raw === 'true';
201
+ case 'object':
202
+ case 'array':
203
+ return parseJson(raw, `--param ${key}`);
204
+ default:
205
+ return parseOr(raw, raw);
206
+ }
207
+ }
208
+ function parseJson(text, what) {
209
+ try {
210
+ return JSON.parse(text);
211
+ }
212
+ catch {
213
+ throw new Error(`${what} is not valid JSON`);
214
+ }
215
+ }
216
+ function parseOr(text, fallback) {
217
+ try {
218
+ return JSON.parse(text);
219
+ }
220
+ catch {
221
+ return fallback;
222
+ }
223
+ }
224
+ // The most the versions listing returns in one page.
225
+ const VERSION_LOOKUP = 200;
226
+ /** The next step after a failed call, printed under the error line; maps an
227
+ * unexpected failure's stack to source in place when the local build is the
228
+ * module that ran. */
229
+ async function explainFailure(err, ctx) {
230
+ const details = err.extras?.details;
231
+ const invocation = typeof details?.invocation_id === 'string' ? details.invocation_id : undefined;
232
+ if (err.code === 'ACTION_TIMEOUT' && ctx.kind === 'read') {
233
+ return `${invocation ?? 'The call'} did not finish within its deadline. A read action cannot write, so nothing changed: it is safe to run it again.`;
234
+ }
235
+ if (err.code === 'ACTION_TIMEOUT') {
236
+ return `The outcome of ${invocation ?? 'the call'} is unknown: writes it started may have committed. See what it committed with \`parall app db log --app ${ctx.appId}${invocation ? ` --invocation ${invocation}` : ''}\` before running it again.`;
237
+ }
238
+ if (err.code !== 'ACTION_FAILED' || typeof details?.stack !== 'string')
239
+ return undefined;
240
+ // Mapping is a convenience: when the version cannot be looked up the stack
241
+ // is still printed, with the reason.
242
+ let lookupFailure;
243
+ let sha = ctx.localSha256;
244
+ if (sha === undefined) {
245
+ try {
246
+ const versions = await ctx.client.getMiniAppVersions(ctx.orgId, ctx.appId, VERSION_LOOKUP);
247
+ const version = versions.find((v) => v.seq === ctx.seq);
248
+ if (version)
249
+ sha = version.action_module_sha256;
250
+ else
251
+ lookupFailure = `version ${ctx.seq} is not among the app's newest ${VERSION_LOOKUP} versions`;
252
+ }
253
+ catch (lookupErr) {
254
+ lookupFailure = `version ${ctx.seq} could not be looked up (${lookupErr.message})`;
255
+ }
256
+ }
257
+ const result = lookupFailure
258
+ ? { stack: details.stack, mapped: false, note: lookupFailure }
259
+ : await mapActionStack(details.stack, resolve(ctx.dist), sha);
260
+ details.stack = result.stack;
261
+ details.stack_mapped = result.mapped;
262
+ const ran = ctx.localSha256 ? 'the local build that ran' : `version ${ctx.seq}`;
263
+ return result.mapped
264
+ ? `The stack above is mapped to source with ${ctx.dist}'s source map (${ran}).`
265
+ : `The stack above is as the isolate reported it (author.js is the module): ${result.note}.`;
266
+ }