@karpoland/sdk 0.0.0-stage → 1.0.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/LICENSE +202 -0
- package/README.ja.md +542 -0
- package/README.md +541 -2
- package/README.zh-CN.md +542 -0
- package/dist/app-B7n0h9Pk.d.cts +450 -0
- package/dist/app-DLU_Aj53.d.ts +450 -0
- package/dist/chunk-EZJ5H5WT.js +87 -0
- package/dist/chunk-EZJ5H5WT.js.map +1 -0
- package/dist/chunk-TRJPD7KM.js +378 -0
- package/dist/chunk-TRJPD7KM.js.map +1 -0
- package/dist/cli.js +875 -0
- package/dist/index.cjs +1448 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +562 -0
- package/dist/index.d.ts +562 -0
- package/dist/index.js +1004 -0
- package/dist/index.js.map +1 -0
- package/dist/page.cjs +311 -0
- package/dist/page.cjs.map +1 -0
- package/dist/page.d.cts +116 -0
- package/dist/page.d.ts +116 -0
- package/dist/page.global.js +1 -0
- package/dist/page.js +135 -0
- package/dist/page.js.map +1 -0
- package/dist/testing.cjs +238 -0
- package/dist/testing.cjs.map +1 -0
- package/dist/testing.d.cts +123 -0
- package/dist/testing.d.ts +123 -0
- package/dist/testing.js +146 -0
- package/dist/testing.js.map +1 -0
- package/dist/types-VExoR9cc.d.cts +1189 -0
- package/dist/types-VExoR9cc.d.ts +1189 -0
- package/package.json +70 -4
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import { App } from './index.js';
|
|
2
|
+
import { Id, InstallRef, SessionRef, Resident, FetchLike, Json } from './index.js';
|
|
3
|
+
|
|
4
|
+
interface SimulateOptions {
|
|
5
|
+
/** The app's signing secret: deliveries are signed with it. */
|
|
6
|
+
signingSecret: string;
|
|
7
|
+
/** The app's slug in deliveries; default "test-app". */
|
|
8
|
+
app?: string;
|
|
9
|
+
/** The service's basePath (AppOptions.basePath): deliveries are posted under it. */
|
|
10
|
+
basePath?: string;
|
|
11
|
+
/** The install deliveries carry unless an option says otherwise; null for none. Default {id: "500", room_id: "900", version: "1.0.0"}. */
|
|
12
|
+
install?: InstallRef | null;
|
|
13
|
+
/** The caller of call() when none is given. Default {id: "1001", name: "Tester", kind: "person"}. */
|
|
14
|
+
caller?: Resident;
|
|
15
|
+
/** The MP-Karpo-Timestamp clock in Unix seconds; default now. */
|
|
16
|
+
now?: () => number;
|
|
17
|
+
}
|
|
18
|
+
/** The service's answer to a delivery: the HTTP status and the JSON body (null when empty). */
|
|
19
|
+
interface Answer<B = any> {
|
|
20
|
+
status: number;
|
|
21
|
+
body: B;
|
|
22
|
+
}
|
|
23
|
+
interface CallOptions {
|
|
24
|
+
/** The call id; default a new one. Reuse one to replay a call. */
|
|
25
|
+
id?: Id;
|
|
26
|
+
install?: InstallRef | null;
|
|
27
|
+
session?: SessionRef | null;
|
|
28
|
+
idempotencyKey?: string;
|
|
29
|
+
/** The caller's first call to the app. */
|
|
30
|
+
firstSeen?: boolean;
|
|
31
|
+
/** Set when a declarative hook (call) runs the tool: its event. */
|
|
32
|
+
event?: string;
|
|
33
|
+
commandMessageId?: Id;
|
|
34
|
+
}
|
|
35
|
+
interface EventOptions {
|
|
36
|
+
/** The delivery id; default a new one. Reuse one to redeliver. */
|
|
37
|
+
id?: Id;
|
|
38
|
+
install?: InstallRef | null;
|
|
39
|
+
sessionId?: Id;
|
|
40
|
+
/** The resident the hook may act for. */
|
|
41
|
+
residentId?: Id;
|
|
42
|
+
/** Default 1. */
|
|
43
|
+
attempt?: number;
|
|
44
|
+
}
|
|
45
|
+
/** A join request gate delivery: the join request. */
|
|
46
|
+
interface GateInput {
|
|
47
|
+
applicant: Resident;
|
|
48
|
+
/** Default the install's room. */
|
|
49
|
+
room_id?: Id;
|
|
50
|
+
/** Default a new id. */
|
|
51
|
+
join_request_id?: Id;
|
|
52
|
+
note?: string;
|
|
53
|
+
/** The delivery id; default a new one. */
|
|
54
|
+
id?: Id;
|
|
55
|
+
install?: InstallRef | null;
|
|
56
|
+
}
|
|
57
|
+
/** A publish handshake. */
|
|
58
|
+
interface HandshakeInput {
|
|
59
|
+
/** Default "1.0.0". */
|
|
60
|
+
version?: string;
|
|
61
|
+
/** Default a new one. */
|
|
62
|
+
challenge?: string;
|
|
63
|
+
tools?: string[];
|
|
64
|
+
hooks?: string[];
|
|
65
|
+
}
|
|
66
|
+
interface Simulator {
|
|
67
|
+
/** Call a tool as caller (default the simulator's caller; null: a declarative hook's call in the app's own context). */
|
|
68
|
+
call<B = any>(tool: string, args?: Record<string, Json | undefined>, caller?: Resident | null, opts?: CallOptions): Promise<Answer<B>>;
|
|
69
|
+
/** Deliver a hook event. */
|
|
70
|
+
event<B = any>(name: string, data: Record<string, unknown>, opts?: EventOptions): Promise<Answer<B>>;
|
|
71
|
+
/** Ask the join request gate: 200 {decision, reason?}, or 204 without a decision. */
|
|
72
|
+
gate<B = any>(input: GateInput): Promise<Answer<B>>;
|
|
73
|
+
/**
|
|
74
|
+
* The publish handshake: 200 {challenge}; with tools and hooks (the
|
|
75
|
+
* manifest's, as the platform sends them) 422 app.HANDSHAKE_FAILED when a
|
|
76
|
+
* handler is missing.
|
|
77
|
+
*/
|
|
78
|
+
handshake<B = any>(input?: HandshakeInput): Promise<Answer<B>>;
|
|
79
|
+
/** Wait for work the handlers left running (ctx.defer, ctx.waitUntil). */
|
|
80
|
+
idle(): Promise<void>;
|
|
81
|
+
}
|
|
82
|
+
/** simulate drives app with signed deliveries, as the platform sends them. */
|
|
83
|
+
declare function simulate(app: App, opts: SimulateOptions): Simulator;
|
|
84
|
+
/** A request the app sent the platform. */
|
|
85
|
+
interface RecordedRequest {
|
|
86
|
+
method: string;
|
|
87
|
+
/** The URL path, e.g. /v1/app-service/sessions. */
|
|
88
|
+
path: string;
|
|
89
|
+
query: Record<string, string>;
|
|
90
|
+
/** Lower-case names. */
|
|
91
|
+
headers: Record<string, string>;
|
|
92
|
+
/** The JSON body, the raw bytes of another body, or undefined. */
|
|
93
|
+
body: any;
|
|
94
|
+
}
|
|
95
|
+
/** A scripted answer; default status 200 and body {}. */
|
|
96
|
+
interface MockAnswer {
|
|
97
|
+
status?: number;
|
|
98
|
+
body?: unknown;
|
|
99
|
+
headers?: Record<string, string>;
|
|
100
|
+
}
|
|
101
|
+
interface PlatformMock {
|
|
102
|
+
/** The platform origin to give createApp / createClient (platform). */
|
|
103
|
+
readonly url: string;
|
|
104
|
+
/** The fetch to give createApp / createClient (fetch): every request lands here. */
|
|
105
|
+
fetch: FetchLike;
|
|
106
|
+
/** Every request so far, oldest first (a copy). */
|
|
107
|
+
requests(): RecordedRequest[];
|
|
108
|
+
/**
|
|
109
|
+
* Answer method (or "*") on path with answer from now on; the latest
|
|
110
|
+
* matching rule wins. path is the full path (/v1/apps/dice) or an
|
|
111
|
+
* app-service route (/sessions/*), "*" matching one segment.
|
|
112
|
+
*/
|
|
113
|
+
respond(method: string, path: string, answer: MockAnswer | ((req: RecordedRequest) => MockAnswer | undefined)): PlatformMock;
|
|
114
|
+
/** The latest request. */
|
|
115
|
+
last(): RecordedRequest | undefined;
|
|
116
|
+
/** Forget the requests and the scripted answers. */
|
|
117
|
+
reset(): void;
|
|
118
|
+
}
|
|
119
|
+
/** mockPlatform stands in for the platform API: it records requests and answers as scripted. */
|
|
120
|
+
declare function mockPlatform(): PlatformMock;
|
|
121
|
+
|
|
122
|
+
export { mockPlatform, simulate };
|
|
123
|
+
export type { Answer, CallOptions, EventOptions, GateInput, HandshakeInput, MockAnswer, PlatformMock, RecordedRequest, SimulateOptions, Simulator };
|
package/dist/testing.js
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import {
|
|
2
|
+
signedHeaders
|
|
3
|
+
} from "./chunk-EZJ5H5WT.js";
|
|
4
|
+
|
|
5
|
+
// src/testing.ts
|
|
6
|
+
var DEFAULT_INSTALL = { id: "500", room_id: "900", version: "1.0.0" };
|
|
7
|
+
var DEFAULT_CALLER = { id: "1001", name: "Tester", kind: "person" };
|
|
8
|
+
function simulate(app, opts) {
|
|
9
|
+
if (!opts?.signingSecret) throw new TypeError("simulate: signingSecret is required");
|
|
10
|
+
const slug = opts.app ?? "test-app";
|
|
11
|
+
const base = (opts.basePath ?? "").replace(/\/+$/, "");
|
|
12
|
+
const install = (o) => o.install !== void 0 ? o.install : opts.install !== void 0 ? opts.install : DEFAULT_INSTALL;
|
|
13
|
+
let seq = 0;
|
|
14
|
+
const nextId = () => String(2e6 + ++seq);
|
|
15
|
+
const pending = [];
|
|
16
|
+
async function deliver(path, msg, ids) {
|
|
17
|
+
const body = new TextEncoder().encode(JSON.stringify(msg));
|
|
18
|
+
const full = base + path;
|
|
19
|
+
const ts = opts.now ? opts.now() : Math.floor(Date.now() / 1e3);
|
|
20
|
+
const headers = new Headers(await signedHeaders(opts.signingSecret, body, { path: full, ts, ...ids }));
|
|
21
|
+
const out = await app.handle({ method: "POST", path: full, headers, body }, (p) => void pending.push(p));
|
|
22
|
+
return { status: out.status, body: out.body ? JSON.parse(out.body) : null };
|
|
23
|
+
}
|
|
24
|
+
const strip = (o) => {
|
|
25
|
+
for (const k of Object.keys(o)) if (o[k] === void 0) delete o[k];
|
|
26
|
+
return o;
|
|
27
|
+
};
|
|
28
|
+
return {
|
|
29
|
+
call(tool, args = {}, caller, o = {}) {
|
|
30
|
+
const id = o.id ?? nextId();
|
|
31
|
+
const call = strip({ id, tool, args, idempotency_key: o.idempotencyKey, first_seen: o.firstSeen });
|
|
32
|
+
const msg = strip({
|
|
33
|
+
type: "karpo.call",
|
|
34
|
+
app: slug,
|
|
35
|
+
call,
|
|
36
|
+
caller: caller === void 0 ? opts.caller ?? DEFAULT_CALLER : caller,
|
|
37
|
+
install: install(o) ?? void 0,
|
|
38
|
+
session: o.session ?? void 0,
|
|
39
|
+
event: o.event,
|
|
40
|
+
command_message_id: o.commandMessageId
|
|
41
|
+
});
|
|
42
|
+
return deliver(`/tools/${encodeURIComponent(tool)}`, msg, { callId: id });
|
|
43
|
+
},
|
|
44
|
+
event(name, data, o = {}) {
|
|
45
|
+
const id = o.id ?? nextId();
|
|
46
|
+
const msg = strip({
|
|
47
|
+
type: "karpo.event",
|
|
48
|
+
event: name,
|
|
49
|
+
delivery_id: id,
|
|
50
|
+
app: slug,
|
|
51
|
+
attempt: o.attempt ?? 1,
|
|
52
|
+
data,
|
|
53
|
+
install: install(o) ?? void 0,
|
|
54
|
+
session_id: o.sessionId,
|
|
55
|
+
resident_id: o.residentId
|
|
56
|
+
});
|
|
57
|
+
return deliver(`/hooks/${encodeURIComponent(name)}`, msg, { deliveryId: id });
|
|
58
|
+
},
|
|
59
|
+
gate(input) {
|
|
60
|
+
const id = input.id ?? nextId();
|
|
61
|
+
const inst = install(input);
|
|
62
|
+
const data = {
|
|
63
|
+
join_request_id: input.join_request_id ?? nextId(),
|
|
64
|
+
room_id: input.room_id ?? inst?.room_id ?? "",
|
|
65
|
+
applicant: input.applicant,
|
|
66
|
+
note: input.note ?? ""
|
|
67
|
+
};
|
|
68
|
+
const msg = strip({
|
|
69
|
+
type: "karpo.event",
|
|
70
|
+
event: "member.join",
|
|
71
|
+
delivery_id: id,
|
|
72
|
+
app: slug,
|
|
73
|
+
attempt: 1,
|
|
74
|
+
data,
|
|
75
|
+
install: inst ?? void 0,
|
|
76
|
+
resident_id: input.applicant.id,
|
|
77
|
+
gate: true
|
|
78
|
+
});
|
|
79
|
+
return deliver("/hooks/member.join", msg, { deliveryId: id });
|
|
80
|
+
},
|
|
81
|
+
handshake(input = {}) {
|
|
82
|
+
const msg = strip({
|
|
83
|
+
type: "karpo.handshake",
|
|
84
|
+
app: slug,
|
|
85
|
+
version: input.version ?? "1.0.0",
|
|
86
|
+
challenge: input.challenge ?? `ch-${nextId()}`,
|
|
87
|
+
tools: input.tools,
|
|
88
|
+
hooks: input.hooks
|
|
89
|
+
});
|
|
90
|
+
return deliver("/.karpo/handshake", msg, {});
|
|
91
|
+
},
|
|
92
|
+
async idle() {
|
|
93
|
+
while (pending.length) await Promise.allSettled(pending.splice(0));
|
|
94
|
+
}
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
var APP_SERVICE = "/v1/app-service";
|
|
98
|
+
function mockPlatform() {
|
|
99
|
+
const url = "https://platform.test";
|
|
100
|
+
const requests = [];
|
|
101
|
+
let rules = [];
|
|
102
|
+
const pattern = (p) => new RegExp("^" + p.split("/").map((seg) => seg === "*" ? "[^/]+" : seg.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("/") + "$");
|
|
103
|
+
const mock = {
|
|
104
|
+
url,
|
|
105
|
+
requests: () => [...requests],
|
|
106
|
+
async fetch(input, init = {}) {
|
|
107
|
+
const u = new URL(String(input));
|
|
108
|
+
const headers = {};
|
|
109
|
+
new Headers(init.headers).forEach((v, k) => headers[k] = v);
|
|
110
|
+
let body = void 0;
|
|
111
|
+
if (init.body !== void 0 && init.body !== null) {
|
|
112
|
+
const raw = typeof init.body === "string" ? init.body : new Uint8Array(await new Response(init.body).arrayBuffer());
|
|
113
|
+
if (typeof raw === "string" && (headers["content-type"] ?? "").includes("json")) body = JSON.parse(raw);
|
|
114
|
+
else body = typeof raw === "string" ? new TextEncoder().encode(raw) : raw;
|
|
115
|
+
}
|
|
116
|
+
const rec = { method: (init.method ?? "GET").toUpperCase(), path: u.pathname, query: Object.fromEntries(u.searchParams), headers, body };
|
|
117
|
+
requests.push(rec);
|
|
118
|
+
const short = rec.path.startsWith(APP_SERVICE + "/") ? rec.path.slice(APP_SERVICE.length) : null;
|
|
119
|
+
let out;
|
|
120
|
+
for (let i = rules.length - 1; i >= 0 && !out; i--) {
|
|
121
|
+
const r = rules[i];
|
|
122
|
+
if (r.method !== "*" && r.method !== rec.method) continue;
|
|
123
|
+
if (!r.re.test(rec.path) && !(short !== null && r.re.test(short))) continue;
|
|
124
|
+
out = typeof r.answer === "function" ? r.answer(rec) : r.answer;
|
|
125
|
+
}
|
|
126
|
+
const status = out?.status ?? 200;
|
|
127
|
+
const text = out?.body === void 0 ? "{}" : JSON.stringify(out.body);
|
|
128
|
+
return new Response(status === 204 ? null : text, { status, headers: { "Content-Type": "application/json", ...out?.headers } });
|
|
129
|
+
},
|
|
130
|
+
respond(method, path, answer) {
|
|
131
|
+
rules.push({ method: method.toUpperCase(), re: pattern(path), answer });
|
|
132
|
+
return mock;
|
|
133
|
+
},
|
|
134
|
+
last: () => requests[requests.length - 1],
|
|
135
|
+
reset() {
|
|
136
|
+
requests.length = 0;
|
|
137
|
+
rules = [];
|
|
138
|
+
}
|
|
139
|
+
};
|
|
140
|
+
return mock;
|
|
141
|
+
}
|
|
142
|
+
export {
|
|
143
|
+
mockPlatform,
|
|
144
|
+
simulate
|
|
145
|
+
};
|
|
146
|
+
//# sourceMappingURL=testing.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/testing.ts"],"sourcesContent":["// @karpoland/sdk/testing: test an app's service without the platform.\n//\n// import { createApp } from \"@karpoland/sdk\";\n// import { mockPlatform, simulate } from \"@karpoland/sdk/testing\";\n//\n// const platform = mockPlatform();\n// // what GET /v1/app-service/signing answers the app's key with\n// platform.respond(\"GET\", \"/signing\", { body: { signing_secret: \"s\", domain_token: \"t\" } });\n// const app = createApp({ appKey: \"kap_test\", platform: platform.url, fetch: platform.fetch });\n// app.tool(\"roll\", (ctx) => ({ result: { n: 4 }, text: `${ctx.caller?.name} 掷出了 4` }));\n// const sim = simulate(app, { signingSecret: \"s\" });\n// await sim.call(\"roll\", { sides: 6 }); // {status: 200, body: {result: {n: 4}, text: \"…\"}}\n// platform.requests; // what the app sent the platform\n//\n// simulate builds deliveries the way the platform does (body, ids,\n// MP-Karpo-Timestamp and MP-Karpo-Signature-V1) and runs them through\n// app.handle; mockPlatform is a fetch that records the app's requests and\n// answers them as the test scripts. Browser safe.\n\nimport type { App } from \"./app.js\";\nimport type { FetchLike } from \"./http.js\";\nimport { signedHeaders } from \"./signing.js\";\nimport type { HookEvents, Id, InstallRef, Json, Resident, SessionRef } from \"./types.js\";\n\n// ----------------------------------------------------------------- simulate\n\nexport interface SimulateOptions {\n /** The app's signing secret: deliveries are signed with it. */\n signingSecret: string;\n /** The app's slug in deliveries; default \"test-app\". */\n app?: string;\n /** The service's basePath (AppOptions.basePath): deliveries are posted under it. */\n basePath?: string;\n /** The install deliveries carry unless an option says otherwise; null for none. Default {id: \"500\", room_id: \"900\", version: \"1.0.0\"}. */\n install?: InstallRef | null;\n /** The caller of call() when none is given. Default {id: \"1001\", name: \"Tester\", kind: \"person\"}. */\n caller?: Resident;\n /** The MP-Karpo-Timestamp clock in Unix seconds; default now. */\n now?: () => number;\n}\n\n/** The service's answer to a delivery: the HTTP status and the JSON body (null when empty). */\nexport interface Answer<B = any> {\n status: number;\n body: B;\n}\n\nexport interface CallOptions {\n /** The call id; default a new one. Reuse one to replay a call. */\n id?: Id;\n install?: InstallRef | null;\n session?: SessionRef | null;\n idempotencyKey?: string;\n /** The caller's first call to the app. */\n firstSeen?: boolean;\n /** Set when a declarative hook (call) runs the tool: its event. */\n event?: string;\n commandMessageId?: Id;\n}\n\nexport interface EventOptions {\n /** The delivery id; default a new one. Reuse one to redeliver. */\n id?: Id;\n install?: InstallRef | null;\n sessionId?: Id;\n /** The resident the hook may act for. */\n residentId?: Id;\n /** Default 1. */\n attempt?: number;\n}\n\n/** A join request gate delivery: the join request. */\nexport interface GateInput {\n applicant: Resident;\n /** Default the install's room. */\n room_id?: Id;\n /** Default a new id. */\n join_request_id?: Id;\n note?: string;\n /** The delivery id; default a new one. */\n id?: Id;\n install?: InstallRef | null;\n}\n\n/** A publish handshake. */\nexport interface HandshakeInput {\n /** Default \"1.0.0\". */\n version?: string;\n /** Default a new one. */\n challenge?: string;\n tools?: string[];\n hooks?: string[];\n}\n\nexport interface Simulator {\n /** Call a tool as caller (default the simulator's caller; null: a declarative hook's call in the app's own context). */\n call<B = any>(tool: string, args?: Record<string, Json | undefined>, caller?: Resident | null, opts?: CallOptions): Promise<Answer<B>>;\n /** Deliver a hook event. */\n event<B = any>(name: string, data: Record<string, unknown>, opts?: EventOptions): Promise<Answer<B>>;\n /** Ask the join request gate: 200 {decision, reason?}, or 204 without a decision. */\n gate<B = any>(input: GateInput): Promise<Answer<B>>;\n /**\n * The publish handshake: 200 {challenge}; with tools and hooks (the\n * manifest's, as the platform sends them) 422 app.HANDSHAKE_FAILED when a\n * handler is missing.\n */\n handshake<B = any>(input?: HandshakeInput): Promise<Answer<B>>;\n /** Wait for work the handlers left running (ctx.defer, ctx.waitUntil). */\n idle(): Promise<void>;\n}\n\nconst DEFAULT_INSTALL: InstallRef = { id: \"500\", room_id: \"900\", version: \"1.0.0\" };\nconst DEFAULT_CALLER: Resident = { id: \"1001\", name: \"Tester\", kind: \"person\" };\n\n/** simulate drives app with signed deliveries, as the platform sends them. */\nexport function simulate(app: App, opts: SimulateOptions): Simulator {\n if (!opts?.signingSecret) throw new TypeError(\"simulate: signingSecret is required\");\n const slug = opts.app ?? \"test-app\";\n const base = (opts.basePath ?? \"\").replace(/\\/+$/, \"\");\n const install = (o: { install?: InstallRef | null }) => (o.install !== undefined ? o.install : opts.install !== undefined ? opts.install : DEFAULT_INSTALL);\n let seq = 0;\n const nextId = () => String(2_000_000 + ++seq);\n const pending: Promise<unknown>[] = [];\n\n async function deliver(path: string, msg: Record<string, unknown>, ids: { callId?: string; deliveryId?: string }): Promise<Answer> {\n const body = new TextEncoder().encode(JSON.stringify(msg));\n const full = base + path;\n const ts = opts.now ? opts.now() : Math.floor(Date.now() / 1000);\n const headers = new Headers(await signedHeaders(opts.signingSecret, body, { path: full, ts, ...ids }));\n const out = await app.handle({ method: \"POST\", path: full, headers, body }, (p) => void pending.push(p));\n return { status: out.status, body: out.body ? JSON.parse(out.body) : null };\n }\n\n const strip = (o: Record<string, unknown>) => {\n for (const k of Object.keys(o)) if (o[k] === undefined) delete o[k];\n return o;\n };\n\n return {\n call(tool, args = {}, caller, o = {}) {\n const id = o.id ?? nextId();\n const call = strip({ id, tool, args, idempotency_key: o.idempotencyKey, first_seen: o.firstSeen });\n const msg = strip({\n type: \"karpo.call\",\n app: slug,\n call,\n caller: caller === undefined ? (opts.caller ?? DEFAULT_CALLER) : caller,\n install: install(o) ?? undefined,\n session: o.session ?? undefined,\n event: o.event,\n command_message_id: o.commandMessageId,\n });\n return deliver(`/tools/${encodeURIComponent(tool)}`, msg, { callId: id });\n },\n event(name, data, o = {}) {\n const id = o.id ?? nextId();\n const msg = strip({\n type: \"karpo.event\",\n event: name,\n delivery_id: id,\n app: slug,\n attempt: o.attempt ?? 1,\n data,\n install: install(o) ?? undefined,\n session_id: o.sessionId,\n resident_id: o.residentId,\n });\n return deliver(`/hooks/${encodeURIComponent(name)}`, msg, { deliveryId: id });\n },\n gate(input) {\n const id = input.id ?? nextId();\n const inst = install(input);\n const data: HookEvents[\"member.join\"] = {\n join_request_id: input.join_request_id ?? nextId(),\n room_id: input.room_id ?? inst?.room_id ?? \"\",\n applicant: input.applicant,\n note: input.note ?? \"\",\n };\n const msg = strip({\n type: \"karpo.event\",\n event: \"member.join\",\n delivery_id: id,\n app: slug,\n attempt: 1,\n data,\n install: inst ?? undefined,\n resident_id: input.applicant.id,\n gate: true,\n });\n return deliver(\"/hooks/member.join\", msg, { deliveryId: id });\n },\n handshake(input = {}) {\n const msg = strip({\n type: \"karpo.handshake\",\n app: slug,\n version: input.version ?? \"1.0.0\",\n challenge: input.challenge ?? `ch-${nextId()}`,\n tools: input.tools,\n hooks: input.hooks,\n });\n return deliver(\"/.karpo/handshake\", msg, {});\n },\n async idle() {\n while (pending.length) await Promise.allSettled(pending.splice(0));\n },\n };\n}\n\n// ------------------------------------------------------------- mockPlatform\n\n/** A request the app sent the platform. */\nexport interface RecordedRequest {\n method: string;\n /** The URL path, e.g. /v1/app-service/sessions. */\n path: string;\n query: Record<string, string>;\n /** Lower-case names. */\n headers: Record<string, string>;\n /** The JSON body, the raw bytes of another body, or undefined. */\n body: any;\n}\n\n/** A scripted answer; default status 200 and body {}. */\nexport interface MockAnswer {\n status?: number;\n body?: unknown;\n headers?: Record<string, string>;\n}\n\nexport interface PlatformMock {\n /** The platform origin to give createApp / createClient (platform). */\n readonly url: string;\n /** The fetch to give createApp / createClient (fetch): every request lands here. */\n fetch: FetchLike;\n /** Every request so far, oldest first (a copy). */\n requests(): RecordedRequest[];\n /**\n * Answer method (or \"*\") on path with answer from now on; the latest\n * matching rule wins. path is the full path (/v1/apps/dice) or an\n * app-service route (/sessions/*), \"*\" matching one segment.\n */\n respond(method: string, path: string, answer: MockAnswer | ((req: RecordedRequest) => MockAnswer | undefined)): PlatformMock;\n /** The latest request. */\n last(): RecordedRequest | undefined;\n /** Forget the requests and the scripted answers. */\n reset(): void;\n}\n\nconst APP_SERVICE = \"/v1/app-service\";\n\n/** mockPlatform stands in for the platform API: it records requests and answers as scripted. */\nexport function mockPlatform(): PlatformMock {\n const url = \"https://platform.test\";\n const requests: RecordedRequest[] = [];\n let rules: { method: string; re: RegExp; answer: MockAnswer | ((req: RecordedRequest) => MockAnswer | undefined) }[] = [];\n const pattern = (p: string) => new RegExp(\"^\" + p.split(\"/\").map((seg) => (seg === \"*\" ? \"[^/]+\" : seg.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\"))).join(\"/\") + \"$\");\n\n const mock: PlatformMock = {\n url,\n requests: () => [...requests],\n async fetch(input, init = {}) {\n const u = new URL(String(input));\n const headers: Record<string, string> = {};\n new Headers(init.headers as HeadersInit | undefined).forEach((v, k) => (headers[k] = v));\n let body: unknown = undefined;\n if (init.body !== undefined && init.body !== null) {\n const raw = typeof init.body === \"string\" ? init.body : new Uint8Array(await new Response(init.body as BodyInit).arrayBuffer());\n if (typeof raw === \"string\" && (headers[\"content-type\"] ?? \"\").includes(\"json\")) body = JSON.parse(raw);\n else body = typeof raw === \"string\" ? new TextEncoder().encode(raw) : raw;\n }\n const rec: RecordedRequest = { method: (init.method ?? \"GET\").toUpperCase(), path: u.pathname, query: Object.fromEntries(u.searchParams), headers, body };\n requests.push(rec);\n const short = rec.path.startsWith(APP_SERVICE + \"/\") ? rec.path.slice(APP_SERVICE.length) : null;\n let out: MockAnswer | undefined;\n for (let i = rules.length - 1; i >= 0 && !out; i--) {\n const r = rules[i]!;\n if (r.method !== \"*\" && r.method !== rec.method) continue;\n if (!r.re.test(rec.path) && !(short !== null && r.re.test(short))) continue;\n out = typeof r.answer === \"function\" ? r.answer(rec) : r.answer;\n }\n const status = out?.status ?? 200;\n const text = out?.body === undefined ? \"{}\" : JSON.stringify(out.body);\n return new Response(status === 204 ? null : text, { status, headers: { \"Content-Type\": \"application/json\", ...out?.headers } });\n },\n respond(method, path, answer) {\n rules.push({ method: method.toUpperCase(), re: pattern(path), answer });\n return mock;\n },\n last: () => requests[requests.length - 1],\n reset() {\n requests.length = 0;\n rules = [];\n },\n };\n return mock;\n}\n"],"mappings":";;;;;AA+GA,IAAM,kBAA8B,EAAE,IAAI,OAAO,SAAS,OAAO,SAAS,QAAQ;AAClF,IAAM,iBAA2B,EAAE,IAAI,QAAQ,MAAM,UAAU,MAAM,SAAS;AAGvE,SAAS,SAAS,KAAU,MAAkC;AACnE,MAAI,CAAC,MAAM,cAAe,OAAM,IAAI,UAAU,qCAAqC;AACnF,QAAM,OAAO,KAAK,OAAO;AACzB,QAAM,QAAQ,KAAK,YAAY,IAAI,QAAQ,QAAQ,EAAE;AACrD,QAAM,UAAU,CAAC,MAAwC,EAAE,YAAY,SAAY,EAAE,UAAU,KAAK,YAAY,SAAY,KAAK,UAAU;AAC3I,MAAI,MAAM;AACV,QAAM,SAAS,MAAM,OAAO,MAAY,EAAE,GAAG;AAC7C,QAAM,UAA8B,CAAC;AAErC,iBAAe,QAAQ,MAAc,KAA8B,KAAgE;AACjI,UAAM,OAAO,IAAI,YAAY,EAAE,OAAO,KAAK,UAAU,GAAG,CAAC;AACzD,UAAM,OAAO,OAAO;AACpB,UAAM,KAAK,KAAK,MAAM,KAAK,IAAI,IAAI,KAAK,MAAM,KAAK,IAAI,IAAI,GAAI;AAC/D,UAAM,UAAU,IAAI,QAAQ,MAAM,cAAc,KAAK,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