@parall/cli 1.78.0 → 1.79.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/dist/commands/apps-access.d.ts +8 -0
  2. package/dist/commands/apps-access.d.ts.map +1 -0
  3. package/dist/commands/apps-access.js +141 -0
  4. package/dist/commands/apps-actions.d.ts +5 -3
  5. package/dist/commands/apps-actions.d.ts.map +1 -1
  6. package/dist/commands/apps-actions.js +5 -3
  7. package/dist/commands/apps-dev-page.d.ts +2 -0
  8. package/dist/commands/apps-dev-page.d.ts.map +1 -1
  9. package/dist/commands/apps-dev-page.js +3 -3
  10. package/dist/commands/apps-dev-server.d.ts +10 -1
  11. package/dist/commands/apps-dev-server.d.ts.map +1 -1
  12. package/dist/commands/apps-dev-server.js +26 -3
  13. package/dist/commands/apps-dev.d.ts +12 -1
  14. package/dist/commands/apps-dev.d.ts.map +1 -1
  15. package/dist/commands/apps-dev.js +25 -10
  16. package/dist/commands/apps-page-sdk.generated.d.ts +1 -1
  17. package/dist/commands/apps-page-sdk.generated.d.ts.map +1 -1
  18. package/dist/commands/apps-page-sdk.generated.js +1 -1
  19. package/dist/commands/apps-templates.gen.js +18 -18
  20. package/dist/commands/apps.d.ts +3 -2
  21. package/dist/commands/apps.d.ts.map +1 -1
  22. package/dist/commands/apps.js +10 -3
  23. package/dist/commands/chat-connections.d.ts +11 -0
  24. package/dist/commands/chat-connections.d.ts.map +1 -0
  25. package/dist/commands/chat-connections.js +162 -0
  26. package/dist/commands/chats.d.ts.map +1 -1
  27. package/dist/commands/chats.js +6 -1
  28. package/dist/commands/search.d.ts.map +1 -1
  29. package/dist/commands/search.js +1 -1
  30. package/dist/lib/output.d.ts +11 -0
  31. package/dist/lib/output.d.ts.map +1 -1
  32. package/dist/lib/output.js +32 -5
  33. package/package.json +4 -4
