dokiworlds-app-sdk 0.1.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/README.md ADDED
@@ -0,0 +1,26 @@
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" }`.
package/package.json ADDED
@@ -0,0 +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
+ }
package/src/index.d.ts ADDED
@@ -0,0 +1,82 @@
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;
package/src/index.js ADDED
@@ -0,0 +1,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 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
+ }