@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
package/dist/page.cjs
ADDED
|
@@ -0,0 +1,311 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/page.ts
|
|
21
|
+
var page_exports = {};
|
|
22
|
+
__export(page_exports, {
|
|
23
|
+
PlatformError: () => PlatformError,
|
|
24
|
+
createPageClient: () => createPageClient
|
|
25
|
+
});
|
|
26
|
+
module.exports = __toCommonJS(page_exports);
|
|
27
|
+
|
|
28
|
+
// src/errors.ts
|
|
29
|
+
var STATUSES = {
|
|
30
|
+
OK: { http: 200, retryable: false, action: "" },
|
|
31
|
+
INVALID_ARGUMENT: { http: 400, retryable: false, action: "fix_request" },
|
|
32
|
+
UNAUTHENTICATED: { http: 401, retryable: false, action: "ask_owner" },
|
|
33
|
+
PERMISSION_DENIED: { http: 403, retryable: false, action: "give_up" },
|
|
34
|
+
NOT_FOUND: { http: 404, retryable: false, action: "give_up" },
|
|
35
|
+
ALREADY_EXISTS: { http: 409, retryable: false, action: "treat_as_done" },
|
|
36
|
+
ABORTED: { http: 409, retryable: true, action: "retry" },
|
|
37
|
+
FAILED_PRECONDITION: { http: 412, retryable: false, action: "give_up" },
|
|
38
|
+
RESOURCE_EXHAUSTED: { http: 429, retryable: false, action: "retry_later" },
|
|
39
|
+
DEADLINE_EXCEEDED: { http: 504, retryable: true, action: "retry_later" },
|
|
40
|
+
UNAVAILABLE: { http: 503, retryable: true, action: "wait" },
|
|
41
|
+
CANCELLED: { http: 499, retryable: false, action: "give_up" },
|
|
42
|
+
UNIMPLEMENTED: { http: 501, retryable: false, action: "give_up" },
|
|
43
|
+
INTERNAL: { http: 500, retryable: true, action: "retry_later" }
|
|
44
|
+
};
|
|
45
|
+
var PlatformError = class extends Error {
|
|
46
|
+
name = "PlatformError";
|
|
47
|
+
/** HTTP status of the answer (0 when the request never got one). */
|
|
48
|
+
httpStatus;
|
|
49
|
+
/** gRPC-style status, e.g. "FAILED_PRECONDITION". */
|
|
50
|
+
status;
|
|
51
|
+
/** Registered reason, e.g. "session.LIMIT_REACHED"; may be empty. */
|
|
52
|
+
reason;
|
|
53
|
+
action;
|
|
54
|
+
retryable;
|
|
55
|
+
/** How long to wait before retrying, from retry_after_ms or Retry-After. */
|
|
56
|
+
retryAfterMs;
|
|
57
|
+
detail;
|
|
58
|
+
appMessage;
|
|
59
|
+
/**
|
|
60
|
+
* The developer token's own error code on developer routes (401/403
|
|
61
|
+
* {error, code, hint}, e.g. token_expired); "" otherwise. Such an answer
|
|
62
|
+
* has no status: action is "" and you handle it by code.
|
|
63
|
+
*/
|
|
64
|
+
code;
|
|
65
|
+
/** The hint that comes with code; "" otherwise. */
|
|
66
|
+
hint;
|
|
67
|
+
/** The raw error body. */
|
|
68
|
+
body;
|
|
69
|
+
constructor(httpStatus, body = {}, retryAfterHeader) {
|
|
70
|
+
super(body.message || body.error || "");
|
|
71
|
+
this.httpStatus = httpStatus;
|
|
72
|
+
this.body = body;
|
|
73
|
+
this.status = body.status || statusOfHttp(httpStatus);
|
|
74
|
+
this.reason = body.reason || "";
|
|
75
|
+
this.code = typeof body.code === "string" ? body.code : "";
|
|
76
|
+
this.hint = typeof body.hint === "string" ? body.hint : "";
|
|
77
|
+
const tokenError = !body.status && !!this.code;
|
|
78
|
+
this.action = body.action || (tokenError ? "" : STATUSES[this.status]?.action || "");
|
|
79
|
+
this.retryable = body.retryable ?? STATUSES[this.status]?.retryable ?? false;
|
|
80
|
+
let after = typeof body.retry_after_ms === "number" && body.retry_after_ms > 0 ? body.retry_after_ms : void 0;
|
|
81
|
+
if (after === void 0 && retryAfterHeader) {
|
|
82
|
+
const s = Number(retryAfterHeader);
|
|
83
|
+
if (Number.isFinite(s)) after = s * 1e3;
|
|
84
|
+
else {
|
|
85
|
+
const t = Date.parse(retryAfterHeader);
|
|
86
|
+
if (!Number.isNaN(t)) after = Math.max(0, t - Date.now());
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
this.retryAfterMs = after;
|
|
90
|
+
this.detail = body.detail;
|
|
91
|
+
this.appMessage = body.app_message;
|
|
92
|
+
}
|
|
93
|
+
};
|
|
94
|
+
function statusOfHttp(http) {
|
|
95
|
+
for (const [k, v] of Object.entries(STATUSES)) if (v.http === http) return k;
|
|
96
|
+
if (http >= 500) return "INTERNAL";
|
|
97
|
+
if (http >= 400) return "FAILED_PRECONDITION";
|
|
98
|
+
return "OK";
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// src/http.ts
|
|
102
|
+
var ALREADY_DONE = /* @__PURE__ */ Symbol.for("karpoland.already_done");
|
|
103
|
+
var RETRY_ACTIONS = /* @__PURE__ */ new Set(["retry", "retry_later"]);
|
|
104
|
+
function shouldRetry(e) {
|
|
105
|
+
if (e.action === "give_up" || e.action === "fix_request") return false;
|
|
106
|
+
return RETRY_ACTIONS.has(e.action) || e.httpStatus === 429 || e.httpStatus === 503;
|
|
107
|
+
}
|
|
108
|
+
var sleep = (ms, signal) => new Promise((resolve, reject) => {
|
|
109
|
+
if (signal?.aborted) return reject(signal.reason);
|
|
110
|
+
const t = setTimeout(resolve, ms);
|
|
111
|
+
signal?.addEventListener("abort", () => (clearTimeout(t), reject(signal.reason)), { once: true });
|
|
112
|
+
});
|
|
113
|
+
function buildURL(base, path, query) {
|
|
114
|
+
const url = new URL(base.replace(/\/+$/, "") + path);
|
|
115
|
+
for (const [k, v] of Object.entries(query ?? {})) {
|
|
116
|
+
if (v === void 0 || v === null || v === "") continue;
|
|
117
|
+
url.searchParams.set(k, String(v));
|
|
118
|
+
}
|
|
119
|
+
return url.toString();
|
|
120
|
+
}
|
|
121
|
+
function createTransport(cfg) {
|
|
122
|
+
const doFetch = cfg.fetch ?? ((i, init) => globalThis.fetch(i, init));
|
|
123
|
+
return {
|
|
124
|
+
async request(method, path, opts = {}) {
|
|
125
|
+
const r = opts.retry === false || cfg.retry === false ? { retries: 0 } : { ...cfg.retry || {}, ...opts.retry || {} };
|
|
126
|
+
const retries = r.retries ?? 3;
|
|
127
|
+
const base = r.baseDelayMs ?? 200;
|
|
128
|
+
const maxDelay = r.maxDelayMs ?? 5e3;
|
|
129
|
+
const maxWait = r.maxWaitMs ?? 1e4;
|
|
130
|
+
const url = buildURL(cfg.base, path, opts.query);
|
|
131
|
+
const raw = opts.body instanceof Uint8Array || opts.body instanceof ArrayBuffer || typeof Blob !== "undefined" && opts.body instanceof Blob;
|
|
132
|
+
const idempotentMethod = opts.idempotent || method === "GET" || method === "PUT" || method === "DELETE";
|
|
133
|
+
let reauthed = false;
|
|
134
|
+
for (let attempt = 0; ; attempt++) {
|
|
135
|
+
const headers = { Accept: "application/json", ...cfg.userAgent ? { "User-Agent": cfg.userAgent } : {}, ...cfg.headers(), ...opts.headers };
|
|
136
|
+
if (opts.body !== void 0 && !raw && !headers["Content-Type"]) headers["Content-Type"] = "application/json";
|
|
137
|
+
let res;
|
|
138
|
+
try {
|
|
139
|
+
res = await doFetch(url, {
|
|
140
|
+
method,
|
|
141
|
+
headers,
|
|
142
|
+
body: opts.body === void 0 ? void 0 : raw ? opts.body : JSON.stringify(opts.body),
|
|
143
|
+
signal: opts.signal
|
|
144
|
+
});
|
|
145
|
+
} catch (err2) {
|
|
146
|
+
if (opts.signal?.aborted || !idempotentMethod || attempt >= retries) throw err2;
|
|
147
|
+
await sleep(backoff(attempt, base, maxDelay), opts.signal);
|
|
148
|
+
continue;
|
|
149
|
+
}
|
|
150
|
+
const text = await res.text();
|
|
151
|
+
let data = void 0;
|
|
152
|
+
if (text) {
|
|
153
|
+
try {
|
|
154
|
+
data = JSON.parse(text);
|
|
155
|
+
} catch {
|
|
156
|
+
data = res.ok ? text : { message: text };
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
if (res.ok) return data ?? {};
|
|
160
|
+
const err = new PlatformError(res.status, data ?? {}, res.headers.get("retry-after"));
|
|
161
|
+
if (attempt > 0 && opts.doneOnRetry && err.reason === opts.doneOnRetry) return ALREADY_DONE;
|
|
162
|
+
if (res.status === 401 && cfg.onUnauthorized && !reauthed) {
|
|
163
|
+
reauthed = true;
|
|
164
|
+
if (await cfg.onUnauthorized()) {
|
|
165
|
+
attempt--;
|
|
166
|
+
continue;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
if (attempt >= retries || !shouldRetry(err)) throw err;
|
|
170
|
+
const wait = err.retryAfterMs ?? backoff(attempt, base, maxDelay);
|
|
171
|
+
if (wait > maxWait) throw err;
|
|
172
|
+
await sleep(wait, opts.signal);
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
function backoff(attempt, base, max) {
|
|
178
|
+
const d = Math.min(max, base * 2 ** attempt);
|
|
179
|
+
return Math.round(d / 2 + Math.random() * (d / 2));
|
|
180
|
+
}
|
|
181
|
+
function randomKey(prefix = "") {
|
|
182
|
+
const c = globalThis.crypto;
|
|
183
|
+
if (c?.randomUUID) return prefix + c.randomUUID();
|
|
184
|
+
return prefix + Date.now().toString(36) + Math.random().toString(36).slice(2, 12);
|
|
185
|
+
}
|
|
186
|
+
var enc = (s) => encodeURIComponent(String(s));
|
|
187
|
+
|
|
188
|
+
// src/page.ts
|
|
189
|
+
var one = async (key, p) => (await p)?.[key];
|
|
190
|
+
function createPageClient(opts = {}) {
|
|
191
|
+
const win = opts.window ?? globalThis.window;
|
|
192
|
+
const before = opts.refreshBeforeMs ?? 3e4;
|
|
193
|
+
let launch = null;
|
|
194
|
+
let timer;
|
|
195
|
+
const listeners = { launch: /* @__PURE__ */ new Set(), refresh: /* @__PURE__ */ new Set(), error: /* @__PURE__ */ new Set(), "session.updated": /* @__PURE__ */ new Set(), "install.updated": /* @__PURE__ */ new Set() };
|
|
196
|
+
const emit = (ev, d) => listeners[ev].forEach((fn) => fn(d));
|
|
197
|
+
let readyWaiters = [];
|
|
198
|
+
let refreshWaiters = [];
|
|
199
|
+
const post = (type) => win?.parent?.postMessage({ type }, "*");
|
|
200
|
+
const schedule = () => {
|
|
201
|
+
if (timer) clearTimeout(timer);
|
|
202
|
+
if (!launch) return;
|
|
203
|
+
const ms = new Date(launch.expires_at).getTime() - Date.now() - before;
|
|
204
|
+
timer = setTimeout(() => void client.refresh().catch((e) => emit("error", e)), Math.max(1e3, ms));
|
|
205
|
+
timer.unref?.();
|
|
206
|
+
};
|
|
207
|
+
const accept = (l) => {
|
|
208
|
+
const first = !launch;
|
|
209
|
+
launch = l;
|
|
210
|
+
schedule();
|
|
211
|
+
emit(first ? "launch" : "refresh", l);
|
|
212
|
+
readyWaiters.forEach((r) => r(l));
|
|
213
|
+
readyWaiters = [];
|
|
214
|
+
refreshWaiters.forEach((w) => w.resolve(l));
|
|
215
|
+
refreshWaiters = [];
|
|
216
|
+
};
|
|
217
|
+
const onMessage = (e) => {
|
|
218
|
+
if (!win || e.source !== win.parent) return;
|
|
219
|
+
const ev = e.data;
|
|
220
|
+
if (ev?.type === "karpo:event" && (ev.event === "session.updated" || ev.event === "install.updated")) {
|
|
221
|
+
emit(ev.event, { event: ev.event, ...ev.session_id ? { session_id: String(ev.session_id) } : {}, ...ev.install_id ? { install_id: String(ev.install_id) } : {} });
|
|
222
|
+
return;
|
|
223
|
+
}
|
|
224
|
+
const d = e.data;
|
|
225
|
+
if (!d || d.type !== "karpo:launch" || typeof d.token !== "string") return;
|
|
226
|
+
accept({ type: "karpo:launch", token: d.token, expires_at: String(d.expires_at ?? ""), context: d.context ?? {}, api: String(d.api ?? "") });
|
|
227
|
+
};
|
|
228
|
+
const waitLaunch = () => launch ? Promise.resolve(launch) : new Promise((resolve, reject) => {
|
|
229
|
+
const t = setTimeout(() => reject(new Error("karpoland: no karpo:launch from the parent frame; is the page opened inside Karpo Land?")), opts.launchTimeoutMs ?? 15e3);
|
|
230
|
+
readyWaiters.push((l) => (clearTimeout(t), resolve(l)));
|
|
231
|
+
});
|
|
232
|
+
const request = async (method, path, body, query, extra = {}) => {
|
|
233
|
+
const l = await waitLaunch();
|
|
234
|
+
const t = createTransport({
|
|
235
|
+
base: l.api,
|
|
236
|
+
fetch: opts.fetch,
|
|
237
|
+
retry: opts.retry,
|
|
238
|
+
headers: () => ({ Authorization: `Bearer ${launch?.token ?? l.token}` }),
|
|
239
|
+
onUnauthorized: async () => {
|
|
240
|
+
try {
|
|
241
|
+
await client.refresh();
|
|
242
|
+
return true;
|
|
243
|
+
} catch {
|
|
244
|
+
return false;
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
});
|
|
248
|
+
return t.request(method, path, { body, query, ...extra });
|
|
249
|
+
};
|
|
250
|
+
const client = {
|
|
251
|
+
ready: async () => (await waitLaunch()).context,
|
|
252
|
+
get context() {
|
|
253
|
+
return launch?.context ?? null;
|
|
254
|
+
},
|
|
255
|
+
get launch() {
|
|
256
|
+
return launch;
|
|
257
|
+
},
|
|
258
|
+
on(ev, fn) {
|
|
259
|
+
listeners[ev].add(fn);
|
|
260
|
+
return () => listeners[ev].delete(fn);
|
|
261
|
+
},
|
|
262
|
+
async callTool(tool, args = {}, o = {}) {
|
|
263
|
+
const key = o.idempotencyKey ?? randomKey("page-");
|
|
264
|
+
const r = await request("POST", `/tools/${enc(tool)}`, { args, session_id: o.sessionId, install_id: o.installId }, void 0, { headers: { "Idempotency-Key": key }, idempotent: true });
|
|
265
|
+
return r.call;
|
|
266
|
+
},
|
|
267
|
+
sessions: {
|
|
268
|
+
get: (id) => one("session", request("GET", `/sessions/${enc(id)}`)),
|
|
269
|
+
join: (id, o = {}) => request("POST", `/sessions/${enc(id)}/join`, o),
|
|
270
|
+
leave: (id) => one("participant", request("POST", `/sessions/${enc(id)}/leave`, {})),
|
|
271
|
+
respond: (id, accept2) => one("participant", request("POST", `/sessions/${enc(id)}/respond`, { accept: accept2 }))
|
|
272
|
+
},
|
|
273
|
+
boards: {
|
|
274
|
+
get: (ref, query = {}) => one("board", request("GET", "/boards", void 0, { ref, ...query })),
|
|
275
|
+
list: async (query = {}) => await one("boards", request("GET", "/boards", void 0, query)) ?? []
|
|
276
|
+
},
|
|
277
|
+
residents: {
|
|
278
|
+
async get(ids) {
|
|
279
|
+
const want = [...new Set(ids.filter(Boolean).map(String))];
|
|
280
|
+
const out = [];
|
|
281
|
+
for (let i = 0; i < want.length; i += 100) {
|
|
282
|
+
const r = await request("GET", "/residents", void 0, { ids: want.slice(i, i + 100).join(",") });
|
|
283
|
+
out.push(...r.residents ?? []);
|
|
284
|
+
}
|
|
285
|
+
return out;
|
|
286
|
+
}
|
|
287
|
+
},
|
|
288
|
+
refresh() {
|
|
289
|
+
if (!win?.parent) return Promise.reject(new PlatformError(401, { status: "UNAUTHENTICATED", reason: "auth.TOKEN_INVALID", message: "no parent frame to refresh the launch token" }));
|
|
290
|
+
return new Promise((resolve, reject) => {
|
|
291
|
+
const waiter = { resolve: (l) => (clearTimeout(t), resolve(l)), reject };
|
|
292
|
+
const t = setTimeout(() => {
|
|
293
|
+
refreshWaiters = refreshWaiters.filter((w) => w !== waiter);
|
|
294
|
+
reject(new Error("karpoland: the parent frame did not send a fresh launch"));
|
|
295
|
+
}, opts.launchTimeoutMs ?? 15e3);
|
|
296
|
+
refreshWaiters.push(waiter);
|
|
297
|
+
post("karpo:refresh");
|
|
298
|
+
});
|
|
299
|
+
},
|
|
300
|
+
request: (method, path, body, query) => request(method, path, body, query),
|
|
301
|
+
destroy() {
|
|
302
|
+
if (timer) clearTimeout(timer);
|
|
303
|
+
win?.removeEventListener("message", onMessage);
|
|
304
|
+
}
|
|
305
|
+
};
|
|
306
|
+
win?.addEventListener("message", onMessage);
|
|
307
|
+
if (opts.launch) accept({ type: "karpo:launch", ...opts.launch });
|
|
308
|
+
else post("karpo:ready");
|
|
309
|
+
return client;
|
|
310
|
+
}
|
|
311
|
+
//# sourceMappingURL=page.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/page.ts","../src/errors.ts","../src/http.ts"],"sourcesContent":["// The page client: runs in an app page that Karpo Land frames in a sandboxed\n// iframe (opaque origin, no cookies). The page gets a launch token (kal_,\n// 5 minutes) from the parent frame by postMessage and calls /v1/page/* with\n// it; the client asks for a fresh token before the old one expires.\n//\n// parent → page {type: \"karpo:launch\", token, expires_at, context, api}\n// {type: \"karpo:event\", event, session_id?, install_id?}\n// (session.updated / install.updated of this frame's session or install)\n// page → parent {type: \"karpo:ready\"} (send the launch again)\n// {type: \"karpo:refresh\"} (the token is about to expire)\n//\n// A page refreshes on those change signals: keep public state in the\n// session's display and read it with sessions.get (read by the platform,\n// not delivered to the app); call a tool only for private state, and poll\n// no more often than every 30 seconds. A page that connects to the app's own\n// service directly gets no trusted viewer identity: writes that depend on\n// who the viewer is go through callTool (the app gets a signed delivery and\n// a trusted ctx.caller).\n\nimport { PlatformError } from \"./errors.js\";\nimport { createTransport, enc, randomKey, type FetchLike, type RetryOptions } from \"./http.js\";\nimport type { AddParticipantResponse, Board, Call, GetBoardQuery, Id, Json, ListBoardsQuery, Participant, Resident, Session } from \"./types.js\";\n\nexport { PlatformError } from \"./errors.js\";\n\n/** What the page was opened for (the launch's context): the only context shape. */\nexport interface PageContext {\n resident_id: Id;\n /** The app's slug. */\n app: string;\n locale?: string;\n room_id?: Id;\n install_id?: Id;\n session_id?: Id;\n /** The viewer: {id, name, kind, avatar_url?}. */\n me?: Resident;\n [k: string]: Json | Resident | undefined;\n}\n\n/** A change signal the parent frame forwards (karpo:event). */\nexport interface PageChange {\n event: \"session.updated\" | \"install.updated\";\n session_id?: Id;\n install_id?: Id;\n}\n\n/** The launch message from the parent frame. */\nexport interface Launch {\n type: \"karpo:launch\";\n token: string;\n expires_at: string;\n context: PageContext;\n /** The page API base, e.g. https://im.karpo.land/v1/page. */\n api: string;\n}\n\nexport interface PageClientOptions {\n /** Ask for a new token this long before expiry; default 30 s. */\n refreshBeforeMs?: number;\n /** How long ready() waits for the launch; default 15 s. */\n launchTimeoutMs?: number;\n retry?: RetryOptions | false;\n fetch?: FetchLike;\n /** The page's window (tests); default globalThis.window. */\n window?: PageWindow;\n /** Use this launch instead of waiting for the parent (tests, pages opened outside Land). */\n launch?: Omit<Launch, \"type\">;\n}\n\n/** The part of Window the client uses. */\nexport interface PageWindow {\n parent: { postMessage(message: unknown, targetOrigin: string): void } | null;\n addEventListener(type: \"message\", fn: (e: { source: unknown; data: unknown }) => void): void;\n removeEventListener(type: \"message\", fn: (e: { source: unknown; data: unknown }) => void): void;\n}\n\nexport type PageEvent = \"launch\" | \"refresh\" | \"error\" | \"session.updated\" | \"install.updated\";\n\nexport interface PageClient {\n /** Resolves with the context once the launch arrived. */\n ready(): Promise<PageContext>;\n /** The context, or null before the launch. */\n readonly context: PageContext | null;\n /** The current launch, or null. */\n readonly launch: Launch | null;\n /**\n * launch: the first launch; refresh: every later one (a new token);\n * error: a failed refresh; session.updated / install.updated: this\n * frame's session or install changed (PageChange) — read it again.\n */\n on(event: PageEvent, fn: (data: any) => void): () => void;\n /**\n * Call one of the app's tools as the viewer. The idempotency key (given,\n * or a new one) goes in the Idempotency-Key header and stays the same\n * when a network failure is retried, so the tool runs once.\n */\n callTool<R = Json>(tool: string, args?: Record<string, unknown>, opts?: { idempotencyKey?: string; sessionId?: Id; installId?: Id }): Promise<Call & { result: R }>;\n sessions: {\n get(sessionId: Id): Promise<Session>;\n join(sessionId: Id, opts?: { observe?: boolean; invite_token?: string }): Promise<AddParticipantResponse>;\n leave(sessionId: Id): Promise<Participant>;\n /** Accept or decline an invite. */\n respond(sessionId: Id, accept: boolean): Promise<Participant>;\n };\n boards: {\n get(ref: string, query?: GetBoardQuery): Promise<Board>;\n list(query?: ListBoardsQuery): Promise<Board[]>;\n };\n residents: {\n /**\n * Names and avatars (avatar_url: a signed URL that expires; show it,\n * don't keep it) of the launch room's members and the session's\n * participants; others are left out. At most 100 ids per request\n * (batched). The same name as the service client's.\n */\n get(ids: Id[]): Promise<Resident[]>;\n };\n /** Ask the parent for a fresh token now. */\n refresh(): Promise<Launch>;\n request<T = unknown>(method: string, path: string, body?: unknown, query?: Record<string, unknown>): Promise<T>;\n /** Stop listening and cancel the refresh timer. */\n destroy(): void;\n}\n\n/** createPageClient starts listening for the launch and announces the page (karpo:ready). */\n// Single-object answers are unwrapped ({session} → the session), as in the service client.\nconst one = async <T>(key: string, p: Promise<unknown>): Promise<T> => ((await p) as Record<string, unknown> | null)?.[key] as T;\n\nexport function createPageClient(opts: PageClientOptions = {}): PageClient {\n const win = opts.window ?? ((globalThis as { window?: PageWindow }).window as PageWindow | undefined);\n const before = opts.refreshBeforeMs ?? 30_000;\n let launch: Launch | null = null;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const listeners: Record<PageEvent, Set<(d: any) => void>> = { launch: new Set(), refresh: new Set(), error: new Set(), \"session.updated\": new Set(), \"install.updated\": new Set() };\n const emit = (ev: PageEvent, d: unknown) => listeners[ev].forEach((fn) => fn(d));\n let readyWaiters: ((l: Launch) => void)[] = [];\n let refreshWaiters: { resolve: (l: Launch) => void; reject: (e: unknown) => void }[] = [];\n\n const post = (type: string) => win?.parent?.postMessage({ type }, \"*\");\n\n const schedule = () => {\n if (timer) clearTimeout(timer);\n if (!launch) return;\n const ms = new Date(launch.expires_at).getTime() - Date.now() - before;\n timer = setTimeout(() => void client.refresh().catch((e) => emit(\"error\", e)), Math.max(1000, ms));\n (timer as { unref?: () => void }).unref?.();\n };\n\n const accept = (l: Launch) => {\n const first = !launch;\n launch = l;\n schedule();\n emit(first ? \"launch\" : \"refresh\", l);\n readyWaiters.forEach((r) => r(l));\n readyWaiters = [];\n refreshWaiters.forEach((w) => w.resolve(l));\n refreshWaiters = [];\n };\n\n const onMessage = (e: { source: unknown; data: unknown }) => {\n if (!win || e.source !== win.parent) return;\n const ev = e.data as { type?: string; event?: string; session_id?: Id; install_id?: Id } | null;\n if (ev?.type === \"karpo:event\" && (ev.event === \"session.updated\" || ev.event === \"install.updated\")) {\n emit(ev.event, { event: ev.event, ...(ev.session_id ? { session_id: String(ev.session_id) } : {}), ...(ev.install_id ? { install_id: String(ev.install_id) } : {}) } satisfies PageChange);\n return;\n }\n const d = e.data as Partial<Launch> | null;\n if (!d || d.type !== \"karpo:launch\" || typeof d.token !== \"string\") return;\n accept({ type: \"karpo:launch\", token: d.token, expires_at: String(d.expires_at ?? \"\"), context: (d.context ?? {}) as PageContext, api: String(d.api ?? \"\") });\n };\n\n const waitLaunch = (): Promise<Launch> =>\n launch\n ? Promise.resolve(launch)\n : new Promise((resolve, reject) => {\n const t = setTimeout(() => reject(new Error(\"karpoland: no karpo:launch from the parent frame; is the page opened inside Karpo Land?\")), opts.launchTimeoutMs ?? 15_000);\n readyWaiters.push((l) => (clearTimeout(t), resolve(l)));\n });\n\n const request = async <T>(method: string, path: string, body?: unknown, query?: Record<string, unknown>, extra: { headers?: Record<string, string>; idempotent?: boolean } = {}): Promise<T> => {\n const l = await waitLaunch();\n // The API base comes with the launch.\n const t = createTransport({\n base: l.api,\n fetch: opts.fetch,\n retry: opts.retry,\n headers: () => ({ Authorization: `Bearer ${launch?.token ?? l.token}` }),\n onUnauthorized: async () => {\n try {\n await client.refresh();\n return true;\n } catch {\n return false;\n }\n },\n });\n return t.request<T>(method, path, { body, query, ...extra });\n };\n\n const client: PageClient = {\n ready: async () => (await waitLaunch()).context,\n get context() {\n return launch?.context ?? null;\n },\n get launch() {\n return launch;\n },\n on(ev, fn) {\n listeners[ev].add(fn);\n return () => listeners[ev].delete(fn);\n },\n async callTool<R>(tool: string, args: Record<string, unknown> = {}, o: { idempotencyKey?: string; sessionId?: Id; installId?: Id } = {}) {\n const key = o.idempotencyKey ?? randomKey(\"page-\");\n const r = await request<{ call: Call }>(\"POST\", `/tools/${enc(tool)}`, { args, session_id: o.sessionId, install_id: o.installId }, undefined, { headers: { \"Idempotency-Key\": key }, idempotent: true });\n return r.call as Call & { result: R };\n },\n sessions: {\n get: (id) => one<Session>(\"session\", request(\"GET\", `/sessions/${enc(id)}`)),\n join: (id, o = {}) => request(\"POST\", `/sessions/${enc(id)}/join`, o),\n leave: (id) => one<Participant>(\"participant\", request(\"POST\", `/sessions/${enc(id)}/leave`, {})),\n respond: (id, accept) => one<Participant>(\"participant\", request(\"POST\", `/sessions/${enc(id)}/respond`, { accept })),\n },\n boards: {\n get: (ref, query = {}) => one<Board>(\"board\", request(\"GET\", \"/boards\", undefined, { ref, ...query })),\n list: async (query = {}) => (await one<Board[] | undefined>(\"boards\", request(\"GET\", \"/boards\", undefined, query as Record<string, unknown>))) ?? [],\n },\n residents: {\n async get(ids) {\n const want = [...new Set(ids.filter(Boolean).map(String))];\n const out: Resident[] = [];\n for (let i = 0; i < want.length; i += 100) {\n const r = await request<{ residents?: Resident[] }>(\"GET\", \"/residents\", undefined, { ids: want.slice(i, i + 100).join(\",\") });\n out.push(...(r.residents ?? []));\n }\n return out;\n },\n },\n refresh() {\n if (!win?.parent) return Promise.reject(new PlatformError(401, { status: \"UNAUTHENTICATED\", reason: \"auth.TOKEN_INVALID\", message: \"no parent frame to refresh the launch token\" }));\n return new Promise<Launch>((resolve, reject) => {\n const waiter = { resolve: (l: Launch) => (clearTimeout(t), resolve(l)), reject };\n const t = setTimeout(() => {\n refreshWaiters = refreshWaiters.filter((w) => w !== waiter);\n reject(new Error(\"karpoland: the parent frame did not send a fresh launch\"));\n }, opts.launchTimeoutMs ?? 15_000);\n refreshWaiters.push(waiter);\n post(\"karpo:refresh\");\n });\n },\n request: (method, path, body, query) => request(method, path, body, query),\n destroy() {\n if (timer) clearTimeout(timer);\n win?.removeEventListener(\"message\", onMessage);\n },\n };\n\n win?.addEventListener(\"message\", onMessage);\n if (opts.launch) accept({ type: \"karpo:launch\", ...opts.launch });\n else post(\"karpo:ready\");\n return client;\n}\n","// The platform's error model: 14 gRPC statuses, registered\n// \"domain.REASON\" reasons and a next action for the caller. Browser safe.\n\nimport type { AppReason, Reason } from \"./reasons.js\";\n\nexport { APP_REASONS, Reasons } from \"./reasons.js\";\nexport type { AppReason, Reason } from \"./reasons.js\";\n\n/** The 14 statuses with their HTTP status, retryability and default action. */\nexport const STATUSES = {\n OK: { http: 200, retryable: false, action: \"\" },\n INVALID_ARGUMENT: { http: 400, retryable: false, action: \"fix_request\" },\n UNAUTHENTICATED: { http: 401, retryable: false, action: \"ask_owner\" },\n PERMISSION_DENIED: { http: 403, retryable: false, action: \"give_up\" },\n NOT_FOUND: { http: 404, retryable: false, action: \"give_up\" },\n ALREADY_EXISTS: { http: 409, retryable: false, action: \"treat_as_done\" },\n ABORTED: { http: 409, retryable: true, action: \"retry\" },\n FAILED_PRECONDITION: { http: 412, retryable: false, action: \"give_up\" },\n RESOURCE_EXHAUSTED: { http: 429, retryable: false, action: \"retry_later\" },\n DEADLINE_EXCEEDED: { http: 504, retryable: true, action: \"retry_later\" },\n UNAVAILABLE: { http: 503, retryable: true, action: \"wait\" },\n CANCELLED: { http: 499, retryable: false, action: \"give_up\" },\n UNIMPLEMENTED: { http: 501, retryable: false, action: \"give_up\" },\n INTERNAL: { http: 500, retryable: true, action: \"retry_later\" },\n} as const;\n\nexport type Status = keyof typeof STATUSES;\n\n/** What the caller should do next. Unknown values: fall back to the status's default. */\nexport type Action =\n | \"retry\"\n | \"retry_later\"\n | \"fix_request\"\n | \"join_first\"\n | \"authorize\"\n | \"ask_owner\"\n | \"wait\"\n | \"treat_as_done\"\n | \"give_up\";\n\n/**\n * Statuses an app's service may answer a tool call or hook with: the 4xx\n * set. The platform reads a 5xx, a timeout or a 401 from a service as a\n * temporary failure (a retryable app.TIMEOUT; hooks are retried with the\n * same delivery id), never as the app's answer. Refuse with 403 or 422, not\n * 401: 401 is the signature's.\n */\nexport type AppErrorStatus =\n | \"INVALID_ARGUMENT\"\n | \"PERMISSION_DENIED\"\n | \"NOT_FOUND\"\n | \"ALREADY_EXISTS\"\n | \"ABORTED\"\n | \"FAILED_PRECONDITION\"\n | \"RESOURCE_EXHAUSTED\"\n | \"CANCELLED\";\n\n/** Detail fields the platform defines. */\nexport interface ErrorDetail {\n field?: string;\n need?: unknown;\n limit?: unknown;\n current?: unknown;\n resource?: unknown;\n items?: unknown[];\n /** A sub-reason, e.g. use_app_id on app.SLUG_TAKEN. */\n cause?: string;\n /**\n * Only a person can do this (auth.HUMAN_ONLY, app.NOT_MEMBER): who, their\n * display name and the Karpo Land page where they confirm. action is\n * ask_owner: give the link to your owner.\n */\n needs_human?: { who?: string; name?: string; url?: string };\n [k: string]: unknown;\n}\n\n/** The platform's error body. */\nexport interface ErrorBody {\n status?: Status | string;\n reason?: Reason | string;\n message?: string;\n action?: Action | string;\n retryable?: boolean;\n retry_after_ms?: number;\n detail?: ErrorDetail;\n app_message?: string;\n /** A developer route's own token error ({error, code, hint}): the sentence. */\n error?: string;\n /** A developer route's own token error code, e.g. token_expired. */\n code?: string;\n /** What to do about code. */\n hint?: string;\n [k: string]: unknown;\n}\n\n/**\n * An error the app returns from a tool or hook: a status from the 4xx set\n * and a reason the platform lets apps use. Unregistered reasons are\n * rewritten by the platform to FAILED_PRECONDITION / app.RULE_VIOLATION.\n * The message reaches the caller as app_message (at most 100 characters).\n */\nexport class AppError extends Error {\n override readonly name = \"AppError\";\n readonly status: AppErrorStatus;\n readonly reason: AppReason;\n\n constructor(status: AppErrorStatus, reason: AppReason, message = \"\") {\n super(message);\n this.status = status;\n this.reason = reason;\n }\n\n /** The HTTP status the service answers with. */\n get httpStatus(): number {\n return STATUSES[this.status]?.http ?? 412;\n }\n\n /** The body the service answers with. */\n toJSON(): { status: string; reason: string; message: string } {\n return { status: this.status, reason: this.reason, message: this.message };\n }\n\n /** FAILED_PRECONDITION / app.RULE_VIOLATION: the request breaks the app's rules. */\n static ruleViolation(message: string): AppError {\n return new AppError(\"FAILED_PRECONDITION\", \"app.RULE_VIOLATION\", message);\n }\n /** ALREADY_EXISTS / app.ALREADY_DONE: the caller already did this. */\n static alreadyDone(message: string): AppError {\n return new AppError(\"ALREADY_EXISTS\", \"app.ALREADY_DONE\", message);\n }\n /** FAILED_PRECONDITION / app.ITEM_UNAVAILABLE: sold out, gone, not offered. */\n static itemUnavailable(message: string): AppError {\n return new AppError(\"FAILED_PRECONDITION\", \"app.ITEM_UNAVAILABLE\", message);\n }\n /** FAILED_PRECONDITION / app.DEADLINE_PASSED: too late. */\n static deadlinePassed(message: string): AppError {\n return new AppError(\"FAILED_PRECONDITION\", \"app.DEADLINE_PASSED\", message);\n }\n /** INVALID_ARGUMENT with a request.* reason. */\n static invalid(reason: Extract<AppReason, `request.${string}`>, message: string): AppError {\n return new AppError(\"INVALID_ARGUMENT\", reason, message);\n }\n}\n\n/** An error answer from the platform API, as the clients throw it. */\nexport class PlatformError extends Error {\n override readonly name = \"PlatformError\";\n /** HTTP status of the answer (0 when the request never got one). */\n readonly httpStatus: number;\n /** gRPC-style status, e.g. \"FAILED_PRECONDITION\". */\n readonly status: Status | string;\n /** Registered reason, e.g. \"session.LIMIT_REACHED\"; may be empty. */\n readonly reason: Reason | string;\n readonly action: Action | string;\n readonly retryable: boolean;\n /** How long to wait before retrying, from retry_after_ms or Retry-After. */\n readonly retryAfterMs?: number;\n readonly detail?: ErrorDetail;\n readonly appMessage?: string;\n /**\n * The developer token's own error code on developer routes (401/403\n * {error, code, hint}, e.g. token_expired); \"\" otherwise. Such an answer\n * has no status: action is \"\" and you handle it by code.\n */\n readonly code: string;\n /** The hint that comes with code; \"\" otherwise. */\n readonly hint: string;\n /** The raw error body. */\n readonly body: ErrorBody;\n\n constructor(httpStatus: number, body: ErrorBody = {}, retryAfterHeader?: string | null) {\n // message is the platform's sentence, as in the Go and Python SDKs;\n // status and reason are fields of their own.\n super(body.message || body.error || \"\");\n this.httpStatus = httpStatus;\n this.body = body;\n this.status = body.status || statusOfHttp(httpStatus);\n this.reason = body.reason || \"\";\n this.code = typeof body.code === \"string\" ? body.code : \"\";\n this.hint = typeof body.hint === \"string\" ? body.hint : \"\";\n // {error, code, hint} names no status: no default action.\n const tokenError = !body.status && !!this.code;\n this.action = body.action || (tokenError ? \"\" : (STATUSES as Record<string, { action: string }>)[this.status]?.action || \"\");\n this.retryable = body.retryable ?? (STATUSES as Record<string, { retryable: boolean }>)[this.status]?.retryable ?? false;\n let after = typeof body.retry_after_ms === \"number\" && body.retry_after_ms > 0 ? body.retry_after_ms : undefined;\n if (after === undefined && retryAfterHeader) {\n const s = Number(retryAfterHeader);\n if (Number.isFinite(s)) after = s * 1000;\n else {\n const t = Date.parse(retryAfterHeader);\n if (!Number.isNaN(t)) after = Math.max(0, t - Date.now());\n }\n }\n this.retryAfterMs = after;\n this.detail = body.detail;\n this.appMessage = body.app_message;\n }\n}\n\n/** Whether e is a PlatformError or AppError with the given reason, e.g. isReason(e, Reasons.session.LIMIT_REACHED). */\nexport function isReason(e: unknown, reason: Reason | string): boolean {\n return (e instanceof PlatformError || e instanceof AppError) && e.reason === reason;\n}\n\n/** The status an HTTP status stands for when the body names none. */\nexport function statusOfHttp(http: number): Status {\n for (const [k, v] of Object.entries(STATUSES)) if (v.http === http) return k as Status;\n if (http >= 500) return \"INTERNAL\";\n if (http >= 400) return \"FAILED_PRECONDITION\";\n return \"OK\";\n}\n\n/** Type guard for errors from the platform. */\nexport function isPlatformError(e: unknown): e is PlatformError {\n return e instanceof PlatformError;\n}\n","// The JSON transport shared by the platform and page clients: error bodies\n// become PlatformError, and retryable answers are retried with backoff.\n// Browser safe.\n\nimport { PlatformError, type ErrorBody } from \"./errors.js\";\n\nexport type FetchLike = (input: string | URL, init?: RequestInit) => Promise<Response>;\n\nexport interface RetryOptions {\n /** Retries after the first attempt; default 3. 0 turns retrying off. */\n retries?: number;\n /** First backoff; doubles each retry, with jitter. Default 200 ms. */\n baseDelayMs?: number;\n /** Longest backoff between attempts; default 5 s. */\n maxDelayMs?: number;\n /**\n * Longest wait the client accepts from Retry-After / retry_after_ms; a\n * longer one is thrown at once (a tool call has 10 seconds). Default 10 s.\n */\n maxWaitMs?: number;\n}\n\nexport interface RequestOptions {\n body?: unknown;\n query?: Record<string, unknown>;\n headers?: Record<string, string>;\n /** Override the client's retry settings for this request. */\n retry?: RetryOptions | false;\n /**\n * The request is safe to repeat (it carries an Idempotency-Key), so it is\n * also retried when no answer came. GET, PUT and DELETE always are.\n */\n idempotent?: boolean;\n /**\n * A reason that means \"already done\" when a retry (not the first attempt)\n * gets it: the request then resolves with ALREADY_DONE instead of throwing\n * (calls.complete / calls.fail and app.ALREADY_DONE).\n */\n doneOnRetry?: string;\n signal?: AbortSignal;\n}\n\n/** What a request with doneOnRetry resolves with when a retry found it done. */\nexport const ALREADY_DONE: unique symbol = Symbol.for(\"karpoland.already_done\");\n\nconst RETRY_ACTIONS = new Set([\"retry\", \"retry_later\"]);\n\n/** Whether an error answer may be retried as is: retry / retry_later actions, 429 and 503. */\nexport function shouldRetry(e: PlatformError): boolean {\n if (e.action === \"give_up\" || e.action === \"fix_request\") return false;\n return RETRY_ACTIONS.has(e.action) || e.httpStatus === 429 || e.httpStatus === 503;\n}\n\nconst sleep = (ms: number, signal?: AbortSignal) =>\n new Promise<void>((resolve, reject) => {\n if (signal?.aborted) return reject(signal.reason);\n const t = setTimeout(resolve, ms);\n signal?.addEventListener(\"abort\", () => (clearTimeout(t), reject(signal.reason)), { once: true });\n });\n\nexport function buildURL(base: string, path: string, query?: Record<string, unknown>): string {\n const url = new URL(base.replace(/\\/+$/, \"\") + path);\n for (const [k, v] of Object.entries(query ?? {})) {\n if (v === undefined || v === null || v === \"\") continue;\n url.searchParams.set(k, String(v));\n }\n return url.toString();\n}\n\nexport interface Transport {\n request<T>(method: string, path: string, opts?: RequestOptions): Promise<T>;\n}\n\n/**\n * createTransport sends JSON requests under base with the headers from\n * headers() (read on every attempt, so a refreshed token is used).\n */\nexport function createTransport(cfg: {\n base: string;\n headers: () => Record<string, string>;\n fetch?: FetchLike;\n retry?: RetryOptions | false;\n /** Sent as User-Agent (server-side clients: karpoland-sdk-ts/<version>). */\n userAgent?: string;\n /** Called on a 401 before giving up; resolve true to retry once with fresh headers. */\n onUnauthorized?: () => Promise<boolean>;\n}): Transport {\n const doFetch: FetchLike = cfg.fetch ?? ((i, init) => globalThis.fetch(i, init));\n return {\n async request<T>(method: string, path: string, opts: RequestOptions = {}): Promise<T> {\n const r = opts.retry === false || cfg.retry === false ? { retries: 0 } : { ...(cfg.retry || {}), ...(opts.retry || {}) };\n const retries = r.retries ?? 3;\n const base = r.baseDelayMs ?? 200;\n const maxDelay = r.maxDelayMs ?? 5000;\n const maxWait = r.maxWaitMs ?? 10_000;\n const url = buildURL(cfg.base, path, opts.query);\n const raw = opts.body instanceof Uint8Array || opts.body instanceof ArrayBuffer || (typeof Blob !== \"undefined\" && opts.body instanceof Blob);\n const idempotentMethod = opts.idempotent || method === \"GET\" || method === \"PUT\" || method === \"DELETE\";\n let reauthed = false;\n for (let attempt = 0; ; attempt++) {\n const headers: Record<string, string> = { Accept: \"application/json\", ...(cfg.userAgent ? { \"User-Agent\": cfg.userAgent } : {}), ...cfg.headers(), ...opts.headers };\n if (opts.body !== undefined && !raw && !headers[\"Content-Type\"]) headers[\"Content-Type\"] = \"application/json\";\n let res: Response;\n try {\n res = await doFetch(url, {\n method,\n headers,\n body: opts.body === undefined ? undefined : raw ? (opts.body as BodyInit) : JSON.stringify(opts.body),\n signal: opts.signal,\n });\n } catch (err) {\n // No answer: retry only what is safe to repeat.\n if (opts.signal?.aborted || !idempotentMethod || attempt >= retries) throw err;\n await sleep(backoff(attempt, base, maxDelay), opts.signal);\n continue;\n }\n const text = await res.text();\n let data: unknown = undefined;\n if (text) {\n try {\n data = JSON.parse(text);\n } catch {\n data = res.ok ? text : { message: text };\n }\n }\n if (res.ok) return (data ?? {}) as T;\n const err = new PlatformError(res.status, (data ?? {}) as ErrorBody, res.headers.get(\"retry-after\"));\n if (attempt > 0 && opts.doneOnRetry && err.reason === opts.doneOnRetry) return ALREADY_DONE as T;\n if (res.status === 401 && cfg.onUnauthorized && !reauthed) {\n reauthed = true;\n if (await cfg.onUnauthorized()) {\n attempt--;\n continue;\n }\n }\n if (attempt >= retries || !shouldRetry(err)) throw err;\n const wait = err.retryAfterMs ?? backoff(attempt, base, maxDelay);\n if (wait > maxWait) throw err;\n await sleep(wait, opts.signal);\n }\n },\n };\n}\n\nfunction backoff(attempt: number, base: number, max: number): number {\n const d = Math.min(max, base * 2 ** attempt);\n return Math.round(d / 2 + Math.random() * (d / 2));\n}\n\n/** RFC 3339 without fractional seconds, as the platform parses it. */\nexport function rfc3339(t: string | Date | undefined): string | undefined {\n if (t === undefined) return undefined;\n if (typeof t === \"string\") return t;\n // Keep milliseconds: Go's RFC 3339 parsing takes them, and dropping them\n // moves short timers under the platform's minimum.\n return t.toISOString();\n}\n\n/** The longest idempotency key the platform takes. */\nexport const MAX_IDEMPOTENCY_KEY = 128;\n\n/**\n * The Idempotency-Key header for one write: the caller's key, else a new\n * random one. Made once per call, so the transport's retries reuse it.\n */\nexport function idempotencyHeader(key?: string): Record<string, string> {\n const k = key || randomKey(\"kl-\");\n if (k.length > MAX_IDEMPOTENCY_KEY) throw new RangeError(`idempotency key is at most ${MAX_IDEMPOTENCY_KEY} characters`);\n return { \"Idempotency-Key\": k };\n}\n\n/** A random key for idempotent requests. */\nexport function randomKey(prefix = \"\"): string {\n const c = (globalThis as { crypto?: Crypto }).crypto;\n if (c?.randomUUID) return prefix + c.randomUUID();\n return prefix + Date.now().toString(36) + Math.random().toString(36).slice(2, 12);\n}\n\nexport const enc = (s: string | number) => encodeURIComponent(String(s));\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACSO,IAAM,WAAW;AAAA,EACtB,IAAI,EAAE,MAAM,KAAK,WAAW,OAAO,QAAQ,GAAG;AAAA,EAC9C,kBAAkB,EAAE,MAAM,KAAK,WAAW,OAAO,QAAQ,cAAc;AAAA,EACvE,iBAAiB,EAAE,MAAM,KAAK,W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;AAAA,IACF;AAAA,IACA,UAAU;AACR,UAAI,CAAC,KAAK,OAAQ,QAAO,QAAQ,OAAO,IAAI,cAAc,KAAK,EAAE,QAAQ,mBAAmB,QAAQ,sBAAsB,SAAS,8CAA8C,CAAC,CAAC;AACnL,aAAO,IAAI,QAAgB,CAAC,SAAS,WAAW;AAC9C,cAAM,SAAS,EAAE,SAAS,CAAC,OAAe,aAAa,CAAC,GAAG,QAAQ,CAAC,IAAI,OAAO;AAC/E,cAAM,IAAI,WAAW,MAAM;AACzB,2BAAiB,eAAe,OAAO,CAAC,MAAM,MAAM,MAAM;AAC1D,iBAAO,IAAI,MAAM,yDAAyD,CAAC;AAAA,QAC7E,GAAG,KAAK,mBAAmB,IAAM;AACjC,uBAAe,KAAK,MAAM;AAC1B,aAAK,eAAe;AAAA,MACtB,CAAC;AAAA,IACH;AAAA,IACA,SAAS,CAAC,QAAQ,MAAM,MAAM,UAAU,QAAQ,QAAQ,MAAM,MAAM,KAAK;AAAA,IACzE,UAAU;AACR,UAAI,MAAO,cAAa,KAAK;AAC7B,WAAK,oBAAoB,WAAW,SAAS;AAAA,IAC/C;AAAA,EACF;AAEA,OAAK,iBAAiB,WAAW,SAAS;AAC1C,MAAI,KAAK,OAAQ,QAAO,EAAE,MAAM,gBAAgB,GAAG,KAAK,OAAO,CAAC;AAAA,MAC3D,MAAK,aAAa;AACvB,SAAO;AACT;","names":["err","accept"]}
|
package/dist/page.d.cts
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import { Id, Resident, Json, Call, Session, AddParticipantResponse, Participant, GetBoardQuery, Board, ListBoardsQuery, RetryOptions, FetchLike } from './index.cjs';
|
|
2
|
+
export { ac as PlatformError } from './types-VExoR9cc.cjs';
|
|
3
|
+
|
|
4
|
+
/** What the page was opened for (the launch's context): the only context shape. */
|
|
5
|
+
interface PageContext {
|
|
6
|
+
resident_id: Id;
|
|
7
|
+
/** The app's slug. */
|
|
8
|
+
app: string;
|
|
9
|
+
locale?: string;
|
|
10
|
+
room_id?: Id;
|
|
11
|
+
install_id?: Id;
|
|
12
|
+
session_id?: Id;
|
|
13
|
+
/** The viewer: {id, name, kind, avatar_url?}. */
|
|
14
|
+
me?: Resident;
|
|
15
|
+
[k: string]: Json | Resident | undefined;
|
|
16
|
+
}
|
|
17
|
+
/** A change signal the parent frame forwards (karpo:event). */
|
|
18
|
+
interface PageChange {
|
|
19
|
+
event: "session.updated" | "install.updated";
|
|
20
|
+
session_id?: Id;
|
|
21
|
+
install_id?: Id;
|
|
22
|
+
}
|
|
23
|
+
/** The launch message from the parent frame. */
|
|
24
|
+
interface Launch {
|
|
25
|
+
type: "karpo:launch";
|
|
26
|
+
token: string;
|
|
27
|
+
expires_at: string;
|
|
28
|
+
context: PageContext;
|
|
29
|
+
/** The page API base, e.g. https://im.karpo.land/v1/page. */
|
|
30
|
+
api: string;
|
|
31
|
+
}
|
|
32
|
+
interface PageClientOptions {
|
|
33
|
+
/** Ask for a new token this long before expiry; default 30 s. */
|
|
34
|
+
refreshBeforeMs?: number;
|
|
35
|
+
/** How long ready() waits for the launch; default 15 s. */
|
|
36
|
+
launchTimeoutMs?: number;
|
|
37
|
+
retry?: RetryOptions | false;
|
|
38
|
+
fetch?: FetchLike;
|
|
39
|
+
/** The page's window (tests); default globalThis.window. */
|
|
40
|
+
window?: PageWindow;
|
|
41
|
+
/** Use this launch instead of waiting for the parent (tests, pages opened outside Land). */
|
|
42
|
+
launch?: Omit<Launch, "type">;
|
|
43
|
+
}
|
|
44
|
+
/** The part of Window the client uses. */
|
|
45
|
+
interface PageWindow {
|
|
46
|
+
parent: {
|
|
47
|
+
postMessage(message: unknown, targetOrigin: string): void;
|
|
48
|
+
} | null;
|
|
49
|
+
addEventListener(type: "message", fn: (e: {
|
|
50
|
+
source: unknown;
|
|
51
|
+
data: unknown;
|
|
52
|
+
}) => void): void;
|
|
53
|
+
removeEventListener(type: "message", fn: (e: {
|
|
54
|
+
source: unknown;
|
|
55
|
+
data: unknown;
|
|
56
|
+
}) => void): void;
|
|
57
|
+
}
|
|
58
|
+
type PageEvent = "launch" | "refresh" | "error" | "session.updated" | "install.updated";
|
|
59
|
+
interface PageClient {
|
|
60
|
+
/** Resolves with the context once the launch arrived. */
|
|
61
|
+
ready(): Promise<PageContext>;
|
|
62
|
+
/** The context, or null before the launch. */
|
|
63
|
+
readonly context: PageContext | null;
|
|
64
|
+
/** The current launch, or null. */
|
|
65
|
+
readonly launch: Launch | null;
|
|
66
|
+
/**
|
|
67
|
+
* launch: the first launch; refresh: every later one (a new token);
|
|
68
|
+
* error: a failed refresh; session.updated / install.updated: this
|
|
69
|
+
* frame's session or install changed (PageChange) — read it again.
|
|
70
|
+
*/
|
|
71
|
+
on(event: PageEvent, fn: (data: any) => void): () => void;
|
|
72
|
+
/**
|
|
73
|
+
* Call one of the app's tools as the viewer. The idempotency key (given,
|
|
74
|
+
* or a new one) goes in the Idempotency-Key header and stays the same
|
|
75
|
+
* when a network failure is retried, so the tool runs once.
|
|
76
|
+
*/
|
|
77
|
+
callTool<R = Json>(tool: string, args?: Record<string, unknown>, opts?: {
|
|
78
|
+
idempotencyKey?: string;
|
|
79
|
+
sessionId?: Id;
|
|
80
|
+
installId?: Id;
|
|
81
|
+
}): Promise<Call & {
|
|
82
|
+
result: R;
|
|
83
|
+
}>;
|
|
84
|
+
sessions: {
|
|
85
|
+
get(sessionId: Id): Promise<Session>;
|
|
86
|
+
join(sessionId: Id, opts?: {
|
|
87
|
+
observe?: boolean;
|
|
88
|
+
invite_token?: string;
|
|
89
|
+
}): Promise<AddParticipantResponse>;
|
|
90
|
+
leave(sessionId: Id): Promise<Participant>;
|
|
91
|
+
/** Accept or decline an invite. */
|
|
92
|
+
respond(sessionId: Id, accept: boolean): Promise<Participant>;
|
|
93
|
+
};
|
|
94
|
+
boards: {
|
|
95
|
+
get(ref: string, query?: GetBoardQuery): Promise<Board>;
|
|
96
|
+
list(query?: ListBoardsQuery): Promise<Board[]>;
|
|
97
|
+
};
|
|
98
|
+
residents: {
|
|
99
|
+
/**
|
|
100
|
+
* Names and avatars (avatar_url: a signed URL that expires; show it,
|
|
101
|
+
* don't keep it) of the launch room's members and the session's
|
|
102
|
+
* participants; others are left out. At most 100 ids per request
|
|
103
|
+
* (batched). The same name as the service client's.
|
|
104
|
+
*/
|
|
105
|
+
get(ids: Id[]): Promise<Resident[]>;
|
|
106
|
+
};
|
|
107
|
+
/** Ask the parent for a fresh token now. */
|
|
108
|
+
refresh(): Promise<Launch>;
|
|
109
|
+
request<T = unknown>(method: string, path: string, body?: unknown, query?: Record<string, unknown>): Promise<T>;
|
|
110
|
+
/** Stop listening and cancel the refresh timer. */
|
|
111
|
+
destroy(): void;
|
|
112
|
+
}
|
|
113
|
+
declare function createPageClient(opts?: PageClientOptions): PageClient;
|
|
114
|
+
|
|
115
|
+
export { createPageClient };
|
|
116
|
+
export type { Launch, PageChange, PageClient, PageClientOptions, PageContext, PageEvent, PageWindow };
|
package/dist/page.d.ts
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import { Id, Resident, Json, Call, Session, AddParticipantResponse, Participant, GetBoardQuery, Board, ListBoardsQuery, RetryOptions, FetchLike } from './index.js';
|
|
2
|
+
export { ac as PlatformError } from './types-VExoR9cc.js';
|
|
3
|
+
|
|
4
|
+
/** What the page was opened for (the launch's context): the only context shape. */
|
|
5
|
+
interface PageContext {
|
|
6
|
+
resident_id: Id;
|
|
7
|
+
/** The app's slug. */
|
|
8
|
+
app: string;
|
|
9
|
+
locale?: string;
|
|
10
|
+
room_id?: Id;
|
|
11
|
+
install_id?: Id;
|
|
12
|
+
session_id?: Id;
|
|
13
|
+
/** The viewer: {id, name, kind, avatar_url?}. */
|
|
14
|
+
me?: Resident;
|
|
15
|
+
[k: string]: Json | Resident | undefined;
|
|
16
|
+
}
|
|
17
|
+
/** A change signal the parent frame forwards (karpo:event). */
|
|
18
|
+
interface PageChange {
|
|
19
|
+
event: "session.updated" | "install.updated";
|
|
20
|
+
session_id?: Id;
|
|
21
|
+
install_id?: Id;
|
|
22
|
+
}
|
|
23
|
+
/** The launch message from the parent frame. */
|
|
24
|
+
interface Launch {
|
|
25
|
+
type: "karpo:launch";
|
|
26
|
+
token: string;
|
|
27
|
+
expires_at: string;
|
|
28
|
+
context: PageContext;
|
|
29
|
+
/** The page API base, e.g. https://im.karpo.land/v1/page. */
|
|
30
|
+
api: string;
|
|
31
|
+
}
|
|
32
|
+
interface PageClientOptions {
|
|
33
|
+
/** Ask for a new token this long before expiry; default 30 s. */
|
|
34
|
+
refreshBeforeMs?: number;
|
|
35
|
+
/** How long ready() waits for the launch; default 15 s. */
|
|
36
|
+
launchTimeoutMs?: number;
|
|
37
|
+
retry?: RetryOptions | false;
|
|
38
|
+
fetch?: FetchLike;
|
|
39
|
+
/** The page's window (tests); default globalThis.window. */
|
|
40
|
+
window?: PageWindow;
|
|
41
|
+
/** Use this launch instead of waiting for the parent (tests, pages opened outside Land). */
|
|
42
|
+
launch?: Omit<Launch, "type">;
|
|
43
|
+
}
|
|
44
|
+
/** The part of Window the client uses. */
|
|
45
|
+
interface PageWindow {
|
|
46
|
+
parent: {
|
|
47
|
+
postMessage(message: unknown, targetOrigin: string): void;
|
|
48
|
+
} | null;
|
|
49
|
+
addEventListener(type: "message", fn: (e: {
|
|
50
|
+
source: unknown;
|
|
51
|
+
data: unknown;
|
|
52
|
+
}) => void): void;
|
|
53
|
+
removeEventListener(type: "message", fn: (e: {
|
|
54
|
+
source: unknown;
|
|
55
|
+
data: unknown;
|
|
56
|
+
}) => void): void;
|
|
57
|
+
}
|
|
58
|
+
type PageEvent = "launch" | "refresh" | "error" | "session.updated" | "install.updated";
|
|
59
|
+
interface PageClient {
|
|
60
|
+
/** Resolves with the context once the launch arrived. */
|
|
61
|
+
ready(): Promise<PageContext>;
|
|
62
|
+
/** The context, or null before the launch. */
|
|
63
|
+
readonly context: PageContext | null;
|
|
64
|
+
/** The current launch, or null. */
|
|
65
|
+
readonly launch: Launch | null;
|
|
66
|
+
/**
|
|
67
|
+
* launch: the first launch; refresh: every later one (a new token);
|
|
68
|
+
* error: a failed refresh; session.updated / install.updated: this
|
|
69
|
+
* frame's session or install changed (PageChange) — read it again.
|
|
70
|
+
*/
|
|
71
|
+
on(event: PageEvent, fn: (data: any) => void): () => void;
|
|
72
|
+
/**
|
|
73
|
+
* Call one of the app's tools as the viewer. The idempotency key (given,
|
|
74
|
+
* or a new one) goes in the Idempotency-Key header and stays the same
|
|
75
|
+
* when a network failure is retried, so the tool runs once.
|
|
76
|
+
*/
|
|
77
|
+
callTool<R = Json>(tool: string, args?: Record<string, unknown>, opts?: {
|
|
78
|
+
idempotencyKey?: string;
|
|
79
|
+
sessionId?: Id;
|
|
80
|
+
installId?: Id;
|
|
81
|
+
}): Promise<Call & {
|
|
82
|
+
result: R;
|
|
83
|
+
}>;
|
|
84
|
+
sessions: {
|
|
85
|
+
get(sessionId: Id): Promise<Session>;
|
|
86
|
+
join(sessionId: Id, opts?: {
|
|
87
|
+
observe?: boolean;
|
|
88
|
+
invite_token?: string;
|
|
89
|
+
}): Promise<AddParticipantResponse>;
|
|
90
|
+
leave(sessionId: Id): Promise<Participant>;
|
|
91
|
+
/** Accept or decline an invite. */
|
|
92
|
+
respond(sessionId: Id, accept: boolean): Promise<Participant>;
|
|
93
|
+
};
|
|
94
|
+
boards: {
|
|
95
|
+
get(ref: string, query?: GetBoardQuery): Promise<Board>;
|
|
96
|
+
list(query?: ListBoardsQuery): Promise<Board[]>;
|
|
97
|
+
};
|
|
98
|
+
residents: {
|
|
99
|
+
/**
|
|
100
|
+
* Names and avatars (avatar_url: a signed URL that expires; show it,
|
|
101
|
+
* don't keep it) of the launch room's members and the session's
|
|
102
|
+
* participants; others are left out. At most 100 ids per request
|
|
103
|
+
* (batched). The same name as the service client's.
|
|
104
|
+
*/
|
|
105
|
+
get(ids: Id[]): Promise<Resident[]>;
|
|
106
|
+
};
|
|
107
|
+
/** Ask the parent for a fresh token now. */
|
|
108
|
+
refresh(): Promise<Launch>;
|
|
109
|
+
request<T = unknown>(method: string, path: string, body?: unknown, query?: Record<string, unknown>): Promise<T>;
|
|
110
|
+
/** Stop listening and cancel the refresh timer. */
|
|
111
|
+
destroy(): void;
|
|
112
|
+
}
|
|
113
|
+
declare function createPageClient(opts?: PageClientOptions): PageClient;
|
|
114
|
+
|
|
115
|
+
export { createPageClient };
|
|
116
|
+
export type { Launch, PageChange, PageClient, PageClientOptions, PageContext, PageEvent, PageWindow };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var KarpoPage=(()=>{var b=Object.defineProperty;var N=Object.getOwnPropertyDescriptor;var O=Object.getOwnPropertyNames;var v=Object.prototype.hasOwnProperty;var C=(e,n,i)=>n in e?b(e,n,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[n]=i;var M=(e,n)=>{for(var i in n)b(e,i,{get:n[i],enumerable:!0})},U=(e,n,i,r)=>{if(n&&typeof n=="object"||typeof n=="function")for(let a of O(n))!v.call(e,a)&&a!==i&&b(e,a,{get:()=>n[a],enumerable:!(r=N(n,a))||r.enumerable});return e};var B=e=>U(b({},"__esModule",{value:!0}),e);var l=(e,n,i)=>C(e,typeof n!="symbol"?n+"":n,i);var $={};M($,{PlatformError:()=>h,createPageClient:()=>W});var k={OK:{http:200,retryable:!1,action:""},INVALID_ARGUMENT:{http:400,retryable:!1,action:"fix_request"},UNAUTHENTICATED:{http:401,retryable:!1,action:"ask_owner"},PERMISSION_DENIED:{http:403,retryable:!1,action:"give_up"},NOT_FOUND:{http:404,retryable:!1,action:"give_up"},ALREADY_EXISTS:{http:409,retryable:!1,action:"treat_as_done"},ABORTED:{http:409,retryable:!0,action:"retry"},FAILED_PRECONDITION:{http:412,retryable:!1,action:"give_up"},RESOURCE_EXHAUSTED:{http:429,retryable:!1,action:"retry_later"},DEADLINE_EXCEEDED:{http:504,retryable:!0,action:"retry_later"},UNAVAILABLE:{http:503,retryable:!0,action:"wait"},CANCELLED:{http:499,retryable:!1,action:"give_up"},UNIMPLEMENTED:{http:501,retryable:!1,action:"give_up"},INTERNAL:{http:500,retryable:!0,action:"retry_later"}};var h=class extends Error{constructor(i,r={},a){super(r.message||r.error||"");l(this,"name","PlatformError");l(this,"httpStatus");l(this,"status");l(this,"reason");l(this,"action");l(this,"retryable");l(this,"retryAfterMs");l(this,"detail");l(this,"appMessage");l(this,"code");l(this,"hint");l(this,"body");this.httpStatus=i,this.body=r,this.status=r.status||q(i),this.reason=r.reason||"",this.code=typeof r.code=="string"?r.code:"",this.hint=typeof r.hint=="string"?r.hint:"";let c=!r.status&&!!this.code;this.action=r.action||(c?"":k[this.status]?.action||""),this.retryable=r.retryable??k[this.status]?.retryable??!1;let p=typeof r.retry_after_ms=="number"&&r.retry_after_ms>0?r.retry_after_ms:void 0;if(p===void 0&&a){let y=Number(a);if(Number.isFinite(y))p=y*1e3;else{let g=Date.parse(a);Number.isNaN(g)||(p=Math.max(0,g-Date.now()))}}this.retryAfterMs=p,this.detail=r.detail,this.appMessage=r.app_message}};function q(e){for(let[n,i]of Object.entries(k))if(i.http===e)return n;return e>=500?"INTERNAL":e>=400?"FAILED_PRECONDITION":"OK"}var F=Symbol.for("karpoland.already_done"),j=new Set(["retry","retry_later"]);function K(e){return e.action==="give_up"||e.action==="fix_request"?!1:j.has(e.action)||e.httpStatus===429||e.httpStatus===503}var S=(e,n)=>new Promise((i,r)=>{if(n?.aborted)return r(n.reason);let a=setTimeout(i,e);n?.addEventListener("abort",()=>(clearTimeout(a),r(n.reason)),{once:!0})});function G(e,n,i){let r=new URL(e.replace(/\/+$/,"")+n);for(let[a,c]of Object.entries(i??{}))c==null||c===""||r.searchParams.set(a,String(c));return r.toString()}function D(e){let n=e.fetch??((i,r)=>globalThis.fetch(i,r));return{async request(i,r,a={}){let c=a.retry===!1||e.retry===!1?{retries:0}:{...e.retry||{},...a.retry||{}},p=c.retries??3,y=c.baseDelayMs??200,g=c.maxDelayMs??5e3,I=c.maxWaitMs??1e4,P=G(e.base,r,a.query),w=a.body instanceof Uint8Array||a.body instanceof ArrayBuffer||typeof Blob<"u"&&a.body instanceof Blob,_=a.idempotent||i==="GET"||i==="PUT"||i==="DELETE",R=!1;for(let d=0;;d++){let m={Accept:"application/json",...e.userAgent?{"User-Agent":e.userAgent}:{},...e.headers(),...a.headers};a.body!==void 0&&!w&&!m["Content-Type"]&&(m["Content-Type"]="application/json");let t;try{t=await n(P,{method:i,headers:m,body:a.body===void 0?void 0:w?a.body:JSON.stringify(a.body),signal:a.signal})}catch(A){if(a.signal?.aborted||!_||d>=p)throw A;await S(x(d,y,g),a.signal);continue}let s=await t.text(),o;if(s)try{o=JSON.parse(s)}catch{o=t.ok?s:{message:s}}if(t.ok)return o??{};let u=new h(t.status,o??{},t.headers.get("retry-after"));if(d>0&&a.doneOnRetry&&u.reason===a.doneOnRetry)return F;if(t.status===401&&e.onUnauthorized&&!R&&(R=!0,await e.onUnauthorized())){d--;continue}if(d>=p||!K(u))throw u;let f=u.retryAfterMs??x(d,y,g);if(f>I)throw u;await S(f,a.signal)}}}}function x(e,n,i){let r=Math.min(i,n*2**e);return Math.round(r/2+Math.random()*(r/2))}function L(e=""){let n=globalThis.crypto;return n?.randomUUID?e+n.randomUUID():e+Date.now().toString(36)+Math.random().toString(36).slice(2,12)}var E=e=>encodeURIComponent(String(e));var T=async(e,n)=>(await n)?.[e];function W(e={}){let n=e.window??globalThis.window,i=e.refreshBeforeMs??3e4,r=null,a,c={launch:new Set,refresh:new Set,error:new Set,"session.updated":new Set,"install.updated":new Set},p=(t,s)=>c[t].forEach(o=>o(s)),y=[],g=[],I=t=>n?.parent?.postMessage({type:t},"*"),P=()=>{if(a&&clearTimeout(a),!r)return;let t=new Date(r.expires_at).getTime()-Date.now()-i;a=setTimeout(()=>{m.refresh().catch(s=>p("error",s))},Math.max(1e3,t)),a.unref?.()},w=t=>{let s=!r;r=t,P(),p(s?"launch":"refresh",t),y.forEach(o=>o(t)),y=[],g.forEach(o=>o.resolve(t)),g=[]},_=t=>{if(!n||t.source!==n.parent)return;let s=t.data;if(s?.type==="karpo:event"&&(s.event==="session.updated"||s.event==="install.updated")){p(s.event,{event:s.event,...s.session_id?{session_id:String(s.session_id)}:{},...s.install_id?{install_id:String(s.install_id)}:{}});return}let o=t.data;!o||o.type!=="karpo:launch"||typeof o.token!="string"||w({type:"karpo:launch",token:o.token,expires_at:String(o.expires_at??""),context:o.context??{},api:String(o.api??"")})},R=()=>r?Promise.resolve(r):new Promise((t,s)=>{let o=setTimeout(()=>s(new Error("karpoland: no karpo:launch from the parent frame; is the page opened inside Karpo Land?")),e.launchTimeoutMs??15e3);y.push(u=>(clearTimeout(o),t(u)))}),d=async(t,s,o,u,f={})=>{let A=await R();return D({base:A.api,fetch:e.fetch,retry:e.retry,headers:()=>({Authorization:`Bearer ${r?.token??A.token}`}),onUnauthorized:async()=>{try{return await m.refresh(),!0}catch{return!1}}}).request(t,s,{body:o,query:u,...f})},m={ready:async()=>(await R()).context,get context(){return r?.context??null},get launch(){return r},on(t,s){return c[t].add(s),()=>c[t].delete(s)},async callTool(t,s={},o={}){let u=o.idempotencyKey??L("page-");return(await d("POST",`/tools/${E(t)}`,{args:s,session_id:o.sessionId,install_id:o.installId},void 0,{headers:{"Idempotency-Key":u},idempotent:!0})).call},sessions:{get:t=>T("session",d("GET",`/sessions/${E(t)}`)),join:(t,s={})=>d("POST",`/sessions/${E(t)}/join`,s),leave:t=>T("participant",d("POST",`/sessions/${E(t)}/leave`,{})),respond:(t,s)=>T("participant",d("POST",`/sessions/${E(t)}/respond`,{accept:s}))},boards:{get:(t,s={})=>T("board",d("GET","/boards",void 0,{ref:t,...s})),list:async(t={})=>await T("boards",d("GET","/boards",void 0,t))??[]},residents:{async get(t){let s=[...new Set(t.filter(Boolean).map(String))],o=[];for(let u=0;u<s.length;u+=100){let f=await d("GET","/residents",void 0,{ids:s.slice(u,u+100).join(",")});o.push(...f.residents??[])}return o}},refresh(){return n?.parent?new Promise((t,s)=>{let o={resolve:f=>(clearTimeout(u),t(f)),reject:s},u=setTimeout(()=>{g=g.filter(f=>f!==o),s(new Error("karpoland: the parent frame did not send a fresh launch"))},e.launchTimeoutMs??15e3);g.push(o),I("karpo:refresh")}):Promise.reject(new h(401,{status:"UNAUTHENTICATED",reason:"auth.TOKEN_INVALID",message:"no parent frame to refresh the launch token"}))},request:(t,s,o,u)=>d(t,s,o,u),destroy(){a&&clearTimeout(a),n?.removeEventListener("message",_)}};return n?.addEventListener("message",_),e.launch?w({type:"karpo:launch",...e.launch}):I("karpo:ready"),m}return B($);})();
|