@@ -0,0 +1,8 @@
1
+ import type { MiniAppAccessLevel } from '@parall/sdk';
2
+ import type { Command } from 'commander';
3
+ /** A member level as given on the command line. */
4
+ export declare function parseMemberLevel(raw: string | undefined, what: string): MiniAppAccessLevel;
5
+ /** A level on the access list: never below read. */
6
+ export declare function parseGrantLevel(raw: string | undefined): 'read' | 'write';
7
+ export declare function registerAppAccessCommands(app: Command): void;
8
+ //# sourceMappingURL=apps-access.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"apps-access.d.ts","sourceRoot":"","sources":["../../src/commands/apps-access.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AACtD,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAwCzC,mDAAmD;AACnD,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,MAAM,GAAG,SAAS,EAAE,IAAI,EAAE,MAAM,GAAG,kBAAkB,CAI1F;AAED,oDAAoD;AACpD,wBAAgB,eAAe,CAAC,GAAG,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,GAAG,OAAO,CAIzE;AAED,wBAAgB,yBAAyB,CAAC,GAAG,EAAE,OAAO,QA2GrD"}
@@ -0,0 +1,141 @@
1
+ import { resolveCredentials } from '../lib/client.js';
2
+ import { parsePositiveInt, printError, printJson, stripPrllScheme } from '../lib/output.js';
3
+ import { appAndArg, appIdFrom, withApp } from './apps-args.js';
4
+ /** `parall app access list | members | add | remove | log`
5
+ * (docs/engineering-design/mini-app-access-design.md §6.3): how far the rest
6
+ * of the organization reaches into an app, the people given more one by
7
+ * one, and the record of every change. The server decides who may see and
8
+ * change what; these commands only name the request. */
9
+ /** The levels the help and the local errors name. `parseMemberLevel` also
10
+ * passes `none` through as the API spells it — the server decides whether
11
+ * it takes it — so this CLI keeps working once the server accepts it. */
12
+ const LEVELS = 'read or write';
13
+ const ACCESS_HELP = `
14
+ Levels:
15
+ read open the app, call its read actions and see its call record
16
+ write also call its write actions — every app's default
17
+
18
+ Everyone else in the organization gets the app's member level (members).
19
+ People added one by one (add) get the higher of that and their own level:
20
+ the list only ever gives more, it never takes anyone below the member
21
+ level. The app's authors and org owners/admins always hold it outright.
22
+
23
+ Who can change it: the app's authors (agents too) and org owners/admins.
24
+ Anyone who can open the app sees the member level and their own level
25
+ (list); only those who can change it also see the list and the record of
26
+ every change, author changes included (log).
27
+
28
+ Keep in mind:
29
+ - Only write actions are refused to people who can only read. A read
30
+ action does whatever its code does for every reader — an outbound
31
+ request included — so put anything with a side effect in a write action.
32
+ - Taking access away refuses the person's next call, but a browser that
33
+ already loaded the page can fetch that version's files for up to an
34
+ hour. Nothing bundled into the page is protected by this setting: keep
35
+ what must stay private in the Database and return it from a read action.`;
36
+ /** A member level as given on the command line. */
37
+ export function parseMemberLevel(raw, what) {
38
+ const level = raw?.trim();
39
+ if (level === 'read' || level === 'write' || level === 'none')
40
+ return level;
41
+ throw new Error(`${what} must be ${LEVELS}`);
42
+ }
43
+ /** A level on the access list: never below read. */
44
+ export function parseGrantLevel(raw) {
45
+ const level = raw?.trim();
46
+ if (level === 'read' || level === 'write')
47
+ return level;
48
+ throw new Error(`--level must be ${LEVELS}`);
49
+ }
50
+ export function registerAppAccessCommands(app) {
51
+ const access = app
52
+ .command('access')
53
+ .description('Who can use an app: everyone else in the organization, and people added one by one (read or write)')
54
+ .addHelpText('after', ACCESS_HELP);
55
+ withApp(access
56
+ .command('list')
57
+ .description("Show the app's member level and your own level; its authors and org owners/admins also see who was added one by one")).action(async (appId, opts) => {
58
+ try {
59
+ const id = appIdFrom(appId, opts.app);
60
+ const { client, orgId } = resolveCredentials();
61
+ printJson(await client.getMiniAppAccess(orgId, id));
62
+ }
63
+ catch (err) {
64
+ printError(err);
65
+ }
66
+ });
67
+ access
68
+ .command('members')
69
+ .description("Set how far everyone else in the organization reaches into the app: read or write (the app's authors or an org owner/admin)")
70
+ .argument('[appId]', 'App ID (app_… or prll://app_…); or pass --app')
71
+ .argument('[level]', LEVELS)
72
+ .option('--app <appId>', 'App ID, in place of the first argument')
73
+ .action(async (first, second, opts) => {
74
+ try {
75
+ const [id, raw] = appAndArg(first, second, opts.app, `level (${LEVELS})`);
76
+ const level = parseMemberLevel(raw, 'The level');
77
+ const { client, orgId } = resolveCredentials();
78
+ printJson(await client.setMiniAppMemberAccess(orgId, id, level));
79
+ }
80
+ catch (err) {
81
+ printError(err);
82
+ }
83
+ });
84
+ access
85
+ .command('add')
86
+ .description("Give a member of the organization (person or agent) read or write on the app, or change their level (the app's authors or an org owner/admin)")
87
+ .argument('[appId]', 'App ID (app_… or prll://app_…); or pass --app')
88
+ .argument('[userId]', 'User or agent ID (usr_…)')
89
+ .option('--app <appId>', 'App ID, in place of the first argument')
90
+ .requiredOption('--level <level>', LEVELS)
91
+ .action(async (first, second, opts) => {
92
+ try {
93
+ const [id, userId] = appAndArg(first, second, opts.app, 'user ID (usr_…)');
94
+ const level = parseGrantLevel(opts.level);
95
+ const { client, orgId } = resolveCredentials();
96
+ printJson(await client.setMiniAppAccessGrant(orgId, id, stripPrllScheme(userId), level));
97
+ }
98
+ catch (err) {
99
+ printError(err);
100
+ }
101
+ });
102
+ access
103
+ .command('remove')
104
+ .description("Take someone off the app's access list; they keep the member level (the app's authors or an org owner/admin)")
105
+ .argument('[appId]', 'App ID (app_… or prll://app_…); or pass --app')
106
+ .argument('[userId]', 'User or agent ID (usr_…)')
107
+ .option('--app <appId>', 'App ID, in place of the first argument')
108
+ .action(async (first, second, opts) => {
109
+ try {
110
+ const [id, userId] = appAndArg(first, second, opts.app, 'user ID (usr_…)');
111
+ const { client, orgId } = resolveCredentials();
112
+ printJson(await client.removeMiniAppAccessGrant(orgId, id, stripPrllScheme(userId)));
113
+ }
114
+ catch (err) {
115
+ printError(err);
116
+ }
117
+ });
118
+ withApp(access
119
+ .command('log')
120
+ .description("List the changes to the app's access and its authors, newest first: who, when, from what to what (the app's authors or an org owner/admin)"))
121
+ .option('--limit <n>', 'Entries to return (default 50, at most 200)')
122
+ .option('--before-id <id>', "Page: the previous page's last id")
123
+ .action(async (appId, opts) => {
124
+ try {
125
+ const id = appIdFrom(appId, opts.app);
126
+ const limit = parsePositiveInt(opts.limit);
127
+ if (opts.limit !== undefined && limit === undefined) {
128
+ throw new Error('--limit must be a positive number');
129
+ }
130
+ const beforeId = parsePositiveInt(opts.beforeId);
131
+ if (opts.beforeId !== undefined && beforeId === undefined) {
132
+ throw new Error('--before-id must be the id of a change (a positive number)');
133
+ }
134
+ const { client, orgId } = resolveCredentials();
135
+ printJson(await client.getMiniAppAccessLog(orgId, id, { limit, before_id: beforeId }));
136
+ }
137
+ catch (err) {
138
+ printError(err);
139
+ }
140
+ });
141
+ }
@@ -3,9 +3,11 @@ import type { Command } from 'commander';
3
3
  /** `parall app action list | run | log`
4
4
  * (docs/engineering-design/mini-app-action-design.md §3, §5.3, §10): the
5
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. */
6
+ * the app lists and runs its read actions, and those who can change it its
7
+ * write actions too (`app access`, apps-access.ts); `--v` names a version
8
+ * other than the current one, and `--local` runs the local build
9
+ * (apps-action-local.ts), both of which take the app's authors or an org
10
+ * owner/admin. */
9
11
  export declare function registerAppActionCommands(app: Command): void;
