@parall/cli 1.73.0 → 1.75.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.
@@ -0,0 +1,6 @@
1
+ import type { Command } from 'commander';
2
+ /** `parall app add <block…>` copies @parall blocks into a Mini App project
3
+ * (apps-blocks.ts). It writes local files only: the block's tables are
4
+ * created by the author with `parall app db exec --file`, as printed. */
5
+ export declare function registerAppAddCommand(app: Command): void;
6
+ //# sourceMappingURL=apps-add.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"apps-add.d.ts","sourceRoot":"","sources":["../../src/commands/apps-add.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAYzC;;yEAEyE;AACzE,wBAAgB,qBAAqB,CAAC,GAAG,EAAE,OAAO,QAkEjD"}
@@ -0,0 +1,93 @@
1
+ import { relative, resolve } from 'node:path';
2
+ import { printError, printJson } from '../lib/output.js';
3
+ import { applyBlock, blockNames, conflictMessage, findBlock, listBlocks, planBlock, } from './apps-blocks.js';
4
+ /** `parall app add <block…>` copies @parall blocks into a Mini App project
5
+ * (apps-blocks.ts). It writes local files only: the block's tables are
6
+ * created by the author with `parall app db exec --file`, as printed. */
7
+ export function registerAppAddCommand(app) {
8
+ app
9
+ .command('add')
10
+ .description('Add ready-made blocks (calendar, kanban, …) to an `app init --actions` project: pages, actions, SQL and manifest declarations')
11
+ .argument('[blocks...]', 'Blocks to add (see --list)')
12
+ .option('--dir <dir>', 'The app project (default: the current directory)', '.')
13
+ .option('--list', 'List the available blocks')
14
+ .option('--force', 'Overwrite files and action declarations that differ from the block')
15
+ .option('--dry-run', 'Show what would change without writing anything')
16
+ .action(async (names, opts) => {
17
+ try {
18
+ if (opts.list) {
19
+ printJson(listBlocks());
20
+ return;
21
+ }
22
+ if (names.length === 0) {
23
+ throw new Error(`Name a block to add: ${blockNames().join(', ')} (parall app add --list)`);
24
+ }
25
+ const blocks = names.map((name) => {
26
+ const block = findBlock(name.replace(/^@parall\//, ''));
27
+ if (!block) {
28
+ throw new Error(`Unknown block ${JSON.stringify(name)}; available: ${blockNames().join(', ')}`);
29
+ }
30
+ return block;
31
+ });
32
+ const dir = resolve(opts.dir);
33
+ // Refuse before writing anything if any block would clobber a file.
34
+ for (const block of blocks) {
35
+ const plan = await planBlock(dir, block, { force: opts.force });
36
+ if (plan.conflicts.length > 0 || plan.actions.conflicts.length > 0) {
37
+ throw new Error(conflictMessage(plan));
38
+ }
39
+ }
40
+ const plans = [];
41
+ for (const block of blocks) {
42
+ // Planned again after the previous block landed: blocks edit the
43
+ // same manifest, package.json and plug-in points.
44
+ const plan = await planBlock(dir, block, { force: opts.force });
45
+ if (!opts.dryRun)
46
+ await applyBlock(plan);
47
+ plans.push(plan);
48
+ }
49
+ printJson({
50
+ dir,
51
+ dry_run: Boolean(opts.dryRun),
52
+ blocks: plans.map((plan) => ({
53
+ name: plan.block,
54
+ files: Object.fromEntries(plan.files.map((file) => [file.path, file.state])),
55
+ actions_added: plan.actions.added,
56
+ dependencies_added: plan.dependencies.added,
57
+ dependencies_kept: plan.dependencies.kept,
58
+ edited: plan.edits.map((edit) => edit.path),
59
+ manual_steps: plan.manual,
60
+ sql: plan.sql,
61
+ })),
62
+ });
63
+ console.error(nextSteps(dir, plans, Boolean(opts.dryRun)));
64
+ }
65
+ catch (err) {
66
+ printError(err);
67
+ }
68
+ });
69
+ }
70
+ function nextSteps(dir, plans, dryRun) {
71
+ const lines = [];
72
+ const where = relative(process.cwd(), dir) || '.';
73
+ for (const plan of plans) {
74
+ const created = plan.files.filter((file) => file.state === 'create').length;
75
+ const overwritten = plan.files.filter((file) => file.state === 'overwrite').length;
76
+ const verb = dryRun ? 'Would add' : 'Added';
77
+ lines.push(`${verb} ${plan.block} to ${where}: ${created} new file(s)${overwritten ? `, ${overwritten} overwritten` : ''}, actions ${[...plan.actions.added, ...plan.actions.unchanged].join(', ')}.`);
78
+ for (const [name, version] of Object.entries(plan.dependencies.kept)) {
79
+ lines.push(` ${name}: kept the project's ${version} (the block is tested with another version)`);
80
+ }
81
+ for (const step of plan.manual)
82
+ lines.push(` By hand — ${step}`);
83
+ }
84
+ const added = plans.flatMap((plan) => Object.keys(plan.dependencies.added));
85
+ lines.push('', 'Next:');
86
+ const sqlFiles = plans.map((plan) => plan.sql);
87
+ lines.push(` 1. Create the tables (PostgreSQL; safe to rerun): ${sqlFiles
88
+ .map((file) => `parall app db exec --app <app_…> --file ${file}`)
89
+ .join(' && ')}`);
90
+ lines.push(` 2. ${added.length > 0 ? `Install the new packages (${added.join(', ')}) and build` : 'Build'}: pnpm install && pnpm build`);
91
+ lines.push(' 3. parall app check dist, then parall app publish dist --app <app_…> --source .');
92
+ return lines.join('\n');
93
+ }
@@ -0,0 +1,96 @@
1
+ /**
2
+ * The @parall blocks `parall app add` installs: ready-made pages wired end
3
+ * to end — page components, an actions file, schema SQL and manifest
4
+ * declarations. Each block is a shadcn registry item (registry-item.json
5
+ * format, files inlined) shipped inside the CLI, so installing one needs no
6
+ * network and matches the CLI's version. What shadcn has no field for — the
7
+ * manifest declarations, where the page and actions plug in, the SQL file —
8
+ * rides in meta.parall.
9
+ */
10
+ export interface RegistryFile {
11
+ path: string;
12
+ type: string;
13
+ target: string;
14
+ content: string;
15
+ }
16
+ export interface ParallBlockMeta {
17
+ /** The page entry: an import line and the expression added to the pages
18
+ * list in src/pages.tsx. */
19
+ page: {
20
+ import: string;
21
+ entry: string;
22
+ };
23
+ /** The actions entry: an import line and the spread added to
24
+ * defineActions in actions/index.ts. */
25
+ actions: {
26
+ import: string;
27
+ entry: string;
28
+ };
29
+ /** Merged into public/manifest.json actions.functions. */
30
+ functions: Record<string, unknown>;
31
+ /** The schema file to apply with `parall app db exec --file`. */
32
+ sql: string;
33
+ }
34
+ export interface RegistryItem {
35
+ $schema?: string;
36
+ name: string;
37
+ type: string;
38
+ title: string;
39
+ description: string;
40
+ author?: string;
41
+ /** npm packages, pinned as name@version. */
42
+ dependencies?: string[];
43
+ registryDependencies?: string[];
44
+ files: RegistryFile[];
45
+ docs?: string;
46
+ meta: {
47
+ parall: ParallBlockMeta;
48
+ };
49
+ }
50
+ export declare function findBlock(name: string): RegistryItem | undefined;
51
+ export declare function blockNames(): string[];
52
+ /** What `parall app add --list` prints. */
53
+ export declare function listBlocks(): {
54
+ name: string;
55
+ title: string;
56
+ description: string;
57
+ actions: string[];
58
+ dependencies: string[];
59
+ files: string[];
60
+ }[];
61
+ export interface BlockPlan {
62
+ block: string;
63
+ dir: string;
64
+ files: Array<{
65
+ path: string;
66
+ content: string;
67
+ state: 'create' | 'overwrite' | 'unchanged';
68
+ }>;
69
+ /** Files that exist with other content (refused without --force). */
70
+ conflicts: string[];
71
+ dependencies: {
72
+ added: Record<string, string>;
73
+ kept: Record<string, string>;
74
+ };
75
+ actions: {
76
+ added: string[];
77
+ unchanged: string[];
78
+ conflicts: string[];
79
+ };
80
+ /** Rewritten files: the manifest, package.json and the two plug-in points. */
81
+ edits: Array<{
82
+ path: string;
83
+ content: string;
84
+ }>;
85
+ /** Steps left to the author when a plug-in marker is missing. */
86
+ manual: string[];
87
+ sql: string;
88
+ }
89
+ /** Plans adding a block to the project in dir without writing anything. */
90
+ export declare function planBlock(dir: string, block: RegistryItem, options?: {
91
+ force?: boolean;
92
+ }): Promise<BlockPlan>;
93
+ /** Writes a plan; refuses one with conflicts. */
94
+ export declare function applyBlock(plan: BlockPlan): Promise<void>;
95
+ export declare function conflictMessage(plan: BlockPlan): string;
96
+ //# sourceMappingURL=apps-blocks.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"apps-blocks.d.ts","sourceRoot":"","sources":["../../src/commands/apps-blocks.ts"],"names":[],"mappings":"AAKA;;;;;;;;GAQG;AAEH,MAAM,WAAW,YAAY;IAC3B,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,eAAe;IAC9B;gCAC4B;IAC5B,IAAI,EAAE;QAAE,MAAM,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,CAAC;IACxC;4CACwC;IACxC,OAAO,EAAE;QAAE,MAAM,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,CAAC;IAC3C,0DAA0D;IAC1D,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACnC,iEAAiE;IACjE,GAAG,EAAE,MAAM,CAAC;CACb;AAED,MAAM,WAAW,YAAY;IAC3B,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;IACd,WAAW,EAAE,MAAM,CAAC;IACpB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,4CAA4C;IAC5C,YAAY,CAAC,EAAE,MAAM,EAAE,CAAC;IACxB,oBAAoB,CAAC,EAAE,MAAM,EAAE,CAAC;IAChC,KAAK,EAAE,YAAY,EAAE,CAAC;IACtB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,IAAI,EAAE;QAAE,MAAM,EAAE,eAAe,CAAA;KAAE,CAAC;CACnC;AAED,wBAAgB,SAAS,CAAC,IAAI,EAAE,MAAM,GAAG,YAAY,GAAG,SAAS,CAEhE;AAED,wBAAgB,UAAU,IAAI,MAAM,EAAE,CAErC;AAED,2CAA2C;AAC3C,wBAAgB,UAAU;;;;;;;IASzB;AAsBD,MAAM,WAAW,SAAS;IACxB,KAAK,EAAE,MAAM,CAAC;IACd,GAAG,EAAE,MAAM,CAAC;IACZ,KAAK,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,QAAQ,GAAG,WAAW,GAAG,WAAW,CAAA;KAAE,CAAC,CAAC;IAC7F,qEAAqE;IACrE,SAAS,EAAE,MAAM,EAAE,CAAC;IACpB,YAAY,EAAE;QAAE,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;QAAC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;KAAE,CAAC;IAC9E,OAAO,EAAE;QAAE,KAAK,EAAE,MAAM,EAAE,CAAC;QAAC,SAAS,EAAE,MAAM,EAAE,CAAC;QAAC,SAAS,EAAE,MAAM,EAAE,CAAA;KAAE,CAAC;IACvE,8EAA8E;IAC9E,KAAK,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IAChD,iEAAiE;IACjE,MAAM,EAAE,MAAM,EAAE,CAAC;IACjB,GAAG,EAAE,MAAM,CAAC;CACb;AAWD,2EAA2E;AAC3E,wBAAsB,SAAS,CAC7B,GAAG,EAAE,MAAM,EACX,KAAK,EAAE,YAAY,EACnB,OAAO,GAAE;IAAE,KAAK,CAAC,EAAE,OAAO,CAAA;CAAO,GAChC,OAAO,CAAC,SAAS,CAAC,CAmGpB;AAkCD,iDAAiD;AACjD,wBAAsB,UAAU,CAAC,IAAI,EAAE,SAAS,GAAG,OAAO,CAAC,IAAI,CAAC,CAW/D;AAED,wBAAgB,eAAe,CAAC,IAAI,EAAE,SAAS,GAAG,MAAM,CAWvD"}
@@ -0,0 +1,196 @@
1
+ import { promises as fs } from 'node:fs';
2
+ import { dirname, join, resolve, sep } from 'node:path';
3
+ import { sortKeys } from './apps-template.js';
4
+ import { TEMPLATE_BLOCKS } from './apps-templates.gen.js';
5
+ export function findBlock(name) {
6
+ return TEMPLATE_BLOCKS.find((block) => block.name === name);
7
+ }
8
+ export function blockNames() {
9
+ return TEMPLATE_BLOCKS.map((block) => block.name);
10
+ }
11
+ /** What `parall app add --list` prints. */
12
+ export function listBlocks() {
13
+ return TEMPLATE_BLOCKS.map((block) => ({
14
+ name: block.name,
15
+ title: block.title,
16
+ description: block.description,
17
+ actions: Object.keys(block.meta.parall.functions),
18
+ dependencies: block.dependencies ?? [],
19
+ files: block.files.map((file) => file.target),
20
+ }));
21
+ }
22
+ // What a project must have for a block to plug in: the --actions scaffold
23
+ // with its shell, hooks and UI primitives.
24
+ const REQUIRED = [
25
+ 'package.json',
26
+ 'public/manifest.json',
27
+ 'actions/index.ts',
28
+ 'actions/people.ts',
29
+ 'src/pages.tsx',
30
+ 'src/hooks/use-action.ts',
31
+ 'src/hooks/use-people.ts',
32
+ 'src/components/ui/button.tsx',
33
+ ];
34
+ const MARKERS = {
35
+ pageImports: '// parall:page-imports',
36
+ pages: '// parall:pages',
37
+ actionImports: '// parall:action-imports',
38
+ actions: '// parall:actions',
39
+ };
40
+ async function readIfExists(path) {
41
+ try {
42
+ return await fs.readFile(path, 'utf8');
43
+ }
44
+ catch (err) {
45
+ if (err.code === 'ENOENT')
46
+ return undefined;
47
+ throw err;
48
+ }
49
+ }
50
+ /** Plans adding a block to the project in dir without writing anything. */
51
+ export async function planBlock(dir, block, options = {}) {
52
+ const root = resolve(dir);
53
+ const missing = [];
54
+ for (const path of REQUIRED) {
55
+ if ((await readIfExists(join(root, path))) === undefined)
56
+ missing.push(path);
57
+ }
58
+ if (missing.length > 0) {
59
+ throw new Error(`${root} is not a Mini App project with actions (missing ${missing.join(', ')}). Blocks plug into the scaffold of \`parall app init <dir> --actions\`.`);
60
+ }
61
+ const meta = block.meta.parall;
62
+ const plan = {
63
+ block: block.name,
64
+ dir: root,
65
+ files: [],
66
+ conflicts: [],
67
+ dependencies: { added: {}, kept: {} },
68
+ actions: { added: [], unchanged: [], conflicts: [] },
69
+ edits: [],
70
+ manual: [],
71
+ sql: meta.sql,
72
+ };
73
+ for (const file of block.files) {
74
+ const target = join(root, file.target);
75
+ if (!target.startsWith(root + sep))
76
+ throw new Error(`block file escapes the project: ${file.target}`);
77
+ const current = await readIfExists(target);
78
+ if (current === undefined) {
79
+ plan.files.push({ path: file.target, content: file.content, state: 'create' });
80
+ }
81
+ else if (current === file.content) {
82
+ plan.files.push({ path: file.target, content: file.content, state: 'unchanged' });
83
+ }
84
+ else {
85
+ plan.files.push({ path: file.target, content: file.content, state: 'overwrite' });
86
+ if (!options.force)
87
+ plan.conflicts.push(file.target);
88
+ }
89
+ }
90
+ // public/manifest.json: declare the block's actions.
91
+ const manifestPath = 'public/manifest.json';
92
+ const manifest = JSON.parse((await readIfExists(join(root, manifestPath))) ?? '{}');
93
+ if (!manifest.actions || typeof manifest.actions !== 'object') {
94
+ throw new Error(`${manifestPath} declares no actions; blocks plug into the scaffold of \`parall app init <dir> --actions\``);
95
+ }
96
+ manifest.actions.functions ??= {};
97
+ for (const [name, declaration] of Object.entries(meta.functions)) {
98
+ const current = manifest.actions.functions[name];
99
+ if (current === undefined) {
100
+ plan.actions.added.push(name);
101
+ }
102
+ else if (JSON.stringify(current) === JSON.stringify(declaration)) {
103
+ plan.actions.unchanged.push(name);
104
+ continue;
105
+ }
106
+ else if (!options.force) {
107
+ plan.actions.conflicts.push(name);
108
+ continue;
109
+ }
110
+ else {
111
+ plan.actions.added.push(name);
112
+ }
113
+ manifest.actions.functions[name] = declaration;
114
+ }
115
+ if (plan.actions.added.length > 0) {
116
+ plan.edits.push({ path: manifestPath, content: `${JSON.stringify(manifest, null, 2)}\n` });
117
+ }
118
+ // package.json: add the block's packages at its pinned versions; a
119
+ // package the project already has keeps its version.
120
+ const pkg = JSON.parse((await readIfExists(join(root, 'package.json'))) ?? '{}');
121
+ pkg.dependencies ??= {};
122
+ for (const spec of block.dependencies ?? []) {
123
+ const at = spec.lastIndexOf('@');
124
+ const name = at > 0 ? spec.slice(0, at) : spec;
125
+ const version = at > 0 ? spec.slice(at + 1) : 'latest';
126
+ const have = pkg.dependencies[name] ?? pkg.devDependencies?.[name];
127
+ if (have === undefined) {
128
+ pkg.dependencies[name] = version;
129
+ plan.dependencies.added[name] = version;
130
+ }
131
+ else if (have !== version) {
132
+ plan.dependencies.kept[name] = have;
133
+ }
134
+ }
135
+ if (Object.keys(plan.dependencies.added).length > 0) {
136
+ pkg.dependencies = sortKeys(pkg.dependencies);
137
+ plan.edits.push({ path: 'package.json', content: `${JSON.stringify(pkg, null, 2)}\n` });
138
+ }
139
+ // The two plug-in points.
140
+ await plugIn(plan, root, 'actions/index.ts', meta.actions, MARKERS.actionImports, MARKERS.actions);
141
+ await plugIn(plan, root, 'src/pages.tsx', meta.page, MARKERS.pageImports, MARKERS.pages);
142
+ return plan;
143
+ }
144
+ /** Adds an import above importMarker and an entry above entryMarker, unless
145
+ * already there. Without the markers it leaves the file alone and records a
146
+ * manual step. */
147
+ async function plugIn(plan, root, path, spec, importMarker, entryMarker) {
148
+ const source = (await readIfExists(join(root, path))) ?? '';
149
+ const lines = source.split('\n');
150
+ const hasImport = lines.some((line) => line.trim() === spec.import);
151
+ const hasEntry = lines.some((line) => line.trim().replace(/,$/, '') === spec.entry);
152
+ if (hasImport && hasEntry)
153
+ return;
154
+ const importAt = lines.findIndex((line) => line.trim().startsWith(importMarker));
155
+ const entryAt = lines.findIndex((line) => line.trim().startsWith(entryMarker));
156
+ if (importAt === -1 || entryAt === -1) {
157
+ plan.manual.push(`${path}: add \`${spec.import}\` and \`${spec.entry},\``);
158
+ return;
159
+ }
160
+ const indent = lines[entryAt]?.match(/^\s*/)?.[0] ?? '';
161
+ // Insert the later marker first so the earlier index stays valid.
162
+ const inserts = [];
163
+ if (!hasImport)
164
+ inserts.push([importAt, spec.import]);
165
+ if (!hasEntry)
166
+ inserts.push([entryAt, `${indent}${spec.entry},`]);
167
+ inserts.sort(([a], [b]) => b - a);
168
+ for (const [at, line] of inserts)
169
+ lines.splice(at, 0, line);
170
+ plan.edits.push({ path, content: lines.join('\n') });
171
+ }
172
+ /** Writes a plan; refuses one with conflicts. */
173
+ export async function applyBlock(plan) {
174
+ if (plan.conflicts.length > 0 || plan.actions.conflicts.length > 0) {
175
+ throw new Error(conflictMessage(plan));
176
+ }
177
+ for (const file of plan.files) {
178
+ if (file.state === 'unchanged')
179
+ continue;
180
+ const target = join(plan.dir, file.path);
181
+ await fs.mkdir(dirname(target), { recursive: true });
182
+ await fs.writeFile(target, file.content);
183
+ }
184
+ for (const edit of plan.edits)
185
+ await fs.writeFile(join(plan.dir, edit.path), edit.content);
186
+ }
187
+ export function conflictMessage(plan) {
188
+ const parts = [];
189
+ if (plan.conflicts.length > 0) {
190
+ parts.push(`these files exist with other content: ${plan.conflicts.join(', ')}`);
191
+ }
192
+ if (plan.actions.conflicts.length > 0) {
193
+ parts.push(`public/manifest.json declares these actions differently: ${plan.actions.conflicts.join(', ')}`);
194
+ }
195
+ return `cannot add ${plan.block}: ${parts.join('; ')}. Nothing was written; rerun with --force to overwrite them.`;
196
+ }
@@ -1,2 +1,2 @@
1
- export declare const PAGE_SDK_SOURCE = "/**\n * @parall/miniapp-sdk \u2014 the page side of the Mini App bridge (design \u00A77.1):\n * host handshake, host\u2192page events, resize, and `action`, the page's only\n * data method: it calls one of the app's server-side actions through the\n * host, which adds the viewer's session and the version the page loaded\n * (Mini App Action design \u00A73.1). No db, files, clip or chat methods exist\n * on this surface. The transport is postMessage to window.parent; the host\n * validates our origin, we validate that messages come from our parent\n * and, after the first answer, pin the parent's origin.\n *\n * Protocol (request/response + events):\n * page \u2192 host {parall: 'v1', id, method: 'ready' | 'resize' | 'action' | 'report', params}\n * host \u2192 page {parall: 'v1', id, result} | {parall: 'v1', id, error: {code, message, details?}}\n * host \u2192 page {parall: 'v1', event: 'route.changed' | 'viewer.changed' | 'data.changed', data}\n */\n\nexport interface ViewerSummary {\n id: string;\n display_name: string;\n is_agent: boolean;\n /** The viewer's organization role (owner / admin / member) \u2014 the same\n * value an action sees as ctx.viewer.role. */\n role?: string;\n}\n\nexport interface AppSummary {\n id: string;\n name: string;\n version_seq: number;\n}\n\nexport interface ReadyResult {\n viewer: ViewerSummary;\n app: AppSummary;\n route: string;\n}\n\n/** A Database the app reads was written. It carries no data: read again. */\nexport interface DataChanged {\n database_id: string;\n data_seq: number;\n /** Sent once after the host's connection came back: writes in between\n * may have been missed, so read again whatever data_seq says. */\n catch_up?: boolean;\n}\n\nexport type HostEvent =\n | { event: 'route.changed'; data: { route: string } }\n | { event: 'viewer.changed'; data: { viewer: ViewerSummary } }\n | { event: 'data.changed'; data: DataChanged };\n\n/** A refusal or failure from the host, in the error-contract envelope. An\n * action's failure keeps the server's code and details (invocation_id,\n * error_kind, field, current_version_seq\u2026); APP_VERSION_CHANGED means the\n * app was updated and the host offers the viewer a reload. */\nexport interface BridgeError extends Error {\n code: string;\n details?: Record<string, unknown>;\n}\n\ninterface WireError {\n code: string;\n message: string;\n details?: Record<string, unknown>;\n}\n\ntype Pending = {\n resolve: (v: unknown) => void;\n reject: (e: Error) => void;\n timer: ReturnType<typeof setTimeout>;\n};\n\nconst PROTOCOL = 'v1';\n\n// How long the page waits for the host. An action waits longer than the\n// host's request timeout, which waits longer than the server takes to\n// answer at worst, so the page always gets the server's answer rather than\n// a timeout of its own (Mini App Action design \u00A73.1, \u00A715).\nconst HOST_TIMEOUT_MS = 10_000;\nconst ACTION_TIMEOUT_MS = 30_000;\n\n// Marks the errors the bridge itself rejects with: what the host or the\n// server answered, never the page's own bug.\nconst FROM_BRIDGE = Symbol.for('parall.bridge-error');\n\nfunction bridgeError(\n code: string,\n message: string,\n details?: Record<string, unknown>,\n): BridgeError {\n const err = Object.assign(new Error(message), { code, details }) as BridgeError;\n Object.defineProperty(err, FROM_BRIDGE, { value: true });\n return err;\n}\n\n/**\n * What a page reports when something goes wrong (Mini App design \u00A79): an\n * error thrown on the page, a promise rejected without a handler, and an\n * action call that failed unexpectedly, timed out or ran over its limits.\n * Never console.error, and never an ActionError \u2014 that is the author's own\n * message to the caller. The host adds the version the page loaded and\n * reports it in the viewer's name; the app's authors are told.\n */\ntype ErrorReport = {\n kind: 'exception' | 'rejection' | 'action';\n name?: string;\n message?: string;\n stack?: string;\n action?: string;\n code?: string;\n invocation_id?: string;\n};\n\n// Each kind of error once per page load, and only so many: a page stuck in\n// a loop must not flood its authors (the server keeps its own budgets).\nconst REPORTS_PER_LOAD = 10;\nconst REPORTED_ACTION_CODES = new Set(['ACTION_TIMEOUT', 'ACTION_LIMIT_EXCEEDED']);\n\nfunction clip(s: string | undefined, max: number): string | undefined {\n return s && s.length > max ? s.slice(0, max) : s;\n}\n\n// A stack line that names a place in the code (file:line[:col]).\nconst FRAME = /:\\d+(?::\\d+)?\\)?$/;\n\n/** What makes two reports the same error \u2014 the way the server groups them:\n * an action failure by its action and code; anything else by its kind, its\n * name and the places its stack names, or by its message when the stack\n * names none. One throw site with a changing message is one error. */\nfunction reportKey(r: ErrorReport): string {\n if (r.kind === 'action') return `action\\u0000${r.action}\\u0000${r.code}`;\n const frames = (r.stack ?? '')\n .split('\\n')\n .map((line) => line.trim())\n .filter((line) => line !== '' && FRAME.test(line));\n return frames.length > 0\n ? `${r.kind}\\u0000${r.name}\\u0000${frames.join('\\n')}`\n : `${r.kind}\\u0000${r.name}\\u0000message\\u0000${r.message}`;\n}\n\nfunction describe(value: unknown): string {\n if (typeof value === 'string') return value;\n try {\n return JSON.stringify(value) ?? String(value);\n } catch {\n return String(value);\n }\n}\n\nclass MiniAppBridge {\n private nextId = 1;\n private pending = new Map<number, Pending>();\n private listeners = new Set<(e: HostEvent) => void>();\n private hostOrigin: string | null = null;\n private started = false;\n private reported = new Set<string>();\n\n constructor() {\n if (typeof window === 'undefined' || typeof window.addEventListener !== 'function') return;\n window.addEventListener('error', (event: ErrorEvent) => {\n const err: unknown = event.error;\n if (err instanceof Error) {\n this.report({ kind: 'exception', name: err.name, message: err.message, stack: err.stack });\n } else {\n const where = event.filename\n ? ` at ${event.filename}:${event.lineno}:${event.colno}`\n : '';\n this.report({\n kind: 'exception',\n name: 'Error',\n message: String(event.message || 'Script error.'),\n stack: where,\n });\n }\n });\n window.addEventListener('unhandledrejection', (event: PromiseRejectionEvent) => {\n const reason: unknown = event.reason;\n // The bridge's own rejections are the host's or the server's answers:\n // a failed action is reported where it failed, by its own rules.\n if (reason !== null && typeof reason === 'object' && FROM_BRIDGE in reason) return;\n if (reason instanceof Error) {\n this.report({\n kind: 'rejection',\n name: reason.name,\n message: reason.message,\n stack: reason.stack,\n });\n } else {\n this.report({ kind: 'rejection', name: '', message: describe(reason) });\n }\n });\n }\n\n /** Sends one error report to the host; drops repeats, anything past the\n * page's share, and every failure of the report itself (an older host\n * answers NOT_GRANTED). */\n private report(r: ErrorReport): void {\n // Cut to what the host may send: the server takes at most 16 KiB.\n const params: ErrorReport = {\n ...r,\n name: clip(r.name, 100),\n message: clip(r.message, 500),\n stack: clip(r.stack, 3000),\n };\n const key = reportKey(params);\n if (this.reported.has(key) || this.reported.size >= REPORTS_PER_LOAD) return;\n this.reported.add(key);\n void this.call('report', params).catch(() => {});\n }\n\n private start(): void {\n if (this.started) return;\n this.started = true;\n window.addEventListener('message', (event: MessageEvent) => {\n // Only our embedding host: same source as window.parent, and once\n // the handshake pinned an origin, exactly that origin.\n if (event.source !== window.parent) return;\n if (this.hostOrigin !== null && event.origin !== this.hostOrigin) return;\n const msg = event.data as Record<string, unknown> | null;\n if (!msg || msg.parall !== PROTOCOL) return;\n if (typeof msg.id === 'number') {\n const pending = this.pending.get(msg.id);\n if (!pending) return;\n this.pending.delete(msg.id);\n clearTimeout(pending.timer);\n if (this.hostOrigin === null) this.hostOrigin = event.origin;\n if (msg.error) {\n const err = msg.error as WireError;\n pending.reject(bridgeError(err.code, err.message, err.details));\n } else {\n pending.resolve(msg.result);\n }\n return;\n }\n if (typeof msg.event === 'string') {\n for (const fn of this.listeners) fn(msg as unknown as HostEvent);\n }\n });\n }\n\n private call<T>(method: string, params?: unknown, timeoutMs = HOST_TIMEOUT_MS): Promise<T> {\n this.start();\n const id = this.nextId++;\n return new Promise<T>((resolve, reject) => {\n const timer = setTimeout(() => {\n if (this.pending.delete(id)) {\n reject(bridgeError('HOST_TIMEOUT', `${method} timed out waiting for the host`));\n }\n }, timeoutMs);\n this.pending.set(id, { resolve: resolve as (v: unknown) => void, reject, timer });\n window.parent.postMessage({ parall: PROTOCOL, id, method, params }, '*');\n });\n }\n\n /** Handshake with the host; resolves with the viewer, app and initial route. */\n ready(): Promise<ReadyResult> {\n return this.call<ReadyResult>('ready');\n }\n\n /** Ask the host to grow/shrink the iframe (fire-and-forget semantics). */\n resize(height: number): void {\n void this.call('resize', { height }).catch(() => {});\n }\n\n /**\n * Call one of the app's actions with the viewer's identity and resolve\n * with what the action returned. A failure rejects with a BridgeError\n * whose code is the server's (ACTION_FAILED, ACTION_TIMEOUT,\n * INVALID_ACTION_PARAMS, APP_VERSION_CHANGED\u2026); its message is the\n * action's ActionError message when it threw one. HOST_TIMEOUT and\n * HOST_UNAVAILABLE mean no answer came back: whether the action ran is\n * not known, so read again before retrying a write.\n */\n async action<T = unknown>(name: string, params?: Record<string, unknown>): Promise<T> {\n let answer: { invocation_id: string; result: T };\n try {\n answer = await this.call<{ invocation_id: string; result: T }>(\n 'action',\n { name, params: params ?? {} },\n ACTION_TIMEOUT_MS,\n );\n } catch (err) {\n // The app's authors hear of an action that failed unexpectedly, timed\n // out or ran over its limits \u2014 caught by the page or not. An\n // ActionError (error_kind \"action\") is the author's own answer.\n const e = err as BridgeError;\n const unexpected = e.code === 'ACTION_FAILED' && e.details?.error_kind === 'unexpected';\n if (unexpected || REPORTED_ACTION_CODES.has(e.code)) {\n const invocation = e.details?.invocation_id;\n this.report({\n kind: 'action',\n action: name,\n code: e.code,\n invocation_id: typeof invocation === 'string' ? invocation : undefined,\n });\n }\n throw err;\n }\n return answer.result;\n }\n\n /** Subscribe to host events; returns the unsubscribe function. */\n onEvent(fn: (e: HostEvent) => void): () => void {\n this.start();\n this.listeners.add(fn);\n return () => this.listeners.delete(fn);\n }\n\n /**\n * Call fn when a Database the app reads has new writes: once per new\n * (database_id, data_seq) \u2014 repeats and older ones are dropped \u2014 and\n * always on a catch-up after the host reconnected. Read again in fn.\n */\n onDataChanged(fn: (change: DataChanged) => void): () => void {\n const seen = new Map<string, number>();\n return this.onEvent((e) => {\n if (e.event !== 'data.changed') return;\n const { database_id, data_seq, catch_up } = e.data;\n const last = seen.get(database_id);\n if (!catch_up && last !== undefined && data_seq <= last) return;\n if (last === undefined || data_seq > last) seen.set(database_id, data_seq);\n fn(e.data);\n });\n }\n}\n\nexport const parall = new MiniAppBridge();\n";
1
+ export declare const PAGE_SDK_SOURCE = "/**\n * @parall/miniapp-sdk \u2014 the page side of the Mini App bridge (design \u00A77.1):\n * host handshake, host\u2192page events, resize, and `action`, the page's only\n * data method: it calls one of the app's server-side actions through the\n * host, which adds the viewer's session and the version the page loaded\n * (Mini App Action design \u00A73.1). No db, files, clip or chat methods exist\n * on this surface. The transport is postMessage to window.parent; the host\n * validates our origin, we validate that messages come from our parent\n * and, after the first answer, pin the parent's origin.\n *\n * Protocol (request/response + events):\n * page \u2192 host {parall: 'v1', id, method: 'ready' | 'resize' | 'action' | 'report', params}\n * host \u2192 page {parall: 'v1', id, result} | {parall: 'v1', id, error: {code, message, details?}}\n * host \u2192 page {parall: 'v1', event: 'route.changed' | 'viewer.changed' | 'data.changed', data}\n */\n\nexport interface ViewerSummary {\n id: string;\n display_name: string;\n is_agent: boolean;\n /** The viewer's organization role (owner / admin / member) \u2014 the same\n * value an action sees as ctx.viewer.role. */\n role?: string;\n}\n\nexport interface AppSummary {\n id: string;\n name: string;\n version_seq: number;\n}\n\nexport interface ReadyResult {\n viewer: ViewerSummary;\n app: AppSummary;\n route: string;\n}\n\n/** A Database the app reads was written. It carries no data: read again. */\nexport interface DataChanged {\n database_id: string;\n data_seq: number;\n /** Sent once after the host's connection came back: writes in between\n * may have been missed, so read again whatever data_seq says. */\n catch_up?: boolean;\n}\n\nexport type HostEvent =\n | { event: 'route.changed'; data: { route: string } }\n | { event: 'viewer.changed'; data: { viewer: ViewerSummary } }\n | { event: 'data.changed'; data: DataChanged };\n\n/** A refusal or failure from the host, in the error-contract envelope. An\n * action's failure keeps the server's code and details (invocation_id,\n * error_kind, field, current_version_seq\u2026); APP_VERSION_CHANGED means the\n * app was updated and the host offers the viewer a reload. */\nexport interface BridgeError extends Error {\n code: string;\n details?: Record<string, unknown>;\n}\n\ninterface WireError {\n code: string;\n message: string;\n details?: Record<string, unknown>;\n}\n\ntype Pending = {\n resolve: (v: unknown) => void;\n reject: (e: Error) => void;\n timer: ReturnType<typeof setTimeout>;\n};\n\nconst PROTOCOL = 'v1';\n\n// How long the page waits for the host. An action waits longer than the\n// host's request timeout, which waits longer than the server takes to\n// answer at worst \u2014 an action that calls Clip may run 100 s \u2014 so the page\n// always gets the server's answer rather than a timeout of its own (Mini\n// App Action design \u00A73.1, \u00A715; Clip design \u00A74.2).\nconst HOST_TIMEOUT_MS = 10_000;\nconst ACTION_TIMEOUT_MS = 120_000;\n\n// Marks the errors the bridge itself rejects with: what the host or the\n// server answered, never the page's own bug.\nconst FROM_BRIDGE = Symbol.for('parall.bridge-error');\n\nfunction bridgeError(\n code: string,\n message: string,\n details?: Record<string, unknown>,\n): BridgeError {\n const err = Object.assign(new Error(message), { code, details }) as BridgeError;\n Object.defineProperty(err, FROM_BRIDGE, { value: true });\n return err;\n}\n\n/**\n * What a page reports when something goes wrong (Mini App design \u00A79): an\n * error thrown on the page, a promise rejected without a handler, and an\n * action call that failed unexpectedly, timed out or ran over its limits.\n * Never console.error, and never an ActionError \u2014 that is the author's own\n * message to the caller. The host adds the version the page loaded and\n * reports it in the viewer's name; the app's authors are told.\n */\ntype ErrorReport = {\n kind: 'exception' | 'rejection' | 'action';\n name?: string;\n message?: string;\n stack?: string;\n action?: string;\n code?: string;\n invocation_id?: string;\n};\n\n// Each kind of error once per page load, and only so many: a page stuck in\n// a loop must not flood its authors (the server keeps its own budgets).\nconst REPORTS_PER_LOAD = 10;\nconst REPORTED_ACTION_CODES = new Set(['ACTION_TIMEOUT', 'ACTION_LIMIT_EXCEEDED']);\n\nfunction clip(s: string | undefined, max: number): string | undefined {\n return s && s.length > max ? s.slice(0, max) : s;\n}\n\n// A stack line that names a place in the code (file:line[:col]).\nconst FRAME = /:\\d+(?::\\d+)?\\)?$/;\n\n/** What makes two reports the same error \u2014 the way the server groups them:\n * an action failure by its action and code; anything else by its kind, its\n * name and the places its stack names, or by its message when the stack\n * names none. One throw site with a changing message is one error. */\nfunction reportKey(r: ErrorReport): string {\n if (r.kind === 'action') return `action\\u0000${r.action}\\u0000${r.code}`;\n const frames = (r.stack ?? '')\n .split('\\n')\n .map((line) => line.trim())\n .filter((line) => line !== '' && FRAME.test(line));\n return frames.length > 0\n ? `${r.kind}\\u0000${r.name}\\u0000${frames.join('\\n')}`\n : `${r.kind}\\u0000${r.name}\\u0000message\\u0000${r.message}`;\n}\n\nfunction describe(value: unknown): string {\n if (typeof value === 'string') return value;\n try {\n return JSON.stringify(value) ?? String(value);\n } catch {\n return String(value);\n }\n}\n\nclass MiniAppBridge {\n private nextId = 1;\n private pending = new Map<number, Pending>();\n private listeners = new Set<(e: HostEvent) => void>();\n private hostOrigin: string | null = null;\n private started = false;\n private reported = new Set<string>();\n\n constructor() {\n if (typeof window === 'undefined' || typeof window.addEventListener !== 'function') return;\n window.addEventListener('error', (event: ErrorEvent) => {\n const err: unknown = event.error;\n if (err instanceof Error) {\n this.report({ kind: 'exception', name: err.name, message: err.message, stack: err.stack });\n } else {\n const where = event.filename\n ? ` at ${event.filename}:${event.lineno}:${event.colno}`\n : '';\n this.report({\n kind: 'exception',\n name: 'Error',\n message: String(event.message || 'Script error.'),\n stack: where,\n });\n }\n });\n window.addEventListener('unhandledrejection', (event: PromiseRejectionEvent) => {\n const reason: unknown = event.reason;\n // The bridge's own rejections are the host's or the server's answers:\n // a failed action is reported where it failed, by its own rules.\n if (reason !== null && typeof reason === 'object' && FROM_BRIDGE in reason) return;\n if (reason instanceof Error) {\n this.report({\n kind: 'rejection',\n name: reason.name,\n message: reason.message,\n stack: reason.stack,\n });\n } else {\n this.report({ kind: 'rejection', name: '', message: describe(reason) });\n }\n });\n }\n\n /** Sends one error report to the host; drops repeats, anything past the\n * page's share, and every failure of the report itself (an older host\n * answers NOT_GRANTED). */\n private report(r: ErrorReport): void {\n // Cut to what the host may send: the server takes at most 16 KiB.\n const params: ErrorReport = {\n ...r,\n name: clip(r.name, 100),\n message: clip(r.message, 500),\n stack: clip(r.stack, 3000),\n };\n const key = reportKey(params);\n if (this.reported.has(key) || this.reported.size >= REPORTS_PER_LOAD) return;\n this.reported.add(key);\n void this.call('report', params).catch(() => {});\n }\n\n private start(): void {\n if (this.started) return;\n this.started = true;\n window.addEventListener('message', (event: MessageEvent) => {\n // Only our embedding host: same source as window.parent, and once\n // the handshake pinned an origin, exactly that origin.\n if (event.source !== window.parent) return;\n if (this.hostOrigin !== null && event.origin !== this.hostOrigin) return;\n const msg = event.data as Record<string, unknown> | null;\n if (!msg || msg.parall !== PROTOCOL) return;\n if (typeof msg.id === 'number') {\n const pending = this.pending.get(msg.id);\n if (!pending) return;\n this.pending.delete(msg.id);\n clearTimeout(pending.timer);\n if (this.hostOrigin === null) this.hostOrigin = event.origin;\n if (msg.error) {\n const err = msg.error as WireError;\n pending.reject(bridgeError(err.code, err.message, err.details));\n } else {\n pending.resolve(msg.result);\n }\n return;\n }\n if (typeof msg.event === 'string') {\n for (const fn of this.listeners) fn(msg as unknown as HostEvent);\n }\n });\n }\n\n private call<T>(method: string, params?: unknown, timeoutMs = HOST_TIMEOUT_MS): Promise<T> {\n this.start();\n const id = this.nextId++;\n return new Promise<T>((resolve, reject) => {\n const timer = setTimeout(() => {\n if (this.pending.delete(id)) {\n reject(bridgeError('HOST_TIMEOUT', `${method} timed out waiting for the host`));\n }\n }, timeoutMs);\n this.pending.set(id, { resolve: resolve as (v: unknown) => void, reject, timer });\n window.parent.postMessage({ parall: PROTOCOL, id, method, params }, '*');\n });\n }\n\n /** Handshake with the host; resolves with the viewer, app and initial route. */\n ready(): Promise<ReadyResult> {\n return this.call<ReadyResult>('ready');\n }\n\n /** Ask the host to grow/shrink the iframe (fire-and-forget semantics). */\n resize(height: number): void {\n void this.call('resize', { height }).catch(() => {});\n }\n\n /**\n * Call one of the app's actions with the viewer's identity and resolve\n * with what the action returned. A failure rejects with a BridgeError\n * whose code is the server's (ACTION_FAILED, ACTION_TIMEOUT,\n * INVALID_ACTION_PARAMS, APP_VERSION_CHANGED\u2026); its message is the\n * action's ActionError message when it threw one. HOST_TIMEOUT and\n * HOST_UNAVAILABLE mean no answer came back: whether the action ran is\n * not known, so read again before retrying a write.\n */\n async action<T = unknown>(name: string, params?: Record<string, unknown>): Promise<T> {\n let answer: { invocation_id: string; result: T };\n try {\n answer = await this.call<{ invocation_id: string; result: T }>(\n 'action',\n { name, params: params ?? {} },\n ACTION_TIMEOUT_MS,\n );\n } catch (err) {\n // The app's authors hear of an action that failed unexpectedly, timed\n // out or ran over its limits \u2014 caught by the page or not. An\n // ActionError (error_kind \"action\") is the author's own answer.\n const e = err as BridgeError;\n const unexpected = e.code === 'ACTION_FAILED' && e.details?.error_kind === 'unexpected';\n if (unexpected || REPORTED_ACTION_CODES.has(e.code)) {\n const invocation = e.details?.invocation_id;\n this.report({\n kind: 'action',\n action: name,\n code: e.code,\n invocation_id: typeof invocation === 'string' ? invocation : undefined,\n });\n }\n throw err;\n }\n return answer.result;\n }\n\n /** Subscribe to host events; returns the unsubscribe function. */\n onEvent(fn: (e: HostEvent) => void): () => void {\n this.start();\n this.listeners.add(fn);\n return () => this.listeners.delete(fn);\n }\n\n /**\n * Call fn when a Database the app reads has new writes: once per new\n * (database_id, data_seq) \u2014 repeats and older ones are dropped \u2014 and\n * always on a catch-up after the host reconnected. Read again in fn.\n */\n onDataChanged(fn: (change: DataChanged) => void): () => void {\n const seen = new Map<string, number>();\n return this.onEvent((e) => {\n if (e.event !== 'data.changed') return;\n const { database_id, data_seq, catch_up } = e.data;\n const last = seen.get(database_id);\n if (!catch_up && last !== undefined && data_seq <= last) return;\n if (last === undefined || data_seq > last) seen.set(database_id, data_seq);\n fn(e.data);\n });\n }\n}\n\nexport const parall = new MiniAppBridge();\n";
2
2
  //# sourceMappingURL=apps-page-sdk.generated.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"apps-page-sdk.generated.d.ts","sourceRoot":"","sources":["../../src/commands/apps-page-sdk.generated.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,eAAe,4zYAAkuY,CAAC"}
1
+ {"version":3,"file":"apps-page-sdk.generated.d.ts","sourceRoot":"","sources":["../../src/commands/apps-page-sdk.generated.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,eAAe,64YAAoyY,CAAC"}
@@ -1,3 +1,3 @@
1
1
  // Generated from ts/miniapp-sdk/src/index.ts by scripts/generate-miniapp-sdk.mjs. Do not edit.
2
2
  // biome-ignore format: generated copy
3
- export const PAGE_SDK_SOURCE = "/**\n * @parall/miniapp-sdk — the page side of the Mini App bridge (design §7.1):\n * host handshake, host→page events, resize, and `action`, the page's only\n * data method: it calls one of the app's server-side actions through the\n * host, which adds the viewer's session and the version the page loaded\n * (Mini App Action design §3.1). No db, files, clip or chat methods exist\n * on this surface. The transport is postMessage to window.parent; the host\n * validates our origin, we validate that messages come from our parent\n * and, after the first answer, pin the parent's origin.\n *\n * Protocol (request/response + events):\n * page → host {parall: 'v1', id, method: 'ready' | 'resize' | 'action' | 'report', params}\n * host → page {parall: 'v1', id, result} | {parall: 'v1', id, error: {code, message, details?}}\n * host → page {parall: 'v1', event: 'route.changed' | 'viewer.changed' | 'data.changed', data}\n */\n\nexport interface ViewerSummary {\n id: string;\n display_name: string;\n is_agent: boolean;\n /** The viewer's organization role (owner / admin / member) — the same\n * value an action sees as ctx.viewer.role. */\n role?: string;\n}\n\nexport interface AppSummary {\n id: string;\n name: string;\n version_seq: number;\n}\n\nexport interface ReadyResult {\n viewer: ViewerSummary;\n app: AppSummary;\n route: string;\n}\n\n/** A Database the app reads was written. It carries no data: read again. */\nexport interface DataChanged {\n database_id: string;\n data_seq: number;\n /** Sent once after the host's connection came back: writes in between\n * may have been missed, so read again whatever data_seq says. */\n catch_up?: boolean;\n}\n\nexport type HostEvent =\n | { event: 'route.changed'; data: { route: string } }\n | { event: 'viewer.changed'; data: { viewer: ViewerSummary } }\n | { event: 'data.changed'; data: DataChanged };\n\n/** A refusal or failure from the host, in the error-contract envelope. An\n * action's failure keeps the server's code and details (invocation_id,\n * error_kind, field, current_version_seq…); APP_VERSION_CHANGED means the\n * app was updated and the host offers the viewer a reload. */\nexport interface BridgeError extends Error {\n code: string;\n details?: Record<string, unknown>;\n}\n\ninterface WireError {\n code: string;\n message: string;\n details?: Record<string, unknown>;\n}\n\ntype Pending = {\n resolve: (v: unknown) => void;\n reject: (e: Error) => void;\n timer: ReturnType<typeof setTimeout>;\n};\n\nconst PROTOCOL = 'v1';\n\n// How long the page waits for the host. An action waits longer than the\n// host's request timeout, which waits longer than the server takes to\n// answer at worst, so the page always gets the server's answer rather than\n// a timeout of its own (Mini App Action design §3.1, §15).\nconst HOST_TIMEOUT_MS = 10_000;\nconst ACTION_TIMEOUT_MS = 30_000;\n\n// Marks the errors the bridge itself rejects with: what the host or the\n// server answered, never the page's own bug.\nconst FROM_BRIDGE = Symbol.for('parall.bridge-error');\n\nfunction bridgeError(\n code: string,\n message: string,\n details?: Record<string, unknown>,\n): BridgeError {\n const err = Object.assign(new Error(message), { code, details }) as BridgeError;\n Object.defineProperty(err, FROM_BRIDGE, { value: true });\n return err;\n}\n\n/**\n * What a page reports when something goes wrong (Mini App design §9): an\n * error thrown on the page, a promise rejected without a handler, and an\n * action call that failed unexpectedly, timed out or ran over its limits.\n * Never console.error, and never an ActionError — that is the author's own\n * message to the caller. The host adds the version the page loaded and\n * reports it in the viewer's name; the app's authors are told.\n */\ntype ErrorReport = {\n kind: 'exception' | 'rejection' | 'action';\n name?: string;\n message?: string;\n stack?: string;\n action?: string;\n code?: string;\n invocation_id?: string;\n};\n\n// Each kind of error once per page load, and only so many: a page stuck in\n// a loop must not flood its authors (the server keeps its own budgets).\nconst REPORTS_PER_LOAD = 10;\nconst REPORTED_ACTION_CODES = new Set(['ACTION_TIMEOUT', 'ACTION_LIMIT_EXCEEDED']);\n\nfunction clip(s: string | undefined, max: number): string | undefined {\n return s && s.length > max ? s.slice(0, max) : s;\n}\n\n// A stack line that names a place in the code (file:line[:col]).\nconst FRAME = /:\\d+(?::\\d+)?\\)?$/;\n\n/** What makes two reports the same error — the way the server groups them:\n * an action failure by its action and code; anything else by its kind, its\n * name and the places its stack names, or by its message when the stack\n * names none. One throw site with a changing message is one error. */\nfunction reportKey(r: ErrorReport): string {\n if (r.kind === 'action') return `action\\u0000${r.action}\\u0000${r.code}`;\n const frames = (r.stack ?? '')\n .split('\\n')\n .map((line) => line.trim())\n .filter((line) => line !== '' && FRAME.test(line));\n return frames.length > 0\n ? `${r.kind}\\u0000${r.name}\\u0000${frames.join('\\n')}`\n : `${r.kind}\\u0000${r.name}\\u0000message\\u0000${r.message}`;\n}\n\nfunction describe(value: unknown): string {\n if (typeof value === 'string') return value;\n try {\n return JSON.stringify(value) ?? String(value);\n } catch {\n return String(value);\n }\n}\n\nclass MiniAppBridge {\n private nextId = 1;\n private pending = new Map<number, Pending>();\n private listeners = new Set<(e: HostEvent) => void>();\n private hostOrigin: string | null = null;\n private started = false;\n private reported = new Set<string>();\n\n constructor() {\n if (typeof window === 'undefined' || typeof window.addEventListener !== 'function') return;\n window.addEventListener('error', (event: ErrorEvent) => {\n const err: unknown = event.error;\n if (err instanceof Error) {\n this.report({ kind: 'exception', name: err.name, message: err.message, stack: err.stack });\n } else {\n const where = event.filename\n ? ` at ${event.filename}:${event.lineno}:${event.colno}`\n : '';\n this.report({\n kind: 'exception',\n name: 'Error',\n message: String(event.message || 'Script error.'),\n stack: where,\n });\n }\n });\n window.addEventListener('unhandledrejection', (event: PromiseRejectionEvent) => {\n const reason: unknown = event.reason;\n // The bridge's own rejections are the host's or the server's answers:\n // a failed action is reported where it failed, by its own rules.\n if (reason !== null && typeof reason === 'object' && FROM_BRIDGE in reason) return;\n if (reason instanceof Error) {\n this.report({\n kind: 'rejection',\n name: reason.name,\n message: reason.message,\n stack: reason.stack,\n });\n } else {\n this.report({ kind: 'rejection', name: '', message: describe(reason) });\n }\n });\n }\n\n /** Sends one error report to the host; drops repeats, anything past the\n * page's share, and every failure of the report itself (an older host\n * answers NOT_GRANTED). */\n private report(r: ErrorReport): void {\n // Cut to what the host may send: the server takes at most 16 KiB.\n const params: ErrorReport = {\n ...r,\n name: clip(r.name, 100),\n message: clip(r.message, 500),\n stack: clip(r.stack, 3000),\n };\n const key = reportKey(params);\n if (this.reported.has(key) || this.reported.size >= REPORTS_PER_LOAD) return;\n this.reported.add(key);\n void this.call('report', params).catch(() => {});\n }\n\n private start(): void {\n if (this.started) return;\n this.started = true;\n window.addEventListener('message', (event: MessageEvent) => {\n // Only our embedding host: same source as window.parent, and once\n // the handshake pinned an origin, exactly that origin.\n if (event.source !== window.parent) return;\n if (this.hostOrigin !== null && event.origin !== this.hostOrigin) return;\n const msg = event.data as Record<string, unknown> | null;\n if (!msg || msg.parall !== PROTOCOL) return;\n if (typeof msg.id === 'number') {\n const pending = this.pending.get(msg.id);\n if (!pending) return;\n this.pending.delete(msg.id);\n clearTimeout(pending.timer);\n if (this.hostOrigin === null) this.hostOrigin = event.origin;\n if (msg.error) {\n const err = msg.error as WireError;\n pending.reject(bridgeError(err.code, err.message, err.details));\n } else {\n pending.resolve(msg.result);\n }\n return;\n }\n if (typeof msg.event === 'string') {\n for (const fn of this.listeners) fn(msg as unknown as HostEvent);\n }\n });\n }\n\n private call<T>(method: string, params?: unknown, timeoutMs = HOST_TIMEOUT_MS): Promise<T> {\n this.start();\n const id = this.nextId++;\n return new Promise<T>((resolve, reject) => {\n const timer = setTimeout(() => {\n if (this.pending.delete(id)) {\n reject(bridgeError('HOST_TIMEOUT', `${method} timed out waiting for the host`));\n }\n }, timeoutMs);\n this.pending.set(id, { resolve: resolve as (v: unknown) => void, reject, timer });\n window.parent.postMessage({ parall: PROTOCOL, id, method, params }, '*');\n });\n }\n\n /** Handshake with the host; resolves with the viewer, app and initial route. */\n ready(): Promise<ReadyResult> {\n return this.call<ReadyResult>('ready');\n }\n\n /** Ask the host to grow/shrink the iframe (fire-and-forget semantics). */\n resize(height: number): void {\n void this.call('resize', { height }).catch(() => {});\n }\n\n /**\n * Call one of the app's actions with the viewer's identity and resolve\n * with what the action returned. A failure rejects with a BridgeError\n * whose code is the server's (ACTION_FAILED, ACTION_TIMEOUT,\n * INVALID_ACTION_PARAMS, APP_VERSION_CHANGED…); its message is the\n * action's ActionError message when it threw one. HOST_TIMEOUT and\n * HOST_UNAVAILABLE mean no answer came back: whether the action ran is\n * not known, so read again before retrying a write.\n */\n async action<T = unknown>(name: string, params?: Record<string, unknown>): Promise<T> {\n let answer: { invocation_id: string; result: T };\n try {\n answer = await this.call<{ invocation_id: string; result: T }>(\n 'action',\n { name, params: params ?? {} },\n ACTION_TIMEOUT_MS,\n );\n } catch (err) {\n // The app's authors hear of an action that failed unexpectedly, timed\n // out or ran over its limits — caught by the page or not. An\n // ActionError (error_kind \"action\") is the author's own answer.\n const e = err as BridgeError;\n const unexpected = e.code === 'ACTION_FAILED' && e.details?.error_kind === 'unexpected';\n if (unexpected || REPORTED_ACTION_CODES.has(e.code)) {\n const invocation = e.details?.invocation_id;\n this.report({\n kind: 'action',\n action: name,\n code: e.code,\n invocation_id: typeof invocation === 'string' ? invocation : undefined,\n });\n }\n throw err;\n }\n return answer.result;\n }\n\n /** Subscribe to host events; returns the unsubscribe function. */\n onEvent(fn: (e: HostEvent) => void): () => void {\n this.start();\n this.listeners.add(fn);\n return () => this.listeners.delete(fn);\n }\n\n /**\n * Call fn when a Database the app reads has new writes: once per new\n * (database_id, data_seq) — repeats and older ones are dropped — and\n * always on a catch-up after the host reconnected. Read again in fn.\n */\n onDataChanged(fn: (change: DataChanged) => void): () => void {\n const seen = new Map<string, number>();\n return this.onEvent((e) => {\n if (e.event !== 'data.changed') return;\n const { database_id, data_seq, catch_up } = e.data;\n const last = seen.get(database_id);\n if (!catch_up && last !== undefined && data_seq <= last) return;\n if (last === undefined || data_seq > last) seen.set(database_id, data_seq);\n fn(e.data);\n });\n }\n}\n\nexport const parall = new MiniAppBridge();\n";
3
+ export const PAGE_SDK_SOURCE = "/**\n * @parall/miniapp-sdk — the page side of the Mini App bridge (design §7.1):\n * host handshake, host→page events, resize, and `action`, the page's only\n * data method: it calls one of the app's server-side actions through the\n * host, which adds the viewer's session and the version the page loaded\n * (Mini App Action design §3.1). No db, files, clip or chat methods exist\n * on this surface. The transport is postMessage to window.parent; the host\n * validates our origin, we validate that messages come from our parent\n * and, after the first answer, pin the parent's origin.\n *\n * Protocol (request/response + events):\n * page → host {parall: 'v1', id, method: 'ready' | 'resize' | 'action' | 'report', params}\n * host → page {parall: 'v1', id, result} | {parall: 'v1', id, error: {code, message, details?}}\n * host → page {parall: 'v1', event: 'route.changed' | 'viewer.changed' | 'data.changed', data}\n */\n\nexport interface ViewerSummary {\n id: string;\n display_name: string;\n is_agent: boolean;\n /** The viewer's organization role (owner / admin / member) — the same\n * value an action sees as ctx.viewer.role. */\n role?: string;\n}\n\nexport interface AppSummary {\n id: string;\n name: string;\n version_seq: number;\n}\n\nexport interface ReadyResult {\n viewer: ViewerSummary;\n app: AppSummary;\n route: string;\n}\n\n/** A Database the app reads was written. It carries no data: read again. */\nexport interface DataChanged {\n database_id: string;\n data_seq: number;\n /** Sent once after the host's connection came back: writes in between\n * may have been missed, so read again whatever data_seq says. */\n catch_up?: boolean;\n}\n\nexport type HostEvent =\n | { event: 'route.changed'; data: { route: string } }\n | { event: 'viewer.changed'; data: { viewer: ViewerSummary } }\n | { event: 'data.changed'; data: DataChanged };\n\n/** A refusal or failure from the host, in the error-contract envelope. An\n * action's failure keeps the server's code and details (invocation_id,\n * error_kind, field, current_version_seq…); APP_VERSION_CHANGED means the\n * app was updated and the host offers the viewer a reload. */\nexport interface BridgeError extends Error {\n code: string;\n details?: Record<string, unknown>;\n}\n\ninterface WireError {\n code: string;\n message: string;\n details?: Record<string, unknown>;\n}\n\ntype Pending = {\n resolve: (v: unknown) => void;\n reject: (e: Error) => void;\n timer: ReturnType<typeof setTimeout>;\n};\n\nconst PROTOCOL = 'v1';\n\n// How long the page waits for the host. An action waits longer than the\n// host's request timeout, which waits longer than the server takes to\n// answer at worst — an action that calls Clip may run 100 s — so the page\n// always gets the server's answer rather than a timeout of its own (Mini\n// App Action design §3.1, §15; Clip design §4.2).\nconst HOST_TIMEOUT_MS = 10_000;\nconst ACTION_TIMEOUT_MS = 120_000;\n\n// Marks the errors the bridge itself rejects with: what the host or the\n// server answered, never the page's own bug.\nconst FROM_BRIDGE = Symbol.for('parall.bridge-error');\n\nfunction bridgeError(\n code: string,\n message: string,\n details?: Record<string, unknown>,\n): BridgeError {\n const err = Object.assign(new Error(message), { code, details }) as BridgeError;\n Object.defineProperty(err, FROM_BRIDGE, { value: true });\n return err;\n}\n\n/**\n * What a page reports when something goes wrong (Mini App design §9): an\n * error thrown on the page, a promise rejected without a handler, and an\n * action call that failed unexpectedly, timed out or ran over its limits.\n * Never console.error, and never an ActionError — that is the author's own\n * message to the caller. The host adds the version the page loaded and\n * reports it in the viewer's name; the app's authors are told.\n */\ntype ErrorReport = {\n kind: 'exception' | 'rejection' | 'action';\n name?: string;\n message?: string;\n stack?: string;\n action?: string;\n code?: string;\n invocation_id?: string;\n};\n\n// Each kind of error once per page load, and only so many: a page stuck in\n// a loop must not flood its authors (the server keeps its own budgets).\nconst REPORTS_PER_LOAD = 10;\nconst REPORTED_ACTION_CODES = new Set(['ACTION_TIMEOUT', 'ACTION_LIMIT_EXCEEDED']);\n\nfunction clip(s: string | undefined, max: number): string | undefined {\n return s && s.length > max ? s.slice(0, max) : s;\n}\n\n// A stack line that names a place in the code (file:line[:col]).\nconst FRAME = /:\\d+(?::\\d+)?\\)?$/;\n\n/** What makes two reports the same error — the way the server groups them:\n * an action failure by its action and code; anything else by its kind, its\n * name and the places its stack names, or by its message when the stack\n * names none. One throw site with a changing message is one error. */\nfunction reportKey(r: ErrorReport): string {\n if (r.kind === 'action') return `action\\u0000${r.action}\\u0000${r.code}`;\n const frames = (r.stack ?? '')\n .split('\\n')\n .map((line) => line.trim())\n .filter((line) => line !== '' && FRAME.test(line));\n return frames.length > 0\n ? `${r.kind}\\u0000${r.name}\\u0000${frames.join('\\n')}`\n : `${r.kind}\\u0000${r.name}\\u0000message\\u0000${r.message}`;\n}\n\nfunction describe(value: unknown): string {\n if (typeof value === 'string') return value;\n try {\n return JSON.stringify(value) ?? String(value);\n } catch {\n return String(value);\n }\n}\n\nclass MiniAppBridge {\n private nextId = 1;\n private pending = new Map<number, Pending>();\n private listeners = new Set<(e: HostEvent) => void>();\n private hostOrigin: string | null = null;\n private started = false;\n private reported = new Set<string>();\n\n constructor() {\n if (typeof window === 'undefined' || typeof window.addEventListener !== 'function') return;\n window.addEventListener('error', (event: ErrorEvent) => {\n const err: unknown = event.error;\n if (err instanceof Error) {\n this.report({ kind: 'exception', name: err.name, message: err.message, stack: err.stack });\n } else {\n const where = event.filename\n ? ` at ${event.filename}:${event.lineno}:${event.colno}`\n : '';\n this.report({\n kind: 'exception',\n name: 'Error',\n message: String(event.message || 'Script error.'),\n stack: where,\n });\n }\n });\n window.addEventListener('unhandledrejection', (event: PromiseRejectionEvent) => {\n const reason: unknown = event.reason;\n // The bridge's own rejections are the host's or the server's answers:\n // a failed action is reported where it failed, by its own rules.\n if (reason !== null && typeof reason === 'object' && FROM_BRIDGE in reason) return;\n if (reason instanceof Error) {\n this.report({\n kind: 'rejection',\n name: reason.name,\n message: reason.message,\n stack: reason.stack,\n });\n } else {\n this.report({ kind: 'rejection', name: '', message: describe(reason) });\n }\n });\n }\n\n /** Sends one error report to the host; drops repeats, anything past the\n * page's share, and every failure of the report itself (an older host\n * answers NOT_GRANTED). */\n private report(r: ErrorReport): void {\n // Cut to what the host may send: the server takes at most 16 KiB.\n const params: ErrorReport = {\n ...r,\n name: clip(r.name, 100),\n message: clip(r.message, 500),\n stack: clip(r.stack, 3000),\n };\n const key = reportKey(params);\n if (this.reported.has(key) || this.reported.size >= REPORTS_PER_LOAD) return;\n this.reported.add(key);\n void this.call('report', params).catch(() => {});\n }\n\n private start(): void {\n if (this.started) return;\n this.started = true;\n window.addEventListener('message', (event: MessageEvent) => {\n // Only our embedding host: same source as window.parent, and once\n // the handshake pinned an origin, exactly that origin.\n if (event.source !== window.parent) return;\n if (this.hostOrigin !== null && event.origin !== this.hostOrigin) return;\n const msg = event.data as Record<string, unknown> | null;\n if (!msg || msg.parall !== PROTOCOL) return;\n if (typeof msg.id === 'number') {\n const pending = this.pending.get(msg.id);\n if (!pending) return;\n this.pending.delete(msg.id);\n clearTimeout(pending.timer);\n if (this.hostOrigin === null) this.hostOrigin = event.origin;\n if (msg.error) {\n const err = msg.error as WireError;\n pending.reject(bridgeError(err.code, err.message, err.details));\n } else {\n pending.resolve(msg.result);\n }\n return;\n }\n if (typeof msg.event === 'string') {\n for (const fn of this.listeners) fn(msg as unknown as HostEvent);\n }\n });\n }\n\n private call<T>(method: string, params?: unknown, timeoutMs = HOST_TIMEOUT_MS): Promise<T> {\n this.start();\n const id = this.nextId++;\n return new Promise<T>((resolve, reject) => {\n const timer = setTimeout(() => {\n if (this.pending.delete(id)) {\n reject(bridgeError('HOST_TIMEOUT', `${method} timed out waiting for the host`));\n }\n }, timeoutMs);\n this.pending.set(id, { resolve: resolve as (v: unknown) => void, reject, timer });\n window.parent.postMessage({ parall: PROTOCOL, id, method, params }, '*');\n });\n }\n\n /** Handshake with the host; resolves with the viewer, app and initial route. */\n ready(): Promise<ReadyResult> {\n return this.call<ReadyResult>('ready');\n }\n\n /** Ask the host to grow/shrink the iframe (fire-and-forget semantics). */\n resize(height: number): void {\n void this.call('resize', { height }).catch(() => {});\n }\n\n /**\n * Call one of the app's actions with the viewer's identity and resolve\n * with what the action returned. A failure rejects with a BridgeError\n * whose code is the server's (ACTION_FAILED, ACTION_TIMEOUT,\n * INVALID_ACTION_PARAMS, APP_VERSION_CHANGED…); its message is the\n * action's ActionError message when it threw one. HOST_TIMEOUT and\n * HOST_UNAVAILABLE mean no answer came back: whether the action ran is\n * not known, so read again before retrying a write.\n */\n async action<T = unknown>(name: string, params?: Record<string, unknown>): Promise<T> {\n let answer: { invocation_id: string; result: T };\n try {\n answer = await this.call<{ invocation_id: string; result: T }>(\n 'action',\n { name, params: params ?? {} },\n ACTION_TIMEOUT_MS,\n );\n } catch (err) {\n // The app's authors hear of an action that failed unexpectedly, timed\n // out or ran over its limits — caught by the page or not. An\n // ActionError (error_kind \"action\") is the author's own answer.\n const e = err as BridgeError;\n const unexpected = e.code === 'ACTION_FAILED' && e.details?.error_kind === 'unexpected';\n if (unexpected || REPORTED_ACTION_CODES.has(e.code)) {\n const invocation = e.details?.invocation_id;\n this.report({\n kind: 'action',\n action: name,\n code: e.code,\n invocation_id: typeof invocation === 'string' ? invocation : undefined,\n });\n }\n throw err;\n }\n return answer.result;\n }\n\n /** Subscribe to host events; returns the unsubscribe function. */\n onEvent(fn: (e: HostEvent) => void): () => void {\n this.start();\n this.listeners.add(fn);\n return () => this.listeners.delete(fn);\n }\n\n /**\n * Call fn when a Database the app reads has new writes: once per new\n * (database_id, data_seq) — repeats and older ones are dropped — and\n * always on a catch-up after the host reconnected. Read again in fn.\n */\n onDataChanged(fn: (change: DataChanged) => void): () => void {\n const seen = new Map<string, number>();\n return this.onEvent((e) => {\n if (e.event !== 'data.changed') return;\n const { database_id, data_seq, catch_up } = e.data;\n const last = seen.get(database_id);\n if (!catch_up && last !== undefined && data_seq <= last) return;\n if (last === undefined || data_seq > last) seen.set(database_id, data_seq);\n fn(e.data);\n });\n }\n}\n\nexport const parall = new MiniAppBridge();\n";
@@ -1,11 +1,6 @@
1
- /** What `parall app init --actions` adds to the page scaffold
2
- * (docs/engineering-design/mini-app-action-design.md §10.1): the action
3
- * sources under actions/, the SDK wrapper vendored as
4
- * actions/parall-actions.ts (ts/miniapp-sdk/src/actions.ts, embedded at
5
- * build time), a second Vite build that writes dist/_actions/index.js —
6
- * one unminified ES module with a source map, whose only import is
7
- * cloudflare:workers — miniflare for `parall app action run --local`, and
8
- * a page that calls the example action. */
9
- export declare function withActions(files: Array<[string, string]>): Array<[string, string]>;
1
+ /** The miniflare range the `--actions` scaffold installs: workerd with the
2
+ * worker_loaders binding the local runner needs (apps-action-local.ts).
3
+ * ts/cli/templates/mini-app/with-actions/package.json pins the same range;
4
+ * test/apps-init.test.mjs keeps the two equal. */
10
5
  export declare const MINIFLARE_RANGE = "^4.20260415.0";
11
6
  //# sourceMappingURL=apps-scaffold-actions.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"apps-scaffold-actions.d.ts","sourceRoot":"","sources":["../../src/commands/apps-scaffold-actions.ts"],"names":[],"mappings":"AAEA;;;;;;;2CAO2C;AAC3C,wBAAgB,WAAW,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,GAAG,KAAK,CAAC,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CA4BnF;AAGD,eAAO,MAAM,eAAe,kBAAkB,CAAC"}
1
+ {"version":3,"file":"apps-scaffold-actions.d.ts","sourceRoot":"","sources":["../../src/commands/apps-scaffold-actions.ts"],"names":[],"mappings":"AAAA;;;kDAGkD;AAClD,eAAO,MAAM,eAAe,kBAAkB,CAAC"}