dokiworlds-app-sdk 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/GUIDE.md ADDED
@@ -0,0 +1,253 @@
1
+ # dokiworlds-app-sdk 使用指南
2
+
3
+ 适用版本:`dokiworlds-app-sdk@0.2.0`。主要入口是 `createAppClient`、`client.whenReady`、`client.input`、`client.apps.launch`、`client.complete` 和 `client.requestExit`;宿主侧可用 `createAppHost` 和 `createAppsHostExtension`。协议仍为 v2。
4
+
5
+ `0.1.0` 的客户端没有初始化输入读取 API,不能直接用于下面的检定演出插槽。
6
+
7
+ ## 安装与运行条件
8
+
9
+ 在 App 的源码项目中安装工作区包(Windows 示例,按本机仓库位置调整):
10
+
11
+ ```bash
12
+ npm install D:/GameDev/dokiworlds/packages/dokiworlds-app-sdk
13
+ ```
14
+
15
+ SDK 是浏览器端 ESM。App 必须运行在支持 `postMessage` 的 iframe 中,由实现 `dokiworld.app` v2 的宿主加载;`apps.launch` 另外要求宿主允许拉起子 App。`npm install` 只提供 SDK,不会自行创建 App 目录、列表或弹窗。若 App 以静态文件放在 `public/apps`,请用自己的构建工具把 `dokiworlds-app-sdk` 打包进浏览器脚本;浏览器不能直接从静态页面解析 `import ... from 'dokiworlds-app-sdk'` 这个 npm 裸包名。异地交付也可以在包目录运行 `npm pack`,将生成的 tgz 交给同事安装;这不等于发布 npm。
16
+
17
+ ## 检定演出插槽:给 App 作者
18
+
19
+ `check_reveal` 用于展示已经由游戏结算的检定。App 不掷新骰、不改变成功/失败、不发奖励,也不负责推进任务。操作小游戏不复用此插槽;已注册的宝箱使用下文的独立适配器。
20
+
21
+ 启动输入是 `doki.check-reveal.input` v1:
22
+
23
+ ```json
24
+ {
25
+ "contract": "doki.check-reveal.input",
26
+ "version": 1,
27
+ "data": {
28
+ "presentationId": "本次演出唯一标识",
29
+ "locale": "zh-CN",
30
+ "title": "说得孙癞子自己松口",
31
+ "check": { "attribute": "CHA", "roll": 15, "modifier": 1, "total": 16, "dc": 11, "passed": true }
32
+ }
33
+ }
34
+ ```
35
+
36
+ 按原值展示 `check`;`attribute` 是内容中的属性标识,不要求一定为示例中的 `CHA`。完成输出必须且只能包含本次 `presentationId` 与 `status: 'viewed'`:
37
+
38
+ ```js
39
+ import { createAppClient } from 'dokiworlds-app-sdk';
40
+
41
+ // 填游戏宿主的实际 origin;跨域时不能写小游戏自己的 window.location.origin。
42
+ const client = createAppClient({ appId: 'fortune-reveal', targetOrigin: 'https://game.example' });
43
+ client.connect();
44
+ window.addEventListener('pagehide', () => client.dispose(), { once: true });
45
+
46
+ const input = await client.whenReady({ timeoutMs: 10_000 });
47
+ if (input.contract !== 'doki.check-reveal.input' || input.version !== 1) {
48
+ client.requestExit();
49
+ throw new Error('Unsupported input contract');
50
+ }
51
+ const { presentationId, title, check, locale } = input.data;
52
+ // App 在这里使用 title、check、locale 播放自己的演出。
53
+ // 只有演出真实结束或玩家点击 App 内“看完”时,才调用这个函数。
54
+ async function finishPresentation() {
55
+ const acknowledgement = await client.complete({
56
+ contract: 'doki.check-reveal.result', version: 1,
57
+ data: { presentationId, status: 'viewed' },
58
+ });
59
+ if (acknowledgement !== 'accepted') throw new Error('Presentation rejected');
60
+ client.dispose();
61
+ }
62
+ // iframe 中的按键不会冒泡到游戏:App 应把 Escape/自己的退出按钮接到 requestExit。
63
+ window.addEventListener('keydown', (event) => {
64
+ if (event.key === 'Escape') client.requestExit();
65
+ });
66
+ ```
67
+
68
+ `client.input` 在初始化前为 `null`,初始化后为输入副本;修改副本不会改变宿主输入。`whenReady` 可在 connect 前后订阅,已经初始化时立即返回;超时和 dispose 会拒绝等待。App 也应处理自己的加载/播放错误并调用 `requestExit`。
69
+
70
+ 宿主有 10 秒初始化上限、初始化后 30 秒演出上限;始终提供正式结果和继续/跳过入口。关闭、跳过、超时、返回旧演出 ID 或错误契约都不会改变已结算结果。减少动态效果时直接显示正式结果,不加载 App。这个插槽不允许 `apps.launch`,调用会收到 `unsupported-operation`。
71
+
72
+ ## 检定演出插槽:给接入方
73
+
74
+ 1. 同事提供固定 `appId`、可嵌入的部署地址,并实现上述契约。服务器需允许游戏域名嵌入(检查 CSP `frame-ancestors` 和 `X-Frame-Options`)。
75
+ 2. 在 `frontend/src/lib/app-registry.ts` 的 `APP_REGISTRY` 登记经过审核的地址,例如:
76
+
77
+ ```ts
78
+ { id: 'fortune-reveal', name: '检定演出', url: 'https://apps.example/fortune/', slots: ['check_reveal'] }
79
+ ```
80
+
81
+ 3. 在剧本源 `pack.yaml` 的现有 `presentation` 中添加以下内容,再经原有编译/版本流程交付:
82
+
83
+ ```yaml
84
+ presentation:
85
+ # 保留原有字段
86
+ app_slots:
87
+ check_reveal:
88
+ app_id: fortune-reveal
89
+ ```
90
+
91
+ 剧本只能引用登记的 ID,不能提供 URL。正式插槽要求与游戏不同源的 HTTPS 地址;开发模式允许独立 localhost/127.0.0.1 端口的 HTTP 服务。独立 App 不应和游戏共享登录凭据。iframe 仅允许脚本、同源资源访问与指针锁,不授予宿主状态、导航或子 App 拉起能力。
92
+
93
+ 未配置插槽时,正常游戏会检查部署方许可的 Physics Dice 是否支持下述服务端结果协议;兼容时使用骰子演出,否则保留原来的抽签/结果界面。显式配置其他 App 时沿用 `APP_REGISTRY`(当前静态表为空),配置不存在或不合法时显示正式结果。目录本身不能注入新的 App 地址。
94
+
95
+ 开发 **APPS** 目录扫描仅供调试,不等于正式登记;直接从目录启动时输入为空,不能代替一次真实检定联调。`AppFrame.tsx` 由开发入口与正式插槽共用;正式触发点包括 `ContextCard.tsx` 的结果卡与对话中最新的 `ActionResultReceipt.tsx`,统一经过 `GameCheckReveal.tsx`。历史回执不补播演出。
96
+
97
+ ## 宝箱:给玩法接入方
98
+
99
+ 已接入 `game-loot-chest` 的 `doki.game.chest-input` v2 / `doki.game.chest-result` v2。部署地址由 `frontend/src/free-roam/loot-chest-contract.ts` 登记,剧本不能传入可执行 URL。接口依据:[同事发布的接入文档](https://static-doki.aimeng.ai/apps/game-loot-chest/docs/integration.zh-CN.md)。
100
+
101
+ **普通游玩的任务交付已默认接入。** Runtime 根据正式 `Quest Transition.status=completed` 绑定识别交付 Action;当其为独立无检定的 `quest_resolution`,且原效果含可展示的物品/货币报酬时,原交付按钮直接进入宝箱。奖励取自原 Action 的固定授予/真实 NPC 转移,不按任务名猜奖励,不新增任何资产。领取时原消费、NPC 扣款、玩家入账、XP 和任务完成仍原子提交。关闭保留待交付任务;旧存档已完成任务不会补发。App 加载失败可直接领取确定的报酬,仍经相同后端校验。
102
+
103
+ 这一适配同时作用于正式剧本和已有存档,无需开启调试或改写已发布 Pack;不适用的有检定/出牌/既有小游戏行动保留原规则。官渡焚粮记“夜径密探粮情”、挂印封金“白马坡前探敌情”可在正常任务流程中验证。**场景中新增独立宝箱**则使用下面的作者配置。
104
+
105
+ 在合法的独立玩家 Action 上配置 `payload.kind: interaction`、`payload.verb: receive`,不能同时配置 Check 或出牌结算。保留 Action 的 ID、目标、条件、时间成本、反馈等必填字段,增加:
106
+
107
+ ```yaml
108
+ minigame:
109
+ version: 1
110
+ kind: loot_chest
111
+ title: 物资宝箱
112
+ instructions: 打开宝箱并领取物资。
113
+ labels: []
114
+ chest:
115
+ table_id: supplies
116
+ table_version: 1
117
+ root:
118
+ type: all
119
+ children:
120
+ - type: item
121
+ itemId: currency:coin
122
+ name: 铜钱
123
+ quantity: {min: 2, max: 5}
124
+ - type: item
125
+ itemId: item_supplies
126
+ name: 物资
127
+ quantity: {fixed: 1}
128
+ ```
129
+
130
+ 物品必须在同一 Pack 中定义为堆叠物品;`currency:coin` 引用 world 中已有的 `coin`。实例装备奖励暂不支持。掉落树支持 `item / empty / all / choose / repeat`,后端编译时校验结构和引用。独立场景宝箱入口需作者按原有草稿、编译、预览、发布流程配置。
131
+
132
+ 后端 start 保存唯一 attempt/session、完整掉落树、版本摘要和 `mulberry32-v1` seed。App 的开锁属于交互表现,不把客户端操作当作权威技能检定。领取时提交原始输出,由后端重算奖励,连同 Action 的正式效果一次提交。一个 Action 在一份存档中只能领取一次;重复请求不会重复发奖。关闭不扣资源、不推进实践;重新打开同一宝箱不重抽。刷新恢复冻结输入,领取失败可重试。只有正式领取才运行任务和引导的正常结算链。需消耗钥匙时使用 Action 条件和领取时的正式效果。
133
+
134
+ 调试模式中,官渡焚粮记/挂印封金的 **玩法测试 → 操作小游戏 → 开启宝箱** 使用独立测试存档,经过同一正式结算 API。直接从 APPS 预览不发游戏奖励。传输校验仅是第一层;只有游戏后端的领取回执表示实际入账。
135
+
136
+ Physics Dice v1.0.7 当前文档明确不接收指定点数或 seed,不能展示现有权威检定的骰点。游戏侧正式入口已接入兼容性检查,但当前版本不会加载;需发布支持 `doki.check-reveal.input` v1 / `doki.check-reveal.result` v1 的指定结果模式。匹配本文固定 App 身份与地址的兼容版本会进入正常检定演出流程,仍需真实 App 联调验收。[骰子接口说明](https://static-doki.aimeng.ai/apps/game-physics-dice/docs/integration.zh-CN.md)
137
+
138
+ 2026-09-29 已确认采用服务端骰点,App 只展示同一结果。供 App 作者实现的输入、完成回执、边界案例与正式入口交接见[物理骰子接入说明](../../.yunxing/physics-dice-server-result-handoff-20260929.md)。
139
+
140
+ 工程边界、验证和渐进呈现见 [ADR 0024](../../.yunxing/adr/0024-loot-chest-app.md)。
141
+
142
+ ## 在本仓库启动本地 App
143
+
144
+ 在 `frontend/public/apps/` 下为每个 App 建一个子目录,例如 `frontend/public/apps/hello-app/index.html`。目录名就是 SDK 的 `appId`,只接受小写字母、数字、`.` 和 `-`,且必须以字母或数字开头和结尾。打开游戏后点击 **APPS** 按钮即可启动调试界面:本地开发时可选择本机目录或管理员已发布到 `https://dev.aimeng.ai/api/game-admin/catalog` 的线上 App;部署环境只显示该线上发布目录。
145
+
146
+ 如果入口不是 `index.html`,或需要指定输入契约,可放置 `manifest.json`:
147
+
148
+ ```json
149
+ {
150
+ "entry": "index.html",
151
+ "locales": { "en": { "name": "Hello App" } },
152
+ "runtime": { "input": { "contract": "demo.hello.input", "version": 1 } }
153
+ }
154
+ ```
155
+
156
+ `entry` 必须是目录内的相对文件路径。未提供 manifest 时,宿主使用 `index.html`、目录名作为显示名称,以及 `{ "contract": "doki.dev.launch", "version": 1, "data": {} }` 作为初始输入。manifest 中的 `runtime.input` 只定义 `contract` 和 `version`;从 **APPS** 按钮直接启动时,`data` 是空对象。当前本地宿主只枚举存在入口文件的子目录,最多读取前 100 个合法目录。
157
+
158
+ 本地 App 使用与宿主同源的 iframe,以便加载 ES module 和静态资源。这个调试入口只应放入可信任的开发 App。
159
+
160
+ ## App 请求拉起另一个 App
161
+
162
+ 下面是 App 源码示例。先 `connect()`,等 `runId` 非空后再调用 `apps.launch`;否则 SDK 会拒绝尚未初始化的发送动作。`targetOrigin` 填实际宿主 origin;本地开发时可使用 `window.location.origin`。
163
+
164
+ ```js
165
+ import { AppsCapabilityError, createAppClient } from 'dokiworlds-app-sdk';
166
+
167
+ const client = createAppClient({
168
+ appId: 'hello-app',
169
+ targetOrigin: window.location.origin,
170
+ });
171
+ client.connect();
172
+ window.addEventListener('pagehide', () => client.dispose(), { once: true });
173
+
174
+ await client.whenReady({ timeoutMs: 10_000 });
175
+
176
+ try {
177
+ const result = await client.apps.launch({
178
+ appId: 'child-app',
179
+ input: {
180
+ contract: 'demo.child.input',
181
+ version: 1,
182
+ data: { level: 1 },
183
+ },
184
+ });
185
+
186
+ if (result.status === 'completed') {
187
+ console.log('Child output:', result.output);
188
+ } else {
189
+ console.log('Child App was closed without a result');
190
+ }
191
+ } catch (error) {
192
+ if (error instanceof AppsCapabilityError) {
193
+ console.error(`Launch failed: ${error.code}`);
194
+ } else {
195
+ console.error('Launch failed:', error);
196
+ }
197
+ }
198
+
199
+ ```
200
+
201
+ `launch` 返回一个 Promise。子 App 调用 `client.complete(...)` 后,父 App 收到 `{ status: 'completed', output }`;用户关闭子 App 时收到 `{ status: 'cancelled' }`。本地宿主一次最多允许五层 App,会拒绝不存在的 `appId`。
202
+
203
+ `input` 和 `output` 均使用版本化契约 `{ contract, version, data }`。`contract` 是非空字符串,`version` 是正整数,`data` 必须能序列化为有界 JSON。单条 payload 的 JSON 上限为 64 KiB。调用方应提前与目标 App 约定契约名、版本和数据结构。
204
+
205
+ ## App 返回完成结果
206
+
207
+ 被拉起的 App 可以通过 `complete` 把结果交给宿主:
208
+
209
+ ```js
210
+ import { createAppClient } from 'dokiworlds-app-sdk';
211
+
212
+ const client = createAppClient({
213
+ appId: 'child-app',
214
+ targetOrigin: window.location.origin,
215
+ });
216
+ client.connect();
217
+
218
+ // 等待宿主初始化;实际 App 可在自己的 UI 中禁用完成按钮直到初始化成功。
219
+ await client.whenReady({ timeoutMs: 10_000 });
220
+
221
+ // 用户完成操作之后调用。
222
+ const acknowledgement = await client.complete({
223
+ contract: 'demo.child.result',
224
+ version: 1,
225
+ data: { score: 42 },
226
+ });
227
+
228
+ if (acknowledgement !== 'accepted') {
229
+ throw new Error('Host rejected the result');
230
+ }
231
+ client.dispose();
232
+ ```
233
+
234
+ 这里同样需要先初始化;`0.2.0` 推荐用 `await client.whenReady()` 替代轮询并直接读取返回的输入。`complete` 返回 `'accepted'` 或 `'rejected'`;宿主未在约 3 秒内确认时会拒绝 Promise。关闭 App 前应等待确认,避免结果丢失。
235
+
236
+ ## 宿主侧职责与错误处理
237
+
238
+ 宿主负责选择可用 App、校验是否允许拉起、创建目标 iframe,并处理协议消息。`launch` handler 必须返回 `{ status: 'completed', output }` 或 `{ status: 'cancelled' }`。本仓库的宿主协议实现位于 `frontend/src/lib/dev-app-host.ts`,共用 iframe 位于 `frontend/src/free-roam/ui/AppFrame.tsx`,开发入口位于 `frontend/src/free-roam/ui/DevAppLauncher.tsx`,目录读取位于 `frontend/src/lib/dev-app-catalog.ts`。本项目宿主不依赖公开 SDK 包;外部 App 才安装并使用 `dokiworlds-app-sdk`。
239
+
240
+ 常见的 `AppsCapabilityError.code`:
241
+
242
+ | code | 含义 |
243
+ | --- | --- |
244
+ | `invalid-request` | `appId` 或输入契约无效,或 payload 超出限制 |
245
+ | `app-unavailable` | 本地目录中没有目标 App |
246
+ | `app-limit` | 本地宿主已达到嵌套层数上限 |
247
+ | `unsupported-operation` | 宿主没有提供 `apps.launch` handler |
248
+ | `invalid-host-result` | 宿主返回的结果不符合契约 |
249
+ | `operation-failed` | 宿主处理失败;不会向 App 暴露内部异常文本 |
250
+ | `timeout` | 拉起请求超过默认一小时;自定义 channel 可通过 `createAppsClientExtension(..., { launchTimeoutMs })` 调整 |
251
+ | `disposed` | 调用前 capability 已释放,或等待期间被释放 |
252
+
253
+ 只有 `result.status === 'completed'` 才读取 `result.output`。`cancelled` 是正常结束分支;上述错误会拒绝 Promise,需要用 `try/catch` 处理。
package/README.md CHANGED
@@ -1,26 +1,29 @@
1
- # dokiworlds-app-sdk
2
-
3
- An App embedded in DokiWorlds can request that its host launch another App. This first release exposes only `apps.launch`; the host controls catalog lookup, permission checks, presentation, and the launched App's lifecycle.
4
-
5
- ```js
6
- import { createAppClient } from "dokiworlds-app-sdk";
7
-
8
- const client = createAppClient({ appId: "my-app", targetOrigin: "https://host.example" });
9
- client.connect();
10
-
11
- const result = await client.apps.launch({
12
- appId: "other-app",
13
- input: { contract: "doki.example.input", version: 1, data: { level: 1 } },
14
- });
15
-
16
- if (result.status === "completed") console.log(result.output);
17
- client.dispose();
18
- ```
19
-
20
- `launch` resolves to `{ status: "completed", output }` or `{ status: "cancelled" }`. A completed output has a versioned `{ contract, version, data }` envelope. Invalid requests, host failures, disposal, and the default one-hour timeout reject the promise with an `AppsCapabilityError` (`code` describes the failure). You can set `launchTimeoutMs` when attaching the capability to a custom channel via `createAppsClientExtension`.
21
-
22
- The package uses the `dokiworld.app` protocol v2 handshake and `dokiworld-app-apps-request`/`dokiworld-app-apps-response` session messages from the original `@dokiworld/app-sdk`. A host with an established session channel can register `createAppsHostExtension(host, { launch })`; that session must allow the `apps` module. Installing this package alone does not add an App catalog or launch UI to the DokiWorlds host.
23
-
24
- ## Local development in this repository
25
-
26
- Place an App at `frontend/public/apps/<app-id>/index.html`, then open a game in a development build and use the **APPS** button. IDs use lowercase letters, digits, dots, and hyphens. An optional `manifest.json` can provide `entry` (a relative HTML path), `locales.en.name`, and `runtime.input` (`contract` and `version`); otherwise `index.html`, the folder name, and the `doki.dev.launch` v1 input contract are used. Local Apps run with the host origin so module scripts and local assets load normally; only put trusted development Apps in this directory. A nested `apps.launch` may target another App in the same local catalog; its completion output is returned to the caller, while closing the child returns `{ status: "cancelled" }`.
1
+ # dokiworlds-app-sdk
2
+
3
+ 中文完整使用说明见 [GUIDE.md](./GUIDE.md)。
4
+
5
+ Version 0.2.0 adds `whenReady()`, the `input` getter, and `requestExit()` to the v2 client. An embedded App can read its versioned input, return a completion, and request another App when the host grants that capability. The host controls catalog lookup, permissions, presentation, and lifecycle. See GUIDE.md for the check-reveal slot contract and local package installation.
6
+
7
+ ```js
8
+ import { createAppClient } from "dokiworlds-app-sdk";
9
+
10
+ const client = createAppClient({ appId: "my-app", targetOrigin: "https://host.example" });
11
+ client.connect();
12
+ const input = await client.whenReady();
13
+
14
+ const result = await client.apps.launch({
15
+ appId: "other-app",
16
+ input: { contract: "doki.example.input", version: 1, data: { level: 1 } },
17
+ });
18
+
19
+ if (result.status === "completed") console.log(result.output);
20
+ client.dispose();
21
+ ```
22
+
23
+ `launch` resolves to `{ status: "completed", output }` or `{ status: "cancelled" }`. A completed output has a versioned `{ contract, version, data }` envelope. Invalid requests, host failures, disposal, and the default one-hour timeout reject the promise with an `AppsCapabilityError` (`code` describes the failure). You can set `launchTimeoutMs` when attaching the capability to a custom channel via `createAppsClientExtension`.
24
+
25
+ The package uses the `dokiworld.app` protocol v2 handshake and `dokiworld-app-apps-request`/`dokiworld-app-apps-response` session messages from the original `@dokiworld/app-sdk`. A host with an established session channel can register `createAppsHostExtension(host, { launch })`; that session must allow the `apps` module. Installing this package alone does not add an App catalog or launch UI to the DokiWorlds host.
26
+
27
+ ## Local development in this repository
28
+
29
+ Place an App at `frontend/public/apps/<app-id>/index.html`, then open a game in a development build and use the **APPS** button. IDs use lowercase letters, digits, dots, and hyphens. An optional `manifest.json` can provide `entry` (a relative HTML path), `locales.en.name`, and `runtime.input` (`contract` and `version`); otherwise `index.html`, the folder name, and the `doki.dev.launch` v1 input contract are used. Local Apps run with the host origin so module scripts and local assets load normally; only put trusted development Apps in this directory. A nested `apps.launch` may target another App in the same local catalog; its completion output is returned to the caller, while closing the child returns `{ status: "cancelled" }`.
package/package.json CHANGED
@@ -1,20 +1,20 @@
1
- {
2
- "name": "dokiworlds-app-sdk",
3
- "version": "0.1.0",
4
- "type": "module",
5
- "exports": {
6
- ".": {
7
- "types": "./src/index.d.ts",
8
- "default": "./src/index.js"
9
- }
10
- },
11
- "files": ["src", "README.md"],
12
- "scripts": {
13
- "test": "node --test tests/*.test.mjs",
14
- "typecheck": "tsc --noEmit -p tsconfig.json",
15
- "prepublishOnly": "npm test && npm run typecheck"
16
- },
17
- "devDependencies": {
18
- "typescript": "^5.9.3"
19
- }
20
- }
1
+ {
2
+ "name": "dokiworlds-app-sdk",
3
+ "version": "0.2.0",
4
+ "type": "module",
5
+ "exports": {
6
+ ".": {
7
+ "types": "./src/index.d.ts",
8
+ "default": "./src/index.js"
9
+ }
10
+ },
11
+ "files": ["src", "README.md", "GUIDE.md"],
12
+ "scripts": {
13
+ "test": "node --test tests/*.test.mjs",
14
+ "typecheck": "tsc --noEmit -p tsconfig.json",
15
+ "prepublishOnly": "npm test && npm run typecheck"
16
+ },
17
+ "devDependencies": {
18
+ "typescript": "^5.9.3"
19
+ }
20
+ }
package/src/index.d.ts CHANGED
@@ -1,82 +1,86 @@
1
- export declare const APP_PROTOCOL: "dokiworld.app";
2
- export declare const APP_PROTOCOL_VERSION: 2;
3
- export declare const DEFAULT_APP_LAUNCH_TIMEOUT_MS: number;
4
-
5
- export interface AppContract<Data = unknown> {
6
- contract: string;
7
- version: number;
8
- data: Data;
9
- }
10
- export interface AppLaunchRequest<Input = unknown> {
11
- appId: string;
12
- input: AppContract<Input>;
13
- }
14
- export type AppLaunchResult<Output = unknown> =
15
- | { status: "completed"; output: AppContract<Output> }
16
- | { status: "cancelled"; output?: never };
17
-
18
- export interface AppSessionMessage {
19
- type: string;
20
- protocol: typeof APP_PROTOCOL;
21
- protocolVersion: typeof APP_PROTOCOL_VERSION;
22
- appId: string;
23
- instanceId: string;
24
- runId: string;
25
- messageId: string;
26
- payload: Record<string, unknown>;
27
- }
28
- export interface AppSessionChannel {
29
- send(type: string, payload: Record<string, unknown>): unknown;
30
- onMessage(listener: (message: AppSessionMessage) => void | Promise<void>): () => void;
31
- }
32
- export declare class AppsCapabilityError extends Error {
33
- readonly code: string;
34
- }
35
- export declare class AppsCapabilityTimeoutError extends AppsCapabilityError {}
36
- export interface AppsClientExtension {
37
- launch<Input = unknown, Output = unknown>(input: AppLaunchRequest<Input>): Promise<AppLaunchResult<Output>>;
38
- dispose(): void;
39
- }
40
- export declare function createAppsClientExtension(
41
- client: AppSessionChannel,
42
- options?: { createId?: (kind: string) => string; launchTimeoutMs?: number },
43
- ): AppsClientExtension;
44
- export declare function createAppsHostExtension(
45
- host: AppSessionChannel,
46
- handlers?: { launch?: (input: AppLaunchRequest) => AppLaunchResult | Promise<AppLaunchResult> },
47
- ): { dispose(): void };
48
- export interface AppHost extends AppSessionChannel {
49
- connect(handlers?: {
50
- onComplete?: (output: AppContract) => { status: "accepted" | "rejected" } | Promise<{ status: "accepted" | "rejected" }>;
51
- onRequestExit?: () => void;
52
- }): () => void;
53
- dispose(): void;
54
- }
55
- export declare function createAppHost(options: {
56
- appId: string;
57
- runId: string;
58
- target: Window;
59
- input: AppContract;
60
- scope?: Window;
61
- expectedOrigin?: string;
62
- createId?: (kind: string) => string;
63
- }): AppHost;
64
-
65
- export interface AppClientOptions {
66
- appId: string;
67
- scope?: Window & { ReactNativeWebView?: { postMessage(message: string): void } };
68
- targetOrigin?: string;
69
- instanceId?: string;
70
- createId?: (kind: string) => string;
71
- readyRetryMs?: number;
72
- }
73
- export interface AppClient {
74
- readonly appId: string;
75
- readonly instanceId: string;
76
- readonly runId: string | null;
77
- readonly apps: AppsClientExtension;
78
- complete(output: AppContract): Promise<"accepted" | "rejected">;
79
- connect(): () => void;
80
- dispose(): void;
81
- }
82
- export declare function createAppClient(options: AppClientOptions): AppClient;
1
+ export declare const APP_PROTOCOL: "dokiworld.app";
2
+ export declare const APP_PROTOCOL_VERSION: 2;
3
+ export declare const DEFAULT_APP_LAUNCH_TIMEOUT_MS: number;
4
+
5
+ export interface AppContract<Data = unknown> {
6
+ contract: string;
7
+ version: number;
8
+ data: Data;
9
+ }
10
+ export interface AppLaunchRequest<Input = unknown> {
11
+ appId: string;
12
+ input: AppContract<Input>;
13
+ }
14
+ export type AppLaunchResult<Output = unknown> =
15
+ | { status: "completed"; output: AppContract<Output> }
16
+ | { status: "cancelled"; output?: never };
17
+
18
+ export interface AppSessionMessage {
19
+ type: string;
20
+ protocol: typeof APP_PROTOCOL;
21
+ protocolVersion: typeof APP_PROTOCOL_VERSION;
22
+ appId: string;
23
+ instanceId: string;
24
+ runId: string;
25
+ messageId: string;
26
+ payload: Record<string, unknown>;
27
+ }
28
+ export interface AppSessionChannel {
29
+ send(type: string, payload: Record<string, unknown>): unknown;
30
+ onMessage(listener: (message: AppSessionMessage) => void | Promise<void>): () => void;
31
+ }
32
+ export declare class AppsCapabilityError extends Error {
33
+ readonly code: string;
34
+ }
35
+ export declare class AppsCapabilityTimeoutError extends AppsCapabilityError {}
36
+ export interface AppsClientExtension {
37
+ launch<Input = unknown, Output = unknown>(input: AppLaunchRequest<Input>): Promise<AppLaunchResult<Output>>;
38
+ dispose(): void;
39
+ }
40
+ export declare function createAppsClientExtension(
41
+ client: AppSessionChannel,
42
+ options?: { createId?: (kind: string) => string; launchTimeoutMs?: number },
43
+ ): AppsClientExtension;
44
+ export declare function createAppsHostExtension(
45
+ host: AppSessionChannel,
46
+ handlers?: { launch?: (input: AppLaunchRequest) => AppLaunchResult | Promise<AppLaunchResult> },
47
+ ): { dispose(): void };
48
+ export interface AppHost extends AppSessionChannel {
49
+ connect(handlers?: {
50
+ onComplete?: (output: AppContract) => { status: "accepted" | "rejected" } | Promise<{ status: "accepted" | "rejected" }>;
51
+ onRequestExit?: () => void;
52
+ }): () => void;
53
+ dispose(): void;
54
+ }
55
+ export declare function createAppHost(options: {
56
+ appId: string;
57
+ runId: string;
58
+ target: Window;
59
+ input: AppContract;
60
+ scope?: Window;
61
+ expectedOrigin?: string;
62
+ createId?: (kind: string) => string;
63
+ }): AppHost;
64
+
65
+ export interface AppClientOptions {
66
+ appId: string;
67
+ scope?: Window & { ReactNativeWebView?: { postMessage(message: string): void } };
68
+ targetOrigin?: string;
69
+ instanceId?: string;
70
+ createId?: (kind: string) => string;
71
+ readyRetryMs?: number;
72
+ }
73
+ export interface AppClient {
74
+ readonly appId: string;
75
+ readonly instanceId: string;
76
+ readonly runId: string | null;
77
+ /** Validated initialization input; each read is a detached copy. */
78
+ readonly input: AppContract | null;
79
+ readonly apps: AppsClientExtension;
80
+ whenReady(options?: { timeoutMs?: number }): Promise<AppContract>;
81
+ requestExit(): void;
82
+ complete(output: AppContract): Promise<"accepted" | "rejected">;
83
+ connect(): () => void;
84
+ dispose(): void;
85
+ }
86
+ export declare function createAppClient(options: AppClientOptions): AppClient;
package/src/index.js CHANGED
@@ -1,285 +1,310 @@
1
- export const APP_PROTOCOL = "dokiworld.app";
2
- export const APP_PROTOCOL_VERSION = 2;
3
- export const DEFAULT_APP_LAUNCH_TIMEOUT_MS = 60 * 60 * 1_000;
4
-
5
- const MAX_ID_LENGTH = 200;
6
- const MAX_PAYLOAD_BYTES = 64 * 1024;
7
- const MAX_PAYLOAD_DEPTH = 12;
8
- const MAX_PAYLOAD_NODES = 2_000;
9
- const isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
10
- const isId = (value) => typeof value === "string" && value.length > 0 && value.length <= MAX_ID_LENGTH;
11
- const defaultId = (kind) => `${kind}-${globalThis.crypto?.randomUUID?.() ?? `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}`;
12
-
13
- function isBoundedValue(value) {
14
- let encoded;
15
- try { encoded = JSON.stringify(value); } catch { return false; }
16
- if (encoded === undefined || new TextEncoder().encode(encoded).byteLength > MAX_PAYLOAD_BYTES) return false;
17
- let nodes = 0;
18
- const visit = (item, depth) => {
19
- if (++nodes > MAX_PAYLOAD_NODES || depth > MAX_PAYLOAD_DEPTH) return false;
20
- if (item === null || typeof item === "string" || typeof item === "boolean") return true;
21
- if (typeof item === "number") return Number.isFinite(item);
22
- if (Array.isArray(item)) return item.every((child) => visit(child, depth + 1));
23
- return isRecord(item) && Object.entries(item).every(([key, child]) => key.length <= MAX_ID_LENGTH && visit(child, depth + 1));
24
- };
25
- return visit(value, 0);
26
- }
27
-
28
- const isContract = (value) => isRecord(value) && isId(value.contract)
29
- && Number.isInteger(value.version) && value.version > 0
30
- && Object.hasOwn(value, "data") && isBoundedValue(value.data);
31
- const isLaunchResult = (value) => isRecord(value) && (
32
- (value.status === "completed" && isContract(value.output))
33
- || (value.status === "cancelled" && value.output === undefined)
34
- );
35
-
36
- export class AppsCapabilityError extends Error {
37
- constructor(code, message) {
38
- super(message);
39
- this.name = "AppsCapabilityError";
40
- this.code = code;
41
- }
42
- }
43
-
44
- export class AppsCapabilityTimeoutError extends AppsCapabilityError {
45
- constructor() {
46
- super("timeout", "DokiWorlds apps.launch timed out");
47
- this.name = "AppsCapabilityTimeoutError";
48
- }
49
- }
50
-
51
- /** Attach the apps.launch capability to an established app session channel. */
52
- export function createAppsClientExtension(client, { createId = defaultId, launchTimeoutMs = DEFAULT_APP_LAUNCH_TIMEOUT_MS } = {}) {
53
- if (typeof client?.send !== "function" || typeof client?.onMessage !== "function") throw new Error("Invalid app session channel");
54
- if (!Number.isFinite(launchTimeoutMs) || launchTimeoutMs <= 0) throw new Error("Invalid App launch timeout");
55
- const pending = new Map();
56
- let disposed = false;
57
- const finish = (requestId, outcome) => {
58
- const request = pending.get(requestId);
59
- if (!request) return;
60
- clearTimeout(request.timer);
61
- pending.delete(requestId);
62
- outcome instanceof Error ? request.reject(outcome) : request.resolve(outcome);
63
- };
64
- const unsubscribe = client.onMessage((message) => {
65
- if (!isRecord(message) || message.type !== "dokiworld-app-apps-response" || !isRecord(message.payload)) return;
66
- const { requestId, operation, status, result, error } = message.payload;
67
- if (!isId(requestId) || !pending.has(requestId) || operation !== "launch") return;
68
- if (status === "fulfilled") {
69
- if (isBoundedValue(result) && isLaunchResult(result)) finish(requestId, result);
70
- else finish(requestId, new AppsCapabilityError("invalid-host-result", "DokiWorlds returned an invalid apps.launch result"));
71
- } else if (status === "rejected" && isRecord(error) && isId(error.code) && typeof error.message === "string") {
72
- finish(requestId, new AppsCapabilityError(error.code, error.message));
73
- }
74
- });
75
- return Object.freeze({
76
- launch(input) {
77
- if (disposed) return Promise.reject(new AppsCapabilityError("disposed", "The apps capability was disposed"));
78
- if (!isRecord(input) || !isId(input.appId) || !isContract(input.input) || !isBoundedValue(input)) {
79
- return Promise.reject(new AppsCapabilityError("invalid-request", "Invalid apps.launch request"));
80
- }
81
- const requestId = createId("apps-request");
82
- if (!isId(requestId) || pending.has(requestId)) {
83
- return Promise.reject(new AppsCapabilityError("invalid-request-id", "Invalid or duplicate request id"));
84
- }
85
- return new Promise((resolve, reject) => {
86
- const timer = setTimeout(() => finish(requestId, new AppsCapabilityTimeoutError()), launchTimeoutMs);
87
- pending.set(requestId, { resolve, reject, timer });
88
- try { client.send("dokiworld-app-apps-request", { requestId, operation: "launch", input }); }
89
- catch (error) { finish(requestId, error instanceof Error ? error : new Error(String(error))); }
90
- });
91
- },
92
- dispose() {
93
- if (disposed) return;
94
- disposed = true;
95
- unsubscribe();
96
- for (const requestId of pending.keys()) finish(requestId, new AppsCapabilityError("disposed", "The apps capability was disposed"));
97
- },
98
- });
99
- }
100
-
101
- /** Host adapter: the host decides which App may launch and handles its lifecycle. */
102
- export function createAppsHostExtension(host, { launch } = {}) {
103
- if (typeof host?.send !== "function" || typeof host?.onMessage !== "function") throw new Error("Invalid app host channel");
104
- let disposed = false;
105
- const inFlight = new Map();
106
- const unsubscribe = host.onMessage(async (message) => {
107
- if (disposed || !isRecord(message) || message.type !== "dokiworld-app-apps-request" || !isRecord(message.payload)) return;
108
- const { requestId, operation, input } = message.payload;
109
- if (!isId(requestId) || operation !== "launch" || !isRecord(input) || !isId(input.appId) || !isContract(input.input) || !isBoundedValue(input)) return;
110
- let outcome = inFlight.get(requestId);
111
- if (!outcome) {
112
- outcome = Promise.resolve().then(async () => {
113
- if (typeof launch !== "function") return { status: "rejected", error: { code: "unsupported-operation", message: "DokiWorlds does not provide apps.launch" } };
114
- try {
115
- const result = await launch(input);
116
- return isBoundedValue(result) && isLaunchResult(result)
117
- ? { status: "fulfilled", result }
118
- : { status: "rejected", error: { code: "invalid-host-result", message: "DokiWorlds returned an invalid apps.launch result" } };
119
- } catch (error) {
120
- return { status: "rejected", error: { code: isRecord(error) && isId(error.code) ? error.code : "operation-failed", message: "DokiWorlds could not complete apps.launch" } };
121
- }
122
- });
123
- inFlight.set(requestId, outcome);
124
- }
125
- host.send("dokiworld-app-apps-response", { requestId, operation, ...await outcome });
126
- });
127
- return Object.freeze({ dispose() { if (!disposed) { disposed = true; unsubscribe(); inFlight.clear(); } } });
128
- }
129
-
130
- /** Host side of the minimal v2 lifecycle used by locally embedded Apps. */
131
- export function createAppHost({ appId, runId, target, input, scope = globalThis.window, expectedOrigin = "null", createId = defaultId } = {}) {
132
- if (!isId(appId) || !isId(runId) || !target?.postMessage || !scope?.addEventListener || !scope?.removeEventListener || !isContract(input)) {
133
- throw new Error("Invalid app host configuration");
134
- }
135
- if (expectedOrigin !== "null") {
136
- let parsed;
137
- try { parsed = new URL(expectedOrigin); } catch { throw new Error("Invalid app host origin"); }
138
- if ((parsed.protocol !== "http:" && parsed.protocol !== "https:") || parsed.origin !== expectedOrigin) throw new Error("Invalid app host origin");
139
- }
140
- let instanceId = null;
141
- let disposed = false;
142
- let connected = false;
143
- const listeners = new Set();
144
- const send = (type, payload) => {
145
- if (!instanceId) throw new Error("The app has not sent ready");
146
- const messageId = createId("message");
147
- if (!isId(messageId)) throw new Error("Invalid app message id");
148
- target.postMessage({ type, protocol: APP_PROTOCOL, protocolVersion: APP_PROTOCOL_VERSION, appId, instanceId, runId, messageId, payload }, expectedOrigin === "null" ? "*" : expectedOrigin);
149
- };
150
- const onMessage = (listener) => { listeners.add(listener); return () => listeners.delete(listener); };
151
- const handleMessage = async (event) => {
152
- if (disposed || !connected || event.source !== target || event.origin !== expectedOrigin || !isRecord(event.data)) return;
153
- const message = event.data;
154
- if (message.protocol !== APP_PROTOCOL || message.protocolVersion !== APP_PROTOCOL_VERSION || message.appId !== appId || !isId(message.instanceId)) return;
155
- if (message.type === "dokiworld-app-ready") {
156
- if (instanceId !== message.instanceId) instanceId = message.instanceId;
157
- send("dokiworld-app-init", { locale: "en", grantedScopes: [], context: {}, input });
158
- return;
159
- }
160
- if (message.instanceId !== instanceId || message.runId !== runId || !isId(message.messageId) || !isRecord(message.payload)) return;
161
- if (message.type === "dokiworld-app-complete") {
162
- const { resultId, output } = message.payload;
163
- if (!isId(resultId) || !isContract(output)) return;
164
- let decision = { status: "accepted" };
165
- try { decision = await handlers.onComplete?.(output) ?? decision; }
166
- catch { decision = { status: "rejected" }; }
167
- send("dokiworld-app-complete-ack", { resultId, status: decision.status === "accepted" ? "accepted" : "rejected" });
168
- return;
169
- }
170
- if (message.type === "dokiworld-app-request-exit") {
171
- handlers.onRequestExit?.();
172
- return;
173
- }
174
- for (const listener of listeners) listener(message);
175
- };
176
- let handlers = {};
177
- scope.addEventListener("message", handleMessage);
178
- const dispose = () => {
179
- if (disposed) return;
180
- disposed = true;
181
- scope.removeEventListener("message", handleMessage);
182
- listeners.clear();
183
- };
184
- return Object.freeze({
185
- send, onMessage,
186
- connect(nextHandlers = {}) {
187
- if (disposed || connected) throw new Error("The app host is disposed or already connected");
188
- connected = true;
189
- handlers = nextHandlers;
190
- return dispose;
191
- },
192
- dispose,
193
- });
194
- }
195
-
196
- /** Minimal protocol-v2 client for an App embedded in a DokiWorlds host. */
197
- export function createAppClient({ appId, scope = globalThis.window, targetOrigin = "*", instanceId = defaultId("instance"), createId = defaultId, readyRetryMs = 500 } = {}) {
198
- if (!isId(appId) || !isId(instanceId) || !scope?.parent?.postMessage || !scope?.addEventListener || !scope?.removeEventListener) throw new Error("Invalid app client identity or window");
199
- if (!Number.isFinite(readyRetryMs) || readyRetryMs <= 0) throw new Error("Invalid App ready retry interval");
200
- let runId = null;
201
- let connected = false;
202
- let disposed = false;
203
- let readyTimer = null;
204
- const listeners = new Set();
205
- const acknowledgements = new Map();
206
- const sendReady = () => {
207
- const message = { type: "dokiworld-app-ready", protocol: APP_PROTOCOL, protocolVersion: APP_PROTOCOL_VERSION, appId, instanceId };
208
- if (scope.ReactNativeWebView?.postMessage) scope.ReactNativeWebView.postMessage(JSON.stringify(message));
209
- else scope.parent.postMessage(message, targetOrigin);
210
- };
211
- const send = (type, payload) => {
212
- if (disposed) throw new Error("The app client was disposed");
213
- if (!runId) throw new Error("The app has not received init");
214
- const messageId = createId("message");
215
- if (!isId(messageId)) throw new Error("Invalid app message id");
216
- const message = { type, protocol: APP_PROTOCOL, protocolVersion: APP_PROTOCOL_VERSION, appId, instanceId, runId, messageId, payload };
217
- if (scope.ReactNativeWebView?.postMessage) scope.ReactNativeWebView.postMessage(JSON.stringify(message));
218
- else scope.parent.postMessage(message, targetOrigin);
219
- return message;
220
- };
221
- const onMessage = (listener) => { listeners.add(listener); return () => listeners.delete(listener); };
222
- const apps = createAppsClientExtension({ send, onMessage }, { createId });
223
- const handleMessage = (event) => {
224
- if (disposed || !connected || event.source !== scope.parent || !isRecord(event.data)) return;
225
- if (targetOrigin !== "*" && event.origin !== targetOrigin) return;
226
- const message = event.data;
227
- if (message.protocol !== APP_PROTOCOL || message.protocolVersion !== APP_PROTOCOL_VERSION || message.appId !== appId || message.instanceId !== instanceId) return;
228
- if (message.type === "dokiworld-app-init" && isId(message.runId) && isId(message.messageId)) {
229
- if (runId && runId !== message.runId) return;
230
- runId = message.runId;
231
- if (readyTimer !== null) { clearInterval(readyTimer); readyTimer = null; }
232
- send("dokiworld-app-initialized", {});
233
- return;
234
- }
235
- if (runId && message.runId === runId && isId(message.messageId) && isRecord(message.payload)) {
236
- if (message.type === "dokiworld-app-complete-ack") {
237
- const pending = isId(message.payload.resultId)
238
- && (message.payload.status === "accepted" || message.payload.status === "rejected")
239
- ? acknowledgements.get(message.payload.resultId)
240
- : null;
241
- if (pending) {
242
- clearTimeout(pending.timer);
243
- acknowledgements.delete(message.payload.resultId);
244
- pending.resolve(message.payload.status);
245
- }
246
- return;
247
- }
248
- for (const listener of listeners) listener(message);
249
- }
250
- };
251
- scope.addEventListener("message", handleMessage);
252
- const dispose = () => {
253
- if (disposed) return;
254
- disposed = true;
255
- scope.removeEventListener("message", handleMessage);
256
- if (readyTimer !== null) clearInterval(readyTimer);
257
- apps.dispose();
258
- for (const pending of acknowledgements.values()) { clearTimeout(pending.timer); pending.reject(new Error("The app client was disposed")); }
259
- acknowledgements.clear();
260
- listeners.clear();
261
- };
262
- return Object.freeze({
263
- appId, instanceId, get runId() { return runId; }, apps,
264
- complete(output) {
265
- if (disposed) return Promise.reject(new Error("The app client was disposed"));
266
- if (!isContract(output)) return Promise.reject(new Error("Invalid app output"));
267
- const resultId = createId("result");
268
- if (!isId(resultId) || acknowledgements.has(resultId)) return Promise.reject(new Error("Invalid or duplicate app result id"));
269
- return new Promise((resolve, reject) => {
270
- const timer = setTimeout(() => { acknowledgements.delete(resultId); reject(new Error("App completion acknowledgement timed out")); }, 3_000);
271
- acknowledgements.set(resultId, { resolve, reject, timer });
272
- try { send("dokiworld-app-complete", { resultId, output }); }
273
- catch (error) { clearTimeout(timer); acknowledgements.delete(resultId); reject(error); }
274
- });
275
- },
276
- connect() {
277
- if (disposed || connected) throw new Error("The app client is disposed or already connected");
278
- connected = true;
279
- sendReady();
280
- readyTimer = setInterval(() => { if (!runId) sendReady(); }, readyRetryMs);
281
- return dispose;
282
- },
283
- dispose,
284
- });
285
- }
1
+ export const APP_PROTOCOL = "dokiworld.app";
2
+ export const APP_PROTOCOL_VERSION = 2;
3
+ export const DEFAULT_APP_LAUNCH_TIMEOUT_MS = 60 * 60 * 1_000;
4
+
5
+ const MAX_ID_LENGTH = 200;
6
+ const MAX_PAYLOAD_BYTES = 64 * 1024;
7
+ const MAX_PAYLOAD_DEPTH = 12;
8
+ const MAX_PAYLOAD_NODES = 2_000;
9
+ const isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
10
+ const isId = (value) => typeof value === "string" && value.length > 0 && value.length <= MAX_ID_LENGTH;
11
+ const defaultId = (kind) => `${kind}-${globalThis.crypto?.randomUUID?.() ?? `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}`;
12
+
13
+ function isBoundedValue(value) {
14
+ let encoded;
15
+ try { encoded = JSON.stringify(value); } catch { return false; }
16
+ if (encoded === undefined || new TextEncoder().encode(encoded).byteLength > MAX_PAYLOAD_BYTES) return false;
17
+ let nodes = 0;
18
+ const visit = (item, depth) => {
19
+ if (++nodes > MAX_PAYLOAD_NODES || depth > MAX_PAYLOAD_DEPTH) return false;
20
+ if (item === null || typeof item === "string" || typeof item === "boolean") return true;
21
+ if (typeof item === "number") return Number.isFinite(item);
22
+ if (Array.isArray(item)) return item.every((child) => visit(child, depth + 1));
23
+ return isRecord(item) && Object.entries(item).every(([key, child]) => key.length <= MAX_ID_LENGTH && visit(child, depth + 1));
24
+ };
25
+ return visit(value, 0);
26
+ }
27
+
28
+ const isContract = (value) => isRecord(value) && isId(value.contract)
29
+ && Number.isInteger(value.version) && value.version > 0
30
+ && Object.hasOwn(value, "data") && isBoundedValue(value.data);
31
+ const isLaunchResult = (value) => isRecord(value) && (
32
+ (value.status === "completed" && isContract(value.output))
33
+ || (value.status === "cancelled" && value.output === undefined)
34
+ );
35
+
36
+ export class AppsCapabilityError extends Error {
37
+ constructor(code, message) {
38
+ super(message);
39
+ this.name = "AppsCapabilityError";
40
+ this.code = code;
41
+ }
42
+ }
43
+
44
+ export class AppsCapabilityTimeoutError extends AppsCapabilityError {
45
+ constructor() {
46
+ super("timeout", "DokiWorlds apps.launch timed out");
47
+ this.name = "AppsCapabilityTimeoutError";
48
+ }
49
+ }
50
+
51
+ /** Attach the apps.launch capability to an established app session channel. */
52
+ export function createAppsClientExtension(client, { createId = defaultId, launchTimeoutMs = DEFAULT_APP_LAUNCH_TIMEOUT_MS } = {}) {
53
+ if (typeof client?.send !== "function" || typeof client?.onMessage !== "function") throw new Error("Invalid app session channel");
54
+ if (!Number.isFinite(launchTimeoutMs) || launchTimeoutMs <= 0) throw new Error("Invalid App launch timeout");
55
+ const pending = new Map();
56
+ let disposed = false;
57
+ const finish = (requestId, outcome) => {
58
+ const request = pending.get(requestId);
59
+ if (!request) return;
60
+ clearTimeout(request.timer);
61
+ pending.delete(requestId);
62
+ outcome instanceof Error ? request.reject(outcome) : request.resolve(outcome);
63
+ };
64
+ const unsubscribe = client.onMessage((message) => {
65
+ if (!isRecord(message) || message.type !== "dokiworld-app-apps-response" || !isRecord(message.payload)) return;
66
+ const { requestId, operation, status, result, error } = message.payload;
67
+ if (!isId(requestId) || !pending.has(requestId) || operation !== "launch") return;
68
+ if (status === "fulfilled") {
69
+ if (isBoundedValue(result) && isLaunchResult(result)) finish(requestId, result);
70
+ else finish(requestId, new AppsCapabilityError("invalid-host-result", "DokiWorlds returned an invalid apps.launch result"));
71
+ } else if (status === "rejected" && isRecord(error) && isId(error.code) && typeof error.message === "string") {
72
+ finish(requestId, new AppsCapabilityError(error.code, error.message));
73
+ }
74
+ });
75
+ return Object.freeze({
76
+ launch(input) {
77
+ if (disposed) return Promise.reject(new AppsCapabilityError("disposed", "The apps capability was disposed"));
78
+ if (!isRecord(input) || !isId(input.appId) || !isContract(input.input) || !isBoundedValue(input)) {
79
+ return Promise.reject(new AppsCapabilityError("invalid-request", "Invalid apps.launch request"));
80
+ }
81
+ const requestId = createId("apps-request");
82
+ if (!isId(requestId) || pending.has(requestId)) {
83
+ return Promise.reject(new AppsCapabilityError("invalid-request-id", "Invalid or duplicate request id"));
84
+ }
85
+ return new Promise((resolve, reject) => {
86
+ const timer = setTimeout(() => finish(requestId, new AppsCapabilityTimeoutError()), launchTimeoutMs);
87
+ pending.set(requestId, { resolve, reject, timer });
88
+ try { client.send("dokiworld-app-apps-request", { requestId, operation: "launch", input }); }
89
+ catch (error) { finish(requestId, error instanceof Error ? error : new Error(String(error))); }
90
+ });
91
+ },
92
+ dispose() {
93
+ if (disposed) return;
94
+ disposed = true;
95
+ unsubscribe();
96
+ for (const requestId of pending.keys()) finish(requestId, new AppsCapabilityError("disposed", "The apps capability was disposed"));
97
+ },
98
+ });
99
+ }
100
+
101
+ /** Host adapter: the host decides which App may launch and handles its lifecycle. */
102
+ export function createAppsHostExtension(host, { launch } = {}) {
103
+ if (typeof host?.send !== "function" || typeof host?.onMessage !== "function") throw new Error("Invalid app host channel");
104
+ let disposed = false;
105
+ const inFlight = new Map();
106
+ const unsubscribe = host.onMessage(async (message) => {
107
+ if (disposed || !isRecord(message) || message.type !== "dokiworld-app-apps-request" || !isRecord(message.payload)) return;
108
+ const { requestId, operation, input } = message.payload;
109
+ if (!isId(requestId) || operation !== "launch" || !isRecord(input) || !isId(input.appId) || !isContract(input.input) || !isBoundedValue(input)) return;
110
+ let outcome = inFlight.get(requestId);
111
+ if (!outcome) {
112
+ outcome = Promise.resolve().then(async () => {
113
+ if (typeof launch !== "function") return { status: "rejected", error: { code: "unsupported-operation", message: "DokiWorlds does not provide apps.launch" } };
114
+ try {
115
+ const result = await launch(input);
116
+ return isBoundedValue(result) && isLaunchResult(result)
117
+ ? { status: "fulfilled", result }
118
+ : { status: "rejected", error: { code: "invalid-host-result", message: "DokiWorlds returned an invalid apps.launch result" } };
119
+ } catch (error) {
120
+ return { status: "rejected", error: { code: isRecord(error) && isId(error.code) ? error.code : "operation-failed", message: "DokiWorlds could not complete apps.launch" } };
121
+ }
122
+ });
123
+ inFlight.set(requestId, outcome);
124
+ }
125
+ host.send("dokiworld-app-apps-response", { requestId, operation, ...await outcome });
126
+ });
127
+ return Object.freeze({ dispose() { if (!disposed) { disposed = true; unsubscribe(); inFlight.clear(); } } });
128
+ }
129
+
130
+ /** Host side of the minimal v2 lifecycle used by locally embedded Apps. */
131
+ export function createAppHost({ appId, runId, target, input, scope = globalThis.window, expectedOrigin = "null", createId = defaultId } = {}) {
132
+ if (!isId(appId) || !isId(runId) || !target?.postMessage || !scope?.addEventListener || !scope?.removeEventListener || !isContract(input)) {
133
+ throw new Error("Invalid app host configuration");
134
+ }
135
+ if (expectedOrigin !== "null") {
136
+ let parsed;
137
+ try { parsed = new URL(expectedOrigin); } catch { throw new Error("Invalid app host origin"); }
138
+ if ((parsed.protocol !== "http:" && parsed.protocol !== "https:") || parsed.origin !== expectedOrigin) throw new Error("Invalid app host origin");
139
+ }
140
+ let instanceId = null;
141
+ let disposed = false;
142
+ let connected = false;
143
+ const listeners = new Set();
144
+ const send = (type, payload) => {
145
+ if (!instanceId) throw new Error("The app has not sent ready");
146
+ const messageId = createId("message");
147
+ if (!isId(messageId)) throw new Error("Invalid app message id");
148
+ target.postMessage({ type, protocol: APP_PROTOCOL, protocolVersion: APP_PROTOCOL_VERSION, appId, instanceId, runId, messageId, payload }, expectedOrigin === "null" ? "*" : expectedOrigin);
149
+ };
150
+ const onMessage = (listener) => { listeners.add(listener); return () => listeners.delete(listener); };
151
+ const handleMessage = async (event) => {
152
+ if (disposed || !connected || event.source !== target || event.origin !== expectedOrigin || !isRecord(event.data)) return;
153
+ const message = event.data;
154
+ if (message.protocol !== APP_PROTOCOL || message.protocolVersion !== APP_PROTOCOL_VERSION || message.appId !== appId || !isId(message.instanceId)) return;
155
+ if (message.type === "dokiworld-app-ready") {
156
+ if (instanceId !== message.instanceId) instanceId = message.instanceId;
157
+ send("dokiworld-app-init", { locale: "en", grantedScopes: [], context: {}, input });
158
+ return;
159
+ }
160
+ if (message.instanceId !== instanceId || message.runId !== runId || !isId(message.messageId) || !isRecord(message.payload)) return;
161
+ if (message.type === "dokiworld-app-complete") {
162
+ const { resultId, output } = message.payload;
163
+ if (!isId(resultId) || !isContract(output)) return;
164
+ let decision = { status: "accepted" };
165
+ try { decision = await handlers.onComplete?.(output) ?? decision; }
166
+ catch { decision = { status: "rejected" }; }
167
+ send("dokiworld-app-complete-ack", { resultId, status: decision.status === "accepted" ? "accepted" : "rejected" });
168
+ return;
169
+ }
170
+ if (message.type === "dokiworld-app-request-exit") {
171
+ handlers.onRequestExit?.();
172
+ return;
173
+ }
174
+ for (const listener of listeners) listener(message);
175
+ };
176
+ let handlers = {};
177
+ scope.addEventListener("message", handleMessage);
178
+ const dispose = () => {
179
+ if (disposed) return;
180
+ disposed = true;
181
+ scope.removeEventListener("message", handleMessage);
182
+ listeners.clear();
183
+ };
184
+ return Object.freeze({
185
+ send, onMessage,
186
+ connect(nextHandlers = {}) {
187
+ if (disposed || connected) throw new Error("The app host is disposed or already connected");
188
+ connected = true;
189
+ handlers = nextHandlers;
190
+ return dispose;
191
+ },
192
+ dispose,
193
+ });
194
+ }
195
+
196
+ /** Minimal protocol-v2 client for an App embedded in a DokiWorlds host. */
197
+ export function createAppClient({ appId, scope = globalThis.window, targetOrigin = "*", instanceId = defaultId("instance"), createId = defaultId, readyRetryMs = 500 } = {}) {
198
+ if (!isId(appId) || !isId(instanceId) || !scope?.parent?.postMessage || !scope?.addEventListener || !scope?.removeEventListener) throw new Error("Invalid app client identity or window");
199
+ if (!Number.isFinite(readyRetryMs) || readyRetryMs <= 0) throw new Error("Invalid App ready retry interval");
200
+ let runId = null;
201
+ let input = null;
202
+ const initializationWaiters = new Set();
203
+ let connected = false;
204
+ let disposed = false;
205
+ let readyTimer = null;
206
+ const listeners = new Set();
207
+ const acknowledgements = new Map();
208
+ const sendReady = () => {
209
+ const message = { type: "dokiworld-app-ready", protocol: APP_PROTOCOL, protocolVersion: APP_PROTOCOL_VERSION, appId, instanceId };
210
+ if (scope.ReactNativeWebView?.postMessage) scope.ReactNativeWebView.postMessage(JSON.stringify(message));
211
+ else scope.parent.postMessage(message, targetOrigin);
212
+ };
213
+ const send = (type, payload) => {
214
+ if (disposed) throw new Error("The app client was disposed");
215
+ if (!runId) throw new Error("The app has not received init");
216
+ const messageId = createId("message");
217
+ if (!isId(messageId)) throw new Error("Invalid app message id");
218
+ const message = { type, protocol: APP_PROTOCOL, protocolVersion: APP_PROTOCOL_VERSION, appId, instanceId, runId, messageId, payload };
219
+ if (scope.ReactNativeWebView?.postMessage) scope.ReactNativeWebView.postMessage(JSON.stringify(message));
220
+ else scope.parent.postMessage(message, targetOrigin);
221
+ return message;
222
+ };
223
+ const onMessage = (listener) => { listeners.add(listener); return () => listeners.delete(listener); };
224
+ const apps = createAppsClientExtension({ send, onMessage }, { createId });
225
+ const handleMessage = (event) => {
226
+ if (disposed || !connected || event.source !== scope.parent || !isRecord(event.data)) return;
227
+ if (targetOrigin !== "*" && event.origin !== targetOrigin) return;
228
+ const message = event.data;
229
+ if (message.protocol !== APP_PROTOCOL || message.protocolVersion !== APP_PROTOCOL_VERSION || message.appId !== appId || message.instanceId !== instanceId) return;
230
+ if (message.type === "dokiworld-app-init" && isId(message.runId) && isId(message.messageId)) {
231
+ if (!isRecord(message.payload) || !isContract(message.payload.input)) return;
232
+ if (runId) {
233
+ if (runId === message.runId) send("dokiworld-app-initialized", {});
234
+ return;
235
+ }
236
+ runId = message.runId;
237
+ input = structuredClone(message.payload.input);
238
+ if (readyTimer !== null) { clearInterval(readyTimer); readyTimer = null; }
239
+ send("dokiworld-app-initialized", {});
240
+ for (const pending of initializationWaiters) {
241
+ clearTimeout(pending.timer);
242
+ pending.resolve(structuredClone(input));
243
+ }
244
+ initializationWaiters.clear();
245
+ return;
246
+ }
247
+ if (runId && message.runId === runId && isId(message.messageId) && isRecord(message.payload)) {
248
+ if (message.type === "dokiworld-app-complete-ack") {
249
+ const pending = isId(message.payload.resultId)
250
+ && (message.payload.status === "accepted" || message.payload.status === "rejected")
251
+ ? acknowledgements.get(message.payload.resultId)
252
+ : null;
253
+ if (pending) {
254
+ clearTimeout(pending.timer);
255
+ acknowledgements.delete(message.payload.resultId);
256
+ pending.resolve(message.payload.status);
257
+ }
258
+ return;
259
+ }
260
+ for (const listener of listeners) listener(message);
261
+ }
262
+ };
263
+ scope.addEventListener("message", handleMessage);
264
+ const dispose = () => {
265
+ if (disposed) return;
266
+ disposed = true;
267
+ scope.removeEventListener("message", handleMessage);
268
+ if (readyTimer !== null) clearInterval(readyTimer);
269
+ apps.dispose();
270
+ for (const pending of initializationWaiters) { clearTimeout(pending.timer); pending.reject(new Error("The app client was disposed")); }
271
+ initializationWaiters.clear();
272
+ for (const pending of acknowledgements.values()) { clearTimeout(pending.timer); pending.reject(new Error("The app client was disposed")); }
273
+ acknowledgements.clear();
274
+ listeners.clear();
275
+ };
276
+ return Object.freeze({
277
+ appId, instanceId, get runId() { return runId; }, get input() { return input === null ? null : structuredClone(input); }, apps,
278
+ whenReady({ timeoutMs = 10_000 } = {}) {
279
+ if (disposed) return Promise.reject(new Error("The app client was disposed"));
280
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) return Promise.reject(new Error("Invalid initialization timeout"));
281
+ if (input !== null) return Promise.resolve(structuredClone(input));
282
+ return new Promise((resolve, reject) => {
283
+ const pending = { resolve, reject, timer: null };
284
+ pending.timer = setTimeout(() => { initializationWaiters.delete(pending); reject(new Error("App initialization timed out")); }, timeoutMs);
285
+ initializationWaiters.add(pending);
286
+ });
287
+ },
288
+ requestExit() { send("dokiworld-app-request-exit", {}); },
289
+ complete(output) {
290
+ if (disposed) return Promise.reject(new Error("The app client was disposed"));
291
+ if (!isContract(output)) return Promise.reject(new Error("Invalid app output"));
292
+ const resultId = createId("result");
293
+ if (!isId(resultId) || acknowledgements.has(resultId)) return Promise.reject(new Error("Invalid or duplicate app result id"));
294
+ return new Promise((resolve, reject) => {
295
+ const timer = setTimeout(() => { acknowledgements.delete(resultId); reject(new Error("App completion acknowledgement timed out")); }, 3_000);
296
+ acknowledgements.set(resultId, { resolve, reject, timer });
297
+ try { send("dokiworld-app-complete", { resultId, output }); }
298
+ catch (error) { clearTimeout(timer); acknowledgements.delete(resultId); reject(error); }
299
+ });
300
+ },
301
+ connect() {
302
+ if (disposed || connected) throw new Error("The app client is disposed or already connected");
303
+ connected = true;
304
+ sendReady();
305
+ readyTimer = setInterval(() => { if (!runId) sendReady(); }, readyRetryMs);
306
+ return dispose;
307
+ },
308
+ dispose,
309
+ });
310
+ }