10
12
  interface ParamOptions {
11
13
  param?: string[];
@@ -1 +1 @@
1
- {"version":3,"file":"apps-actions.d.ts","sourceRoot":"","sources":["../../src/commands/apps-actions.ts"],"names":[],"mappings":"AAEA,OAAO,EAGL,KAAK,mBAAmB,EAEzB,MAAM,aAAa,CAAC;AACrB,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAOzC;;;;;iEAKiE;AACjE,wBAAgB,yBAAyB,CAAC,GAAG,EAAE,OAAO,QAsIrD;AAaD,UAAU,YAAY;IACpB,KAAK,CAAC,EAAE,MAAM,EAAE,CAAC;IACjB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB;AAED;;0EAE0E;AAC1E,wBAAsB,WAAW,CAC/B,MAAM,EAAE,mBAAmB,GAAG,IAAI,EAClC,IAAI,EAAE,YAAY,GACjB,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAkBlC"}
1
+ {"version":3,"file":"apps-actions.d.ts","sourceRoot":"","sources":["../../src/commands/apps-actions.ts"],"names":[],"mappings":"AAEA,OAAO,EAGL,KAAK,mBAAmB,EAEzB,MAAM,aAAa,CAAC;AACrB,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAOzC;;;;;;;kBAOkB;AAClB,wBAAgB,yBAAyB,CAAC,GAAG,EAAE,OAAO,QAsIrD;AAaD,UAAU,YAAY;IACpB,KAAK,CAAC,EAAE,MAAM,EAAE,CAAC;IACjB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB;AAED;;0EAE0E;AAC1E,wBAAsB,WAAW,CAC/B,MAAM,EAAE,mBAAmB,GAAG,IAAI,EAClC,IAAI,EAAE,YAAY,GACjB,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAkBlC"}
@@ -9,9 +9,11 @@ import { mapActionStack } from './apps-action-stack.js';
9
9
  /** `parall app action list | run | log`
10
10
  * (docs/engineering-design/mini-app-action-design.md §3, §5.3, §10): the
11
11
  * same endpoints the page calls, for agents and authors. Anyone who can open
12
- * the app lists and runs its actions; `--v` names a version other than the
13
- * current one, and `--local` runs the local build (apps-action-local.ts),
14
- * both of which take the app's authors or an org owner/admin. */
12
+ * the app lists and runs its read actions, and those who can change it its
13
+ * write actions too (`app access`, apps-access.ts); `--v` names a version
14
+ * other than the current one, and `--local` runs the local build
15
+ * (apps-action-local.ts), both of which take the app's authors or an org
16
+ * owner/admin. */
15
17
  export function registerAppActionCommands(app) {
16
18
  const action = app
17
19
  .command('action')
@@ -7,11 +7,13 @@ export interface DevPageContext {
7
7
  name: string;
8
8
  database_id: string;
9
9
  };
10
+ /** `access` is the viewer's level the page gets (viewer.access). */
10
11
  viewer: {
11
12
  id: string;
12
13
  display_name: string;
13
14
  is_agent: boolean;
14
15
  role: string;
16
+ access: 'read' | 'write';
15
17
  };
16
18
  }
17
19
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"apps-dev-page.d.ts","sourceRoot":"","sources":["../../src/commands/apps-dev-page.ts"],"names":[],"mappings":"AAAA,mEAAmE;AACnE,MAAM,WAAW,cAAc;IAC7B,wDAAwD;IACxD,SAAS,EAAE,MAAM,CAAC;IAClB,GAAG,EAAE;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAC;QAAC,WAAW,EAAE,MAAM,CAAA;KAAE,CAAC;IACvD,MAAM,EAAE;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,YAAY,EAAE,MAAM,CAAC;QAAC,QAAQ,EAAE,OAAO,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE,CAAC;CAC/E;AAYD;;;;;;;GAOG;AACH,wBAAgB,cAAc,CAAC,GAAG,EAAE,cAAc,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM,CAiPzE"}
1
+ {"version":3,"file":"apps-dev-page.d.ts","sourceRoot":"","sources":["../../src/commands/apps-dev-page.ts"],"names":[],"mappings":"AAAA,mEAAmE;AACnE,MAAM,WAAW,cAAc;IAC7B,wDAAwD;IACxD,SAAS,EAAE,MAAM,CAAC;IAClB,GAAG,EAAE;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAC;QAAC,WAAW,EAAE,MAAM,CAAA;KAAE,CAAC;IACvD,oEAAoE;IACpE,MAAM,EAAE;QACN,EAAE,EAAE,MAAM,CAAC;QACX,YAAY,EAAE,MAAM,CAAC;QACrB,QAAQ,EAAE,OAAO,CAAC;QAClB,IAAI,EAAE,MAAM,CAAC;QACb,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC;KAC1B,CAAC;CACH;AAYD;;;;;;;GAOG;AACH,wBAAgB,cAAc,CAAC,GAAG,EAAE,cAAc,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM,CAiPzE"}
@@ -83,15 +83,15 @@ li{padding:10px 12px;border-bottom:1px solid var(--line)}
83
83
  const ctx = JSON.parse(document.getElementById('ctx').textContent);
84
84
  const zh = (navigator.language || '').toLowerCase().startsWith('zh');
85
85
  const T = zh
86
- ? { local: '本地构建 · 未发布', real: '连的是真实 Database,写会生效', as: (n, r) => '以 ' + n + '(' + r + ')的身份', reload: '重新加载', calls: '调用记录', empty: '页面调用 action 后会显示在这里。', noToken: '地址里缺少令牌:请用终端里打印的完整地址打开,否则 action 调不通。', write: '写', read: '读', ok: '成功', failed: '失败', timeout: '超时', limit: '超限', gone: '本地联调服务没有回应', pageError: '页面报错', kinds: { exception: '页面异常', rejection: '未处理的 Promise', action: 'action 失败' } }
87
- : { local: 'Local build · not published', real: 'Real Database: writes take effect', as: (n, r) => 'As ' + n + ' (' + r + ')', reload: 'Reload', calls: 'Calls', empty: 'Actions the page calls show up here.', noToken: 'The address has no token: open the full address the terminal printed, or actions cannot be called.', write: 'write', read: 'read', ok: 'ok', failed: 'failed', timeout: 'timed out', limit: 'over limit', gone: 'The local dev server did not answer', pageError: 'Page error', kinds: { exception: 'thrown', rejection: 'unhandled promise', action: 'action failed' } };
86
+ ? { local: '本地构建 · 未发布', real: '连的是真实 Database,写会生效', as: (n, r) => '以 ' + n + '(' + r + ')的身份', viewOnly: '只读:写类 action 会被拒绝', reload: '重新加载', calls: '调用记录', empty: '页面调用 action 后会显示在这里。', noToken: '地址里缺少令牌:请用终端里打印的完整地址打开,否则 action 调不通。', write: '写', read: '读', ok: '成功', failed: '失败', timeout: '超时', limit: '超限', gone: '本地联调服务没有回应', pageError: '页面报错', kinds: { exception: '页面异常', rejection: '未处理的 Promise', action: 'action 失败' } }
87
+ : { local: 'Local build · not published', real: 'Real Database: writes take effect', as: (n, r) => 'As ' + n + ' (' + r + ')', viewOnly: 'View only: write actions are refused', reload: 'Reload', calls: 'Calls', empty: 'Actions the page calls show up here.', noToken: 'The address has no token: open the full address the terminal printed, or actions cannot be called.', write: 'write', read: 'read', ok: 'ok', failed: 'failed', timeout: 'timed out', limit: 'over limit', gone: 'The local dev server did not answer', pageError: 'Page error', kinds: { exception: 'thrown', rejection: 'unhandled promise', action: 'action failed' } };
88
88
  const $ = (id) => document.getElementById(id);
89
89
  const token = new URLSearchParams(location.search).get('t') || '';
90
90
  $('addr').textContent = location.host + '/?t=' + (token ? '••••••' : '');
91
91
  $('name').textContent = ctx.app.name;
92
92
  $('local').textContent = T.local;
93
93
  $('real').textContent = T.real;
94
- $('viewer').textContent = T.as(ctx.viewer.display_name, ctx.viewer.role);
94
+ $('viewer').textContent = T.as(ctx.viewer.display_name, ctx.viewer.role) + (ctx.viewer.access === 'read' ? ' · ' + T.viewOnly : '');
95
95
  $('reload').textContent = T.reload;
96
96
  $('calls').textContent = T.calls;
97
97
  $('empty').textContent = T.empty;
@@ -9,6 +9,15 @@ import { type MiniAppActionKind } from '@parall/sdk';
9
9
  * loopback Host (so DNS rebinding cannot reach it); JSON bodies only. The
10
10
  * page and the host page are on two ports — two origins — like the app
11
11
  * origin and the Parall origin. */
12
+ /** The viewer's level on the app the dev host reports (viewer.access). */
13
+ export type DevAccess = 'read' | 'write';
14
+ /** What the page gets for a write action when the dev host shows it to
15
+ * someone who can only view the app: the code Parall answers with, and a
16
+ * message that says the refusal is the dev host's. */
17
+ export declare const DEV_VIEW_ONLY_REFUSAL: {
18
+ readonly code: "PERMISSION_DENIED";
19
+ readonly message: "You can only view this app, so its write actions are refused (parall app dev --access read: nothing ran)";
20
+ };
12
21
  /** One call as the host page shows it and answers the page. */
13
22
  export interface DevCallAnswer {
14
23
  ok: boolean;
@@ -32,7 +41,7 @@ export interface DevCallAnswer {
32
41
  /** Printed when `parall app dev` starts: it is a server, and an agent that
33
42
  * waits for it to return waits until its tool gives up. */
34
43
  export declare const DEV_LONG_RUNNING_HINT = " This keeps running until stopped: from a script or an agent, start it in the background (parall app dev \u2026 > dev.log 2>&1 &). To check one action, parall app action run <app> <name> --local runs it and returns.";
35
- export declare function serveAppDev(dist: string, port: number, appId: string): Promise<void>;
44
+ export declare function serveAppDev(dist: string, port: number, appId: string, accessOverride?: DevAccess): Promise<void>;
36
45
  /** The deployment's files-worker origin, the one outside source the
37
46
  * apps-worker lets a page load images from (attachment images the platform
38
47
  * serves). Deployments name it after the API host — `api.X` serves files from
@@ -1 +1 @@
1
- {"version":3,"file":"apps-dev-server.d.ts","sourceRoot":"","sources":["../../src/commands/apps-dev-server.ts"],"names":[],"mappings":"AAIA,OAAO,EAAY,KAAK,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAK/D;;;;;;;;;mCASmC;AAEnC,+DAA+D;AAC/D,MAAM,WAAW,aAAa;IAC5B,EAAE,EAAE,OAAO,CAAC;IACZ,IAAI,CAAC,EAAE,iBAAiB,CAAC;IACzB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,MAAM,CAAC,EAAE,OAAO,CAAC;IACjB,KAAK,CAAC,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAC;QAAC,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;KAAE,CAAC;IAC7E,+BAA+B;IAC/B,OAAO,EAAE,MAAM,CAAC;IAChB,qDAAqD;IACrD,QAAQ,CAAC,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,EAAE,EAAE,MAAM,CAAA;KAAE,CAAC;IACxC,WAAW,EAAE,MAAM,CAAC;CACrB;AAKD;2DAC2D;AAC3D,eAAO,MAAM,qBAAqB,6NACqL,CAAC;AAExN,wBAAsB,WAAW,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAqF1F;AAED;;;;mEAImE;AACnE,wBAAgB,cAAc,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAQrD;AAcD;iDACiD;AACjD,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAE9E"}
1
+ {"version":3,"file":"apps-dev-server.d.ts","sourceRoot":"","sources":["../../src/commands/apps-dev-server.ts"],"names":[],"mappings":"AAIA,OAAO,EAAY,KAAK,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAK/D;;;;;;;;;mCASmC;AAEnC,0EAA0E;AAC1E,MAAM,MAAM,SAAS,GAAG,MAAM,GAAG,OAAO,CAAC;AAEzC;;sDAEsD;AACtD,eAAO,MAAM,qBAAqB;;;CAIxB,CAAC;AAEX,+DAA+D;AAC/D,MAAM,WAAW,aAAa;IAC5B,EAAE,EAAE,OAAO,CAAC;IACZ,IAAI,CAAC,EAAE,iBAAiB,CAAC;IACzB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,MAAM,CAAC,EAAE,OAAO,CAAC;IACjB,KAAK,CAAC,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAC;QAAC,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;KAAE,CAAC;IAC7E,+BAA+B;IAC/B,OAAO,EAAE,MAAM,CAAC;IAChB,qDAAqD;IACrD,QAAQ,CAAC,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,EAAE,EAAE,MAAM,CAAA;KAAE,CAAC;IACxC,WAAW,EAAE,MAAM,CAAC;CACrB;AAKD;2DAC2D;AAC3D,eAAO,MAAM,qBAAqB,6NACqL,CAAC;AAExN,wBAAsB,WAAW,CAC/B,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,MAAM,EACZ,KAAK,EAAE,MAAM,EACb,cAAc,CAAC,EAAE,SAAS,GACzB,OAAO,CAAC,IAAI,CAAC,CAqGf;AAED;;;;mEAImE;AACnE,wBAAgB,cAAc,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAQrD;AAcD;iDACiD;AACjD,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAE9E"}
@@ -6,12 +6,19 @@ import { ApiError } from '@parall/sdk';
6
6
  import { resolveCredentials } from '../lib/client.js';
7
7
  import { readLocalAction, runLocalAction } from './apps-action-local.js';
8
8
  import { devAppHostPage } from './apps-dev-page.js';
9
+ /** What the page gets for a write action when the dev host shows it to
10
+ * someone who can only view the app: the code Parall answers with, and a
11
+ * message that says the refusal is the dev host's. */
12
+ export const DEV_VIEW_ONLY_REFUSAL = {
13
+ code: 'PERMISSION_DENIED',
14
+ message: 'You can only view this app, so its write actions are refused (parall app dev --access read: nothing ran)',
15
+ };
9
16
  const MAX_BODY_BYTES = 1 << 20;
10
17
  const MAX_CONSOLE_CHARS = 8000;
11
18
  /** Printed when `parall app dev` starts: it is a server, and an agent that
12
19
  * waits for it to return waits until its tool gives up. */
13
20
  export const DEV_LONG_RUNNING_HINT = ' This keeps running until stopped: from a script or an agent, start it in the background (parall app dev … > dev.log 2>&1 &). To check one action, parall app action run <app> <name> --local runs it and returns.';
14
- export async function serveAppDev(dist, port, appId) {
21
+ export async function serveAppDev(dist, port, appId, accessOverride) {
15
22
  const { client, orgId } = resolveCredentials();
16
23
  const apiUrl = process.env.PRLL_API_URL ?? '';
17
24
  const [me, app, members] = await Promise.all([
@@ -20,6 +27,9 @@ export async function serveAppDev(dist, port, appId) {
20
27
  client.getOrgMembers(orgId),
21
28
  ]);
22
29
  const role = members.find((m) => m.user_id === me.id)?.role ?? 'member';
30
+ // Who runs this is almost always an author (they hold the app outright);
31
+ // --access read shows the page as someone who can only view it.
32
+ const access = accessOverride ?? app.viewer_access ?? 'write';
23
33
  const appPort = port + 1;
24
34
  const filesOrigin = filesOriginFor(apiUrl);
25
35
  const token = randomBytes(24).toString('base64url');
@@ -38,6 +48,11 @@ export async function serveAppDev(dist, port, appId) {
38
48
  // Read on every call, so a rebuild takes effect without a restart.
39
49
  const local = await readLocalAction(dist, name);
40
50
  kind = local.kind;
51
+ if (access === 'read' && kind === 'write') {
52
+ // As Parall answers someone who can only view the app: refused
53
+ // before anything runs.
54
+ return done({ ok: false, kind, error: { ...DEV_VIEW_ONLY_REFUSAL } });
55
+ }
41
56
  const out = await runLocalAction(client, orgId, app.id, apiUrl, dist, name, local, params, {
42
57
  console: (text) => {
43
58
  printed = (printed + text).slice(-MAX_CONSOLE_CHARS);
@@ -71,7 +86,13 @@ export async function serveAppDev(dist, port, appId) {
71
86
  const page = {
72
87
  appOrigin: `http://127.0.0.1:${appPort}`,
73
88
  app: { id: app.id, name: app.name, database_id: app.database_id },
74
- viewer: { id: me.id, display_name: me.display_name, is_agent: me.type === 'agent', role },
89
+ viewer: {
90
+ id: me.id,
91
+ display_name: me.display_name,
92
+ is_agent: me.type === 'agent',
93
+ role,
94
+ access,
95
+ },
75
96
  };
76
97
  const host = createServer((req, res) => {
77
98
  handleHostRequest(req, res, { port, token, page, run }).catch(() => failRequest(res));
@@ -89,7 +110,9 @@ export async function serveAppDev(dist, port, appId) {
89
110
  }
90
111
  console.error(`Mini App dev host: http://127.0.0.1:${port}/?t=${token}`);
91
112
  console.error(` ${app.name} (${app.id}) from ${dist}, page on http://127.0.0.1:${appPort}`);
92
- console.error(" Actions run on this machine against the app's real Database: writes are real. Ctrl-C to stop.");
113
+ console.error(access === 'read'
114
+ ? " As someone who can only view the app: its write actions are refused without running; read actions run on this machine against the app's real Database. Ctrl-C to stop."
115
+ : " Actions run on this machine against the app's real Database: writes are real. Ctrl-C to stop.");
93
116
  console.error(DEV_LONG_RUNNING_HINT);
94
117
  }
95
118
  /** The deployment's files-worker origin, the one outside source the
@@ -1,8 +1,19 @@
1
1
  import type { Command } from 'commander';
2
+ import { type DevAccess } from './apps-dev-server.js';
2
3
  /** `parall app dev`: a local host page speaking the same bridge as the
3
4
  * Parall hosts, for an author (often an agent with a headless browser) to
4
5
  * look at the built page before publishing. With --app the page also calls
5
6
  * the local build's actions against the app's real Database
6
- * (apps-dev-server.ts); without it the host is static and offline. */
7
+ * (apps-dev-server.ts); without it the host is static and offline.
8
+ * `--access read` shows the page to someone who can only view the app
9
+ * (mini-app-access-design.md §5.2): the viewer says so, and with --app its
10
+ * write actions are refused here, as Parall refuses them, without running. */
7
11
  export declare function registerAppDevCommand(app: Command): void;
12
+ /** The viewer's level the host reports, as --access gives it; undefined
13
+ * when --access is not given. */
14
+ export declare function devAccess(raw: string | undefined): DevAccess | undefined;
15
+ /** The local host page: the host side of the bridge shell — answers ready
16
+ * with a dev viewer at `access`, relays resize, logs everything else. The
17
+ * same request/response protocol the real hosts speak (§6.3, shell subset). */
18
+ export declare function devHostPage(access: DevAccess): string;
8
19
  //# sourceMappingURL=apps-dev.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"apps-dev.d.ts","sourceRoot":"","sources":["../../src/commands/apps-dev.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAIzC;;;;sEAIsE;AACtE,wBAAgB,qBAAqB,CAAC,GAAG,EAAE,OAAO,QA0CjD"}
1
+ {"version":3,"file":"apps-dev.d.ts","sourceRoot":"","sources":["../../src/commands/apps-dev.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAEzC,OAAO,EAAyB,KAAK,SAAS,EAAe,MAAM,sBAAsB,CAAC;AAE1F;;;;;;;8EAO8E;AAC9E,wBAAgB,qBAAqB,CAAC,GAAG,EAAE,OAAO,QA+CjD;AAgBD;iCACiC;AACjC,wBAAgB,SAAS,CAAC,GAAG,EAAE,MAAM,GAAG,SAAS,GAAG,SAAS,GAAG,SAAS,CAKxE;AAmCD;;+EAE+E;AAC/E,wBAAgB,WAAW,CAAC,MAAM,EAAE,SAAS,GAAG,MAAM,CAiCrD"}
@@ -7,7 +7,10 @@ import { DEV_LONG_RUNNING_HINT, serveAppDev } from './apps-dev-server.js';
7
7
  * Parall hosts, for an author (often an agent with a headless browser) to
8
8
  * look at the built page before publishing. With --app the page also calls
9
9
  * the local build's actions against the app's real Database
10
- * (apps-dev-server.ts); without it the host is static and offline. */
10
+ * (apps-dev-server.ts); without it the host is static and offline.
11
+ * `--access read` shows the page to someone who can only view the app
12
+ * (mini-app-access-design.md §5.2): the viewer says so, and with --app its
13
+ * write actions are refused here, as Parall refuses them, without running. */
11
14
  export function registerAppDevCommand(app) {
12
15
  app
13
16
  .command('dev')
@@ -15,17 +18,19 @@ export function registerAppDevCommand(app) {
15
18
  .option('--dist <dir>', 'The built bundle directory', 'dist')
16
19
  .option('--port <n>', 'Port to listen on (with --app, the page uses the next one)', '5180')
17
20
  .option('--app <app>', "Connect the page to this app: the actions it calls run on this machine against the app's real Database (writes are real; needs miniflare in the project)")
21
+ .option('--access <level>', 'Show the page as someone who can only view the app: read (with --app its write actions are refused without running), or write. Default: your own level on --app, else write')
18
22
  .action(async (opts) => {
19
23
  try {
24
+ const access = devAccess(opts.access);
20
25
  const dist = resolve(opts.dist);
21
26
  await fs.access(join(dist, 'index.html'));
22
27
  const port = Number(opts.port);
23
28
  if (opts.app) {
24
- await serveAppDev(dist, port, stripPrllScheme(opts.app));
29
+ await serveAppDev(dist, port, stripPrllScheme(opts.app), access);
25
30
  return;
26
31
  }
27
32
  const server = createServer((req, res) => {
28
- void handleDevRequest(dist, req.url ?? '/', res);
33
+ void handleDevRequest(dist, req.url ?? '/', res, access ?? 'write');
29
34
  });
30
35
  // Loopback only: this serves the app's build directory and must not
31
36
  // be reachable from the local network. A bind failure (port in use)
@@ -39,7 +44,7 @@ export function registerAppDevCommand(app) {
39
44
  });
40
45
  });
41
46
  console.error(`Mini App dev host: http://127.0.0.1:${port}/ (serving ${dist})`);
42
- console.error('The host page answers parall.ready() with a local dev viewer; Ctrl-C to stop.');
47
+ console.error(`The host page answers parall.ready() with a local dev viewer who can ${access === 'read' ? 'only view the app' : 'change the app'}; Ctrl-C to stop.`);
43
48
  console.error(DEV_LONG_RUNNING_HINT);
44
49
  }
45
50
  catch (err) {
@@ -60,12 +65,22 @@ const devContentTypes = {
60
65
  '.map': 'application/json',
61
66
  '.woff2': 'font/woff2',
62
67
  };
63
- async function handleDevRequest(dist, url, res) {
68
+ /** The viewer's level the host reports, as --access gives it; undefined
69
+ * when --access is not given. */
70
+ export function devAccess(raw) {
71
+ if (raw === undefined)
72
+ return undefined;
73
+ const level = raw.trim();
74
+ if (level === 'read' || level === 'write')
75
+ return level;
76
+ throw new Error('--access must be read or write');
77
+ }
78
+ async function handleDevRequest(dist, url, res, access) {
64
79
  try {
65
80
  const pathname = decodeURIComponent(new URL(url, 'http://localhost').pathname);
66
81
  if (pathname === '/' || pathname === '/index.html') {
67
82
  res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
68
- res.end(devHostPage());
83
+ res.end(devHostPage(access));
69
84
  return;
70
85
  }
71
86
  if (pathname.startsWith('/app/')) {
@@ -89,9 +104,9 @@ async function handleDevRequest(dist, url, res) {
89
104
  }
90
105
  }
91
106
  /** The local host page: the host side of the bridge shell — answers ready
92
- * with a dev viewer, relays resize, logs everything else. The same
93
- * request/response protocol the real hosts speak (§6.3, shell subset). */
94
- function devHostPage() {
107
+ * with a dev viewer at `access`, relays resize, logs everything else. The
108
+ * same request/response protocol the real hosts speak (§6.3, shell subset). */
109
+ export function devHostPage(access) {
95
110
  return `<!doctype html>
96
111
  <html>
97
112
  <head><meta charset="utf-8"><title>Mini App dev host</title>
@@ -108,7 +123,7 @@ function devHostPage() {
108
123
  if (!msg || msg.parall !== 'v1' || typeof msg.id !== 'number') return;
109
124
  if (msg.method === 'ready') {
110
125
  frame.contentWindow.postMessage({ parall: 'v1', id: msg.id, result: {
111
- viewer: { id: 'usr_dev', display_name: 'Dev Viewer', is_agent: false },
126
+ viewer: { id: 'usr_dev', display_name: 'Dev Viewer', is_agent: false, access: ${JSON.stringify(access)} },
112
127
  app: { id: 'app_dev', name: 'local dev', version_seq: 0 },
113
128
  route: location.hash.slice(1) || '',
114
129
  }}, '*');
@@ -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 \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";
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 /** How far the viewer reaches into this app: 'write' \u2014 they may call\n * every action \u2014 or 'read' \u2014 they may only call read actions, and the\n * platform refuses their write actions. A hint for hiding edit controls,\n * never the gate. Absent from hosts that predate it: read it as 'write'.\n * An action's ctx.viewer does not carry it. */\n access?: 'read' | 'write';\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,64YAAoyY,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,8xZAAsqZ,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 — 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";
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 /** How far the viewer reaches into this app: 'write' — they may call\n * every action — or 'read' — they may only call read actions, and the\n * platform refuses their write actions. A hint for hiding edit controls,\n * never the gate. Absent from hosts that predate it: read it as 'write'.\n * An action's ctx.viewer does not carry it. */\n access?: 'read' | 'write';\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";