@tryghost/app-sdk 0.0.0-stage → 0.1.0-alpha.1

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.
@@ -0,0 +1,1339 @@
1
+ //#region ../app-contracts/build/plain-text.js
2
+ var ALLOWED = "\\p{L}\\p{M}\\p{N}\\p{P}\\p{S}\\p{Zs}\\u200C\\u200D";
3
+ new RegExp(`^[${ALLOWED}]*$`, "u");
4
+ var NOT_PLAIN_TEXT = new RegExp(`[^${ALLOWED}]`, "gu");
5
+ /** Returns the text with the characters `isPlainText` refuses removed. */
6
+ function toPlainText(value) {
7
+ return value.replace(NOT_PLAIN_TEXT, "");
8
+ }
9
+ //#endregion
10
+ //#region ../app-contracts/build/bridge/rules.js
11
+ /**
12
+ * The bridge's rules that have no dependencies. The root entry point exports them so the SDK
13
+ * can use them without zod. The schemas in this folder build on them, so the SDK and Admin
14
+ * read a path or a refusal the same way.
15
+ *
16
+ * What Admin sends the page has no schema, because Admin builds it and never parses it. Its
17
+ * types are declared here, next to the guards the SDK checks it with. The SDK trusts Admin, so
18
+ * the guards only check shape and path containment. They turn a mismatch into a clear error
19
+ * rather than `undefined` somewhere in the app. Only the schemas check limits.
20
+ */
21
+ /** Posted by the app's page to `window.parent` once the SDK has loaded. */
22
+ var HELLO_MESSAGE_TYPE = "ghost-app:hello";
23
+ /**
24
+ * How long an app's page has to start, in milliseconds. Admin gives up on a frame this long
25
+ * after mounting it, and the SDK waits this long for Admin to start the app unless the app
26
+ * passes its own `timeout`. Long enough for a slow page on a slow connection to load and send
27
+ * its hello.
28
+ */
29
+ var START_TIMEOUT_MS = 1e4;
30
+ /**
31
+ * The methods an app may use, in uppercase: the ones the allowlist has routes for. The SDK
32
+ * uppercases what apps pass.
33
+ */
34
+ var FETCH_METHODS = [
35
+ "GET",
36
+ "POST",
37
+ "PUT",
38
+ "DELETE"
39
+ ];
40
+ /**
41
+ * Whether a request with this method may carry a body. Expects an uppercase method from
42
+ * `FETCH_METHODS`. The Admin API reads no body on a `GET`, and fetch refuses to send one.
43
+ */
44
+ function methodAllowsBody(method) {
45
+ return method !== "GET";
46
+ }
47
+ var RESERVED_REQUEST_HEADER = /^(?:cookie|authorization|x-ghost-.*|app-pragma|host|origin|referer|content-length|content-type|content-encoding|x-forwarded-.*|forwarded|x-real-ip|via)$/i;
48
+ /**
49
+ * Whether a request header is one that apps may not set, in any case. Admin refuses a request
50
+ * that sets one rather than dropping the header, so the app gets an error instead of wondering
51
+ * why the header never arrived. The browser refuses some of these anyway; they are listed here
52
+ * so that none of them relies on the browser.
53
+ */
54
+ function isReservedRequestHeader(name) {
55
+ return RESERVED_REQUEST_HEADER.test(name);
56
+ }
57
+ /**
58
+ * The messages Admin and the SDK use when they refuse an argument for the same reason, so an
59
+ * app gets the same message whichever side catches the problem. The SDK checks only for obvious
60
+ * mistakes, before anything crosses the channel; Admin's schemas check everything again.
61
+ */
62
+ var ARGUMENT_MESSAGES = {
63
+ fetchPath: "Expected an Admin API path such as /posts/, not a URL",
64
+ fetchMethod: `Expected a method of: ${FETCH_METHODS.join(", ")}`,
65
+ fetchBody: "Expected no body on a GET request",
66
+ reservedHeader: (name) => `Expected no ${name.toLowerCase()} header, which only Admin sets`,
67
+ jsonBody: "Expected the body as JSON text",
68
+ appPath: "Expected a path within the app, starting with a single /",
69
+ pathMove: "Expected a move of push or replace",
70
+ place: "Expected a place such as { post: { id } }, { page: { id } }, { member: { id } } or { apps: true }"
71
+ };
72
+ /**
73
+ * The codes a refused call carries across the channel. The structured clone that carries an
74
+ * error keeps only its message, so the refusing side puts the code at the start of the
75
+ * message, as in `blocked: Apps can't use GET /db/`, and the other side parses it back out. Codes
76
+ * are only ever added: an SDK that doesn't know a code treats the whole message as a generic
77
+ * refusal.
78
+ *
79
+ * The host codes, which Admin refuses the page's calls with:
80
+ *
81
+ * - `session_ended`: the session is over; the page is about to be replaced.
82
+ * - `invalid_argument`: an argument Admin does not take.
83
+ * - `invalid_path`: a path that is not an Admin API path or a route within the app, or one
84
+ * the Admin API only responds to with a redirect, such as a path without its trailing `/`.
85
+ * - `blocked`: a request the allowlist doesn't allow, or a write it refuses.
86
+ * - `network_error`: Admin could not reach its own API.
87
+ * - `rejected`: anything else; the detail says why.
88
+ */
89
+ var HOST_ERROR_CODES = [
90
+ "session_ended",
91
+ "invalid_argument",
92
+ "invalid_path",
93
+ "blocked",
94
+ "network_error",
95
+ "rejected"
96
+ ];
97
+ [...HOST_ERROR_CODES];
98
+ var CODED_MESSAGE = /^([a-z_]+): ([\s\S]*)$/;
99
+ /**
100
+ * Builds the message a refusal crosses the channel as: `code: detail`. Each side should pass
101
+ * only its own codes; typing its refusals as `HostErrorCode` or `AppErrorCode` enforces that.
102
+ */
103
+ function encodeBridgeError(code, detail) {
104
+ return `${code}: ${detail}`;
105
+ }
106
+ /**
107
+ * Reads the code and detail back from a refusal's `code: detail` message. Takes the codes the
108
+ * other side may send: `HOST_ERROR_CODES` for a refusal from Admin, and `APP_ERROR_CODES` for
109
+ * one from the page. Returns `undefined` for a message that doesn't start with one of them.
110
+ */
111
+ function decodeBridgeError(message, codes) {
112
+ const [, code = "", detail = ""] = CODED_MESSAGE.exec(message) ?? [];
113
+ return codes.includes(code) ? {
114
+ code,
115
+ detail
116
+ } : void 0;
117
+ }
118
+ var THEME_MODES = ["light", "dark"];
119
+ var CONTROL_CHARACTER = /\p{Cc}/u;
120
+ /**
121
+ * Whether a value is a path that stays within the base it is resolved against, rather than
122
+ * escaping it. It must start with a single `/`, so it can't carry a scheme or be read as
123
+ * `//host`. It must not contain `\`, which URL parsers read as `/`, or any control character.
124
+ */
125
+ function isContainedPath(value) {
126
+ return typeof value === "string" && value.startsWith("/") && !value.startsWith("//") && !value.includes("\\") && !CONTROL_CHARACTER.test(value);
127
+ }
128
+ var APP_PATH_BASE = "https://app.invalid";
129
+ /**
130
+ * Returns an app path in the URL parser's normalised form, the one form Admin and the SDK
131
+ * store it in. `.` and `..` are resolved within the app, so a path can never climb out of it.
132
+ * Characters that need escaping are escaped once, so a path the app reported compares equal to
133
+ * the same path read back from Admin's URL. `/search?q=a b` becomes `/search?q=a%20b`, and
134
+ * `/x/../episodes/1` becomes `/episodes/1`.
135
+ *
136
+ * Expects a path that `isContainedPath` accepts; anything else may not be a path within the
137
+ * app at all. `AppPathSchema` already returns this form, so Admin never calls this directly.
138
+ * The SDK, which doesn't load zod, does.
139
+ */
140
+ function normaliseAppPath(path) {
141
+ const url = new URL(path, APP_PATH_BASE);
142
+ return `${url.pathname}${url.search}${url.hash}`;
143
+ }
144
+ /** An object, or an array: anything whose fields can be read. */
145
+ function isRecord(value) {
146
+ return typeof value === "object" && value !== null;
147
+ }
148
+ function hasStrings(value, keys) {
149
+ return isRecord(value) && keys.every((key) => typeof value[key] === "string");
150
+ }
151
+ function isTheme(value) {
152
+ return hasStrings(value, ["accent_color"]) && THEME_MODES.includes(value.mode);
153
+ }
154
+ function isStartContext(value) {
155
+ return isRecord(value) && hasStrings(value.site, [
156
+ "url",
157
+ "title",
158
+ "timezone",
159
+ "locale"
160
+ ]) && hasStrings(value.user, ["id", "role"]) && isTheme(value.theme) && isRecord(value.session) && Number.isSafeInteger(value.session.revision) && value.session.revision >= 0 && isContainedPath(value.path);
161
+ }
162
+ function isConnectMessage(value) {
163
+ return isRecord(value) && value.type === "ghost-app:connect" && Array.isArray(value.exports) && value.exports.every((name) => typeof name === "string");
164
+ }
165
+ function isFetchResponse(value) {
166
+ return isRecord(value) && Number.isSafeInteger(value.status) && value.status >= 200 && value.status <= 599 && typeof value.statusText === "string" && isRecord(value.headers) && !Array.isArray(value.headers) && Object.values(value.headers).every((header) => typeof header === "string") && typeof value.body === "string";
167
+ }
168
+ //#endregion
169
+ //#region src/errors.ts
170
+ /** The only error type the SDK rejects with, so an app can branch on `code`. */
171
+ var GhostAppError = class extends Error {
172
+ code;
173
+ constructor(code, message, options) {
174
+ super(message, options);
175
+ this.name = "GhostAppError";
176
+ this.code = code;
177
+ }
178
+ };
179
+ /**
180
+ * Converts whatever a call to Admin rejected with into a `GhostAppError`, with the code Admin
181
+ * gave or, if there is none, `rejected` with Admin's message.
182
+ */
183
+ function fromHostError(error, operation) {
184
+ const message = typeof error === "object" && error !== null && "message" in error ? String(error.message) : void 0;
185
+ if (message === void 0) return new GhostAppError("rejected", `Ghost refused ${operation}`, { cause: error });
186
+ const coded = decodeBridgeError(message, HOST_ERROR_CODES);
187
+ if (coded) return new GhostAppError(coded.code, coded.detail, { cause: error });
188
+ return new GhostAppError("rejected", message, { cause: error });
189
+ }
190
+ function invalidArgument(message) {
191
+ return new GhostAppError("invalid_argument", message);
192
+ }
193
+ function invalidPath(message) {
194
+ return new GhostAppError("invalid_path", message);
195
+ }
196
+ function unsupported(operation) {
197
+ return new GhostAppError("unsupported", `This site's Ghost doesn't support ${operation} yet`);
198
+ }
199
+ function sessionEnded() {
200
+ return new GhostAppError("session_ended", "The session with Ghost has ended");
201
+ }
202
+ //#endregion
203
+ //#region node_modules/@quilted/threads/build/esm/constants.mjs
204
+ var SERIALIZE_METHOD = Symbol.for("quilt.threads.serialize");
205
+ var TRANSFERABLE = Symbol.for("quilt.threads.transferable");
206
+ //#endregion
207
+ //#region node_modules/@quilted/events/build/esm/abort/NestedAbortController.mjs
208
+ /**
209
+ * An `AbortController` that will automatically abort when any of
210
+ * its "parent" `AbortController`s abort. This is useful for when
211
+ * you have nested asynchronous operations that may abort independently.
212
+ * The `AbortController` can also be independently aborted.
213
+ *
214
+ * To associate the parent `AbortController`s, pass their signals
215
+ * as arguments to the constructor.
216
+ *
217
+ * @example
218
+ * import {NestedAbortController} from '@shopify/events';
219
+ *
220
+ * const parent = new AbortController();
221
+ * const nested = new NestedAbortController(parent.signal);
222
+ *
223
+ * parent.abort();
224
+ * nested.signal.aborted; // true
225
+ */
226
+ var NestedAbortController = class extends AbortController {
227
+ constructor(...parents) {
228
+ super();
229
+ const abortedSignal = parents.find((signal) => signal.aborted);
230
+ if (abortedSignal) this.abort(abortedSignal.reason);
231
+ else {
232
+ const abort = (event) => this.abort(event.target.reason);
233
+ const options = { signal: this.signal };
234
+ for (const signal of parents) signal.addEventListener("abort", abort, options);
235
+ }
236
+ }
237
+ };
238
+ //#endregion
239
+ //#region node_modules/@quilted/threads/build/esm/errors.mjs
240
+ var ThreadClosedError = class extends Error {
241
+ constructor() {
242
+ super("You attempted to call a function on a closed thread.");
243
+ }
244
+ };
245
+ //#endregion
246
+ //#region node_modules/@quilted/threads/build/esm/nanoid.mjs
247
+ var a = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";
248
+ function nanoid(e = 21) {
249
+ let t = "", r = crypto.getRandomValues(new Uint8Array(e));
250
+ for (let n = 0; n < e; n++) t += a[63 & r[n]];
251
+ return t;
252
+ }
253
+ //#endregion
254
+ //#region node_modules/@quilted/threads/build/esm/functions/ThreadFunctionsAutomatic.mjs
255
+ /**
256
+ * A strategy for managing functions across threads that automatically releases
257
+ * functions when they are no longer needed. This is done by deserializing functions
258
+ * into a proxy that can be called, and wrapping that proxy in a `FinalizationRegistry`,
259
+ * which allows us to send a message to the parent thread when the function is no
260
+ * longer used.
261
+ *
262
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry
263
+ */
264
+ var ThreadFunctionsAutomatic = class {
265
+ #functionsToId = (() => /* @__PURE__ */ new Map())();
266
+ #idsToFunction = (() => /* @__PURE__ */ new Map())();
267
+ #idsToProxy = (() => /* @__PURE__ */ new Map())();
268
+ #finalization = (() => /* @__PURE__ */ new WeakMap())();
269
+ get(id) {
270
+ return this.#idsToFunction.get(id);
271
+ }
272
+ release(id) {
273
+ const func = this.#idsToFunction.get(id);
274
+ if (func) {
275
+ this.#idsToFunction.delete(id);
276
+ this.#functionsToId.delete(func);
277
+ }
278
+ return Boolean(func);
279
+ }
280
+ serialize(func) {
281
+ let id = this.#functionsToId.get(func);
282
+ if (id == null) {
283
+ id = nanoid();
284
+ this.#functionsToId.set(func, id);
285
+ this.#idsToFunction.set(id, func);
286
+ }
287
+ return id;
288
+ }
289
+ deserialize(id, thread) {
290
+ let proxy = this.#idsToProxy.get(id)?.deref();
291
+ if (proxy) return proxy;
292
+ proxy = (...args) => {
293
+ if (!this.#idsToProxy.has(id)) throw new Error("You attempted to call a function that was already revoked.");
294
+ return thread.call((callID, args, transferable) => {
295
+ thread.messages.send([
296
+ 3,
297
+ callID,
298
+ id,
299
+ args
300
+ ], transferable);
301
+ }, args);
302
+ };
303
+ this.#finalizationRegistry(thread)?.register(proxy, id);
304
+ this.#idsToProxy.set(id, new WeakRef(proxy));
305
+ return proxy;
306
+ }
307
+ #finalizationRegistry(thread) {
308
+ let finalization = this.#finalization.get(thread);
309
+ if (typeof FinalizationRegistry === "undefined") return;
310
+ if (!finalization) {
311
+ finalization = new FinalizationRegistry((id) => {
312
+ thread.messages.send([5, id]);
313
+ });
314
+ this.#finalization.set(thread, finalization);
315
+ }
316
+ return finalization;
317
+ }
318
+ };
319
+ //#endregion
320
+ //#region node_modules/@quilted/threads/build/esm/serialization/shared.mjs
321
+ function isIterator(value) {
322
+ return value != null && (Symbol.asyncIterator in value || Symbol.iterator in value) && typeof value.next === "function";
323
+ }
324
+ function isBasicObject(value) {
325
+ if (value == null || typeof value !== "object") return false;
326
+ const prototype = Object.getPrototypeOf(value);
327
+ return prototype == null || prototype === Object.prototype;
328
+ }
329
+ //#endregion
330
+ //#region node_modules/@quilted/threads/build/esm/serialization/ThreadSerializationStructuredClone.mjs
331
+ var FUNCTION = "_@f";
332
+ var ASYNC_ITERATOR = "_@i";
333
+ /**
334
+ * A thread encoder that can transfer supports a wide variety of JavaScript types by
335
+ * converting them to a format that the [`structuredClone`](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm)
336
+ * algorithm can process. This
337
+ *
338
+ * Additionally, this encoder will convert functions into a JSON-friendly representation.
339
+ * These functions will use a manual memory management technique to ensure they can be
340
+ * garbage collected by default, but can be configured to use a `WeakRef`-based automatic
341
+ * memory management system by setting the `garbageCollection: 'weak-ref'` option.
342
+ */
343
+ var ThreadSerializationStructuredClone = class {
344
+ #customSerializer;
345
+ #customDeserializer;
346
+ constructor(options) {
347
+ this.#customSerializer = options?.serialize;
348
+ this.#customDeserializer = options?.deserialize;
349
+ }
350
+ /**
351
+ * Serializes a value into a structured cloning-compatible format that can be transferred between threads.
352
+ */
353
+ serialize(value, thread, transferable) {
354
+ return this.#serializeInternal(value, thread, transferable);
355
+ }
356
+ #serializeInternal(value, thread, transferable, seen = /* @__PURE__ */ new Map(), isApplyingDefault = false) {
357
+ if (value == null) return value;
358
+ if (seen.has(value)) return seen.get(value);
359
+ seen.set(value, void 0);
360
+ if (typeof value === "object") {
361
+ if (this.#customSerializer && !isApplyingDefault) {
362
+ const customValue = this.#customSerializer(value, (value) => this.#serializeInternal(value, thread, transferable, seen, true), thread, transferable);
363
+ if (customValue !== void 0) {
364
+ seen.set(value, customValue);
365
+ return customValue;
366
+ }
367
+ }
368
+ if (value[TRANSFERABLE]) {
369
+ transferable?.push(value);
370
+ seen.set(value, value);
371
+ return value;
372
+ }
373
+ const serializeValue = (value) => {
374
+ return this.#serializeInternal(value, thread, transferable, seen);
375
+ };
376
+ if (typeof value[SERIALIZE_METHOD] === "function") {
377
+ const result = value[SERIALIZE_METHOD]({ serialize: serializeValue });
378
+ seen.set(value, result);
379
+ return result;
380
+ }
381
+ if (Array.isArray(value)) {
382
+ const result = value.map((item) => serializeValue(item));
383
+ seen.set(value, result);
384
+ return result;
385
+ }
386
+ if (value instanceof Map) {
387
+ const entries = [...value.entries()].map(([key, value]) => {
388
+ return [serializeValue(key), serializeValue(value)];
389
+ });
390
+ const result = new Map(entries);
391
+ seen.set(value, result);
392
+ return result;
393
+ }
394
+ if (value instanceof Set) {
395
+ const entries = [...value].map((entry) => serializeValue(entry));
396
+ const result = new Set(entries);
397
+ seen.set(value, result);
398
+ return result;
399
+ }
400
+ const valueIsIterator = isIterator(value);
401
+ if (isBasicObject(value) || valueIsIterator) {
402
+ const result = {};
403
+ for (const key of Object.keys(value)) result[key] = serializeValue(value[key]);
404
+ if (valueIsIterator) {
405
+ result.next ??= serializeValue(value.next.bind(value));
406
+ result.return ??= serializeValue(value.return.bind(value));
407
+ result.throw ??= serializeValue(value.throw.bind(value));
408
+ result[ASYNC_ITERATOR] = true;
409
+ }
410
+ seen.set(value, result);
411
+ return result;
412
+ }
413
+ }
414
+ if (typeof value === "function") {
415
+ const serialized = thread.functions.serialize(value, thread, transferable);
416
+ const result = { [FUNCTION]: serialized };
417
+ seen.set(value, result);
418
+ return result;
419
+ }
420
+ seen.set(value, value);
421
+ return value;
422
+ }
423
+ /**
424
+ * Deserializes a structured cloning-compatible value from another thread.
425
+ */
426
+ deserialize(value, thread) {
427
+ return this.#deserializeInternal(value, thread);
428
+ }
429
+ #deserializeInternal(value, thread, isApplyingDefault = false) {
430
+ if (value == null) return value;
431
+ if (typeof value === "object") {
432
+ if (this.#customDeserializer && !isApplyingDefault) {
433
+ const customValue = this.#customDeserializer(value, (value) => this.#deserializeInternal(value, thread, true), thread);
434
+ if (customValue !== void 0) return customValue;
435
+ }
436
+ if (value == null) return value;
437
+ if (Array.isArray(value)) return value.map((value) => this.#deserializeInternal(value, thread));
438
+ if (value instanceof Map) return new Map([...value].map(([key, value]) => [this.#deserializeInternal(key, thread), this.#deserializeInternal(value, thread)]));
439
+ if (value instanceof Set) return new Set([...value].map((entry) => this.#deserializeInternal(entry, thread)));
440
+ if (FUNCTION in value) return thread.functions.deserialize(value[FUNCTION], thread);
441
+ if (!isBasicObject(value)) return value;
442
+ const result = {};
443
+ for (const key of Object.keys(value)) if (key === ASYNC_ITERATOR) result[Symbol.asyncIterator] = () => result;
444
+ else result[key] = this.#deserializeInternal(value[key], thread);
445
+ return result;
446
+ }
447
+ return value;
448
+ }
449
+ };
450
+ //#endregion
451
+ //#region node_modules/@quilted/threads/build/esm/Thread.mjs
452
+ /**
453
+ * An object that can serialize and deserialize values communicated between two threads.
454
+ */
455
+ /**
456
+ * An object that can serialize and deserialize values communicated between two threads.
457
+ */
458
+ /**
459
+ * Options to customize the creation of a `ThreadSerialization` instance.
460
+ */
461
+ /**
462
+ * Options to customize the creation of a `Thread` instance.
463
+ */
464
+ /**
465
+ * An object backing a `Thread` that provides the message-passing interface
466
+ * that allows communication to flow between environments. This message-passing
467
+ * interface is based on the [`postMessage` interface](https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage),
468
+ * which is easily adaptable to many JavaScript objects and environments.
469
+ */
470
+ /**
471
+ * A map of messages that can be sent between threads.
472
+ */
473
+ /**
474
+ * The possible data payloads that can be transferred between threads.
475
+ */
476
+ /**
477
+ * A helper type that extracts all callable methods that can be safely proxied
478
+ * between threads; that is, ones which return a promise or async iterator.
479
+ */
480
+ /**
481
+ * A thread represents a target JavaScript environment that exposes a set
482
+ * of callable, asynchronous methods. The thread takes care of automatically
483
+ * encoding and decoding its arguments and return values, so you can interact
484
+ * with it as if its methods were implemented in the same environment as your
485
+ * own code.
486
+ */
487
+ var Thread = class {
488
+ /**
489
+ * An object that exposes the methods that can be called on the paired thread.
490
+ * This object will automatically encode and decode arguments and return values
491
+ * as necessary.
492
+ */
493
+ /**
494
+ * An object that exposes the methods that can be called on this thread by the
495
+ * paired thread. To set these methods, pass the `exports` option when creating
496
+ * a new `Thread`.
497
+ */
498
+ /**
499
+ * An object that provides the message-passing interface that allows communication
500
+ * to flow between environments.
501
+ */
502
+ /**
503
+ * An object that manages how functions are proxied between threads.
504
+ */
505
+ /**
506
+ * An object that manages how values are serialized and deserialized between threads.
507
+ */
508
+ /**
509
+ * An `AbortSignal` that indicates whether the communication channel is still open.
510
+ */
511
+ get signal() {
512
+ return this.#abort.signal;
513
+ }
514
+ /**
515
+ * A boolean indicating whether the communication channel is still open.
516
+ */
517
+ get closed() {
518
+ return this.#abort.signal.aborted;
519
+ }
520
+ #abort;
521
+ #idsToResolver = (() => /* @__PURE__ */ new Map())();
522
+ constructor(messages, { imports, exports, functions = new ThreadFunctionsAutomatic(), serialization = new ThreadSerializationStructuredClone(), signal } = {}) {
523
+ this.messages = messages;
524
+ this.#abort = signal ? new NestedAbortController(signal) : new AbortController();
525
+ this.exports = exports ?? {};
526
+ this.imports = createThreadImports(this.#handlerForCall.bind(this), imports);
527
+ this.functions = functions;
528
+ this.serialization = serialization;
529
+ this.functions.start?.(this);
530
+ this.serialization.start?.(this);
531
+ this.signal.addEventListener("abort", () => {
532
+ for (const id of this.#idsToResolver.keys()) this.#resolveCall(id, void 0, new ThreadClosedError());
533
+ this.#idsToResolver.clear();
534
+ }, { once: true });
535
+ messages.listen(async (rawData) => {
536
+ if (!(Array.isArray(rawData) && typeof rawData[0] === "number")) return;
537
+ const data = rawData;
538
+ switch (data[0]) {
539
+ case 1: {
540
+ const [, id, property, args] = data;
541
+ const func = this.exports[property] ?? (() => {
542
+ throw new Error(`No '${property}' method is exported from this thread`);
543
+ });
544
+ await this.#callLocal(func, args, (value, error, transferable) => {
545
+ this.messages.send([
546
+ 2,
547
+ id,
548
+ value,
549
+ error
550
+ ], transferable);
551
+ });
552
+ break;
553
+ }
554
+ case 3: {
555
+ const [, callID, funcID, args] = data;
556
+ const func = this.functions.get(funcID, this) ?? missingThreadFunction;
557
+ await this.#callLocal(func, args, (value, error, transferable) => {
558
+ this.messages.send([
559
+ 4,
560
+ callID,
561
+ value,
562
+ error
563
+ ], transferable);
564
+ });
565
+ break;
566
+ }
567
+ case 2:
568
+ case 4:
569
+ this.#resolveCall(...data.slice(1));
570
+ break;
571
+ case 5: {
572
+ const id = data[1];
573
+ this.functions.release(id, this);
574
+ break;
575
+ }
576
+ }
577
+ }, { signal: this.signal });
578
+ }
579
+ /**
580
+ * Closes the communication channel between the two threads. This will prevent
581
+ * any further communication between the threads, and will clean up any memory
582
+ * associated with in-progress communication. It will also reject any inflight
583
+ * function calls between threads with a `ThreadClosedError`.
584
+ */
585
+ close() {
586
+ this.#abort.abort();
587
+ }
588
+ /**
589
+ * Requests that the thread provide the context needed to make a function
590
+ * call between threads. You provide this method a function to call and the
591
+ * unserialized arguments you wish to call it with, and the thread will call
592
+ * the function you provided with a serialized call ID, the serialized arguments,
593
+ * and any transferable objects that need to be passed between threads.
594
+ */
595
+ call(func, args) {
596
+ if (this.closed) return Promise.reject(new ThreadClosedError());
597
+ const transferable = [];
598
+ const serialized = this.serialization.serialize(args, this, transferable);
599
+ const id = nanoid();
600
+ const done = this.#waitForResult(id);
601
+ func(id, serialized, transferable);
602
+ return done;
603
+ }
604
+ async #callLocal(func, args, withResult) {
605
+ try {
606
+ const result = this.functions.call ? await this.functions.call(func, args, this) : await func(...this.serialization.deserialize(args, this));
607
+ const transferable = [];
608
+ withResult(this.serialization.serialize(result, this, transferable), void 0, transferable);
609
+ } catch (error) {
610
+ withResult(void 0, this.serialization.serialize(error, this));
611
+ }
612
+ }
613
+ #handlerForCall(property) {
614
+ return (...args) => {
615
+ try {
616
+ if (typeof property !== "string" && typeof property !== "number") throw new Error(`Can’t call a symbol method on a thread: ${property.toString()}`);
617
+ return this.call((id, serializedArgs, transferable) => {
618
+ this.messages.send([
619
+ 1,
620
+ id,
621
+ property,
622
+ serializedArgs
623
+ ], transferable);
624
+ }, args);
625
+ } catch (error) {
626
+ return Promise.reject(error);
627
+ }
628
+ };
629
+ }
630
+ #resolveCall(...args) {
631
+ const callID = args[0];
632
+ const resolver = this.#idsToResolver.get(callID);
633
+ if (resolver) {
634
+ resolver(...args);
635
+ this.#idsToResolver.delete(callID);
636
+ }
637
+ }
638
+ #waitForResult(id) {
639
+ const promise = new Promise((resolve, reject) => {
640
+ this.#idsToResolver.set(id, (_, value, error) => {
641
+ if (error == null) resolve(this.serialization.deserialize(value, this));
642
+ else reject(this.serialization.deserialize(error, this));
643
+ });
644
+ });
645
+ Object.defineProperty(promise, Symbol.asyncIterator, { async *value() {
646
+ const result = await promise;
647
+ Object.defineProperty(result, Symbol.asyncIterator, { value: () => result });
648
+ yield* result;
649
+ } });
650
+ return promise;
651
+ }
652
+ };
653
+ function createThreadImports(handlerForImport, imported) {
654
+ let call;
655
+ if (imported == null) {
656
+ if (typeof Proxy !== "function") throw new Error(`You must pass an array of callable methods in environments without Proxies.`);
657
+ const cache = /* @__PURE__ */ new Map();
658
+ call = new Proxy({}, { get(_target, property) {
659
+ if (cache.has(property)) return cache.get(property);
660
+ const handler = handlerForImport(property);
661
+ cache.set(property, handler);
662
+ return handler;
663
+ } });
664
+ } else {
665
+ call = {};
666
+ for (const method of imported) Object.defineProperty(call, method, {
667
+ value: handlerForImport(method),
668
+ writable: false,
669
+ configurable: true,
670
+ enumerable: true
671
+ });
672
+ }
673
+ return call;
674
+ }
675
+ function missingThreadFunction() {
676
+ throw new Error(`You attempted to call a function that is not stored. It may have already been released.`);
677
+ }
678
+ //#endregion
679
+ //#region node_modules/@quilted/threads/build/esm/threads/ThreadMessagePort.mjs
680
+ /**
681
+ * Creates a thread from a `MessagePort` instance in the browser.
682
+ *
683
+ * @see https://developer.mozilla.org/en-US/docs/Web/API/MessagePort
684
+ *
685
+ * @example
686
+ * import {ThreadMessagePort} from '@quilted/threads';
687
+ *
688
+ * const channel = new MessageChannel();
689
+ *
690
+ * const threadOne = new ThreadMessagePort(channel.port1);
691
+ * const threadTwo = new ThreadMessagePort(channel.port2, {
692
+ * exports: {
693
+ * async sendMessage(message) {
694
+ * console.log(message);
695
+ * },
696
+ * },
697
+ * });
698
+ *
699
+ * channel.port1.start();
700
+ * channel.port2.start();
701
+ *
702
+ * await threadOne.imports.sendMessage('Hello world!');
703
+ */
704
+ var ThreadMessagePort = class ThreadMessagePort extends Thread {
705
+ /**
706
+ * Starts a thread wrapped around a `MessagePort` object, and returns the imports
707
+ * of the thread.
708
+ *
709
+ * @example
710
+ * ```ts
711
+ * import {ThreadMessagePort} from '@quilted/threads';
712
+ *
713
+ * const channel = new MessageChannel();
714
+ *
715
+ * ThreadMessagePort.export(channel.port1, {
716
+ * async getMessage() {
717
+ * return 'Hello, world!';
718
+ * },
719
+ * });
720
+ *
721
+ * const {getMessage} = ThreadMessagePort.import(channel.port2);
722
+ *
723
+ * channel.port1.start();
724
+ * channel.port2.start();
725
+ *
726
+ * const message = await getMessage(); // 'Hello, world!'
727
+ * ```
728
+ */
729
+ static import(port, options) {
730
+ return new ThreadMessagePort(port, options).imports;
731
+ }
732
+ /**
733
+ * Starts a thread wrapped around a `MessagePort` object, providing the second
734
+ * argument as the exports of the thread.
735
+ *
736
+ * @example
737
+ * ```ts
738
+ * import {ThreadMessagePort} from '@quilted/threads';
739
+ *
740
+ * const channel = new MessageChannel();
741
+ *
742
+ * ThreadMessagePort.export(channel.port1, {
743
+ * async getMessage() {
744
+ * return 'Hello, world!';
745
+ * },
746
+ * });
747
+ *
748
+ * const {getMessage} = ThreadMessagePort.import(channel.port2);
749
+ *
750
+ * channel.port1.start();
751
+ * channel.port2.start();
752
+ *
753
+ * const message = await getMessage(); // 'Hello, world!'
754
+ * ```
755
+ */
756
+ static export(port, exports, options) {
757
+ new ThreadMessagePort(port, {
758
+ ...options,
759
+ exports
760
+ });
761
+ }
762
+ constructor(port, options) {
763
+ super(portToMessageTarget(port), options);
764
+ this.port = port;
765
+ }
766
+ };
767
+ function portToMessageTarget(port) {
768
+ return {
769
+ send(...args) {
770
+ port.postMessage(...args);
771
+ },
772
+ listen(listener, { signal }) {
773
+ port.addEventListener("message", (event) => {
774
+ listener(event.data);
775
+ }, { signal });
776
+ }
777
+ };
778
+ }
779
+ //#endregion
780
+ //#region src/fetch.ts
781
+ var JSON_BODY = "Expected a body that can be sent as JSON";
782
+ var NULL_BODY_STATUSES = /* @__PURE__ */ new Set([
783
+ 204,
784
+ 205,
785
+ 304
786
+ ]);
787
+ function isJsonBody(value) {
788
+ if (Array.isArray(value)) return true;
789
+ if (!isRecord(value)) return false;
790
+ const prototype = Object.getPrototypeOf(value);
791
+ return prototype === Object.prototype || prototype === null;
792
+ }
793
+ function toJson(body) {
794
+ let json;
795
+ try {
796
+ json = JSON.stringify(body);
797
+ } catch (error) {
798
+ throw new GhostAppError("invalid_argument", JSON_BODY, { cause: error });
799
+ }
800
+ if (json === void 0) throw invalidArgument(JSON_BODY);
801
+ return json;
802
+ }
803
+ function toHeaders(init) {
804
+ let headers;
805
+ try {
806
+ headers = new Headers(init);
807
+ } catch (error) {
808
+ throw new GhostAppError("invalid_argument", "Expected headers with valid names and values", { cause: error });
809
+ }
810
+ const entries = [...headers.entries()];
811
+ const reserved = entries.find(([name]) => isReservedRequestHeader(name));
812
+ if (reserved) throw invalidArgument(ARGUMENT_MESSAGES.reservedHeader(reserved[0]));
813
+ return Object.fromEntries(entries);
814
+ }
815
+ /**
816
+ * Converts `fetch(path, init)` into the plain request Admin accepts. Only obvious mistakes are
817
+ * refused here, using the same rules Admin applies; Admin checks everything again.
818
+ */
819
+ function toFetchRequest(path, init = {}) {
820
+ if (!isContainedPath(path)) throw invalidPath(ARGUMENT_MESSAGES.fetchPath);
821
+ if (typeof init !== "object" || init === null) throw invalidArgument("Expected options such as { method, headers, body }");
822
+ const { method: given = "GET" } = init;
823
+ const method = typeof given === "string" ? given.toUpperCase() : given;
824
+ if (!FETCH_METHODS.includes(method)) throw invalidArgument(ARGUMENT_MESSAGES.fetchMethod);
825
+ const headers = toHeaders(init.headers);
826
+ const request = {
827
+ path,
828
+ method
829
+ };
830
+ if (init.body !== void 0 && init.body !== null) {
831
+ if (!methodAllowsBody(method)) throw invalidArgument(ARGUMENT_MESSAGES.fetchBody);
832
+ if (typeof init.body === "string") request.body = init.body;
833
+ else if (isJsonBody(init.body)) request.body = toJson(init.body);
834
+ else throw invalidArgument("Expected the body as text, or as an object or array to send as JSON");
835
+ }
836
+ if (Object.keys(headers).length > 0) request.headers = headers;
837
+ return request;
838
+ }
839
+ var UNREADABLE_ANSWER = "Ghost answered with a response this SDK doesn't understand";
840
+ /** Rebuilds Admin's response as the `Response` the app would have got from `fetch`. */
841
+ function toResponse(answer) {
842
+ if (!isFetchResponse(answer)) throw new GhostAppError("rejected", UNREADABLE_ANSWER);
843
+ try {
844
+ return new Response(NULL_BODY_STATUSES.has(answer.status) ? null : answer.body, {
845
+ status: answer.status,
846
+ statusText: answer.statusText,
847
+ headers: answer.headers
848
+ });
849
+ } catch (error) {
850
+ throw new GhostAppError("rejected", UNREADABLE_ANSWER, { cause: error });
851
+ }
852
+ }
853
+ //#endregion
854
+ //#region src/history.ts
855
+ /**
856
+ * The page's route: the path, query and fragment of its URL, in the normalised form Admin
857
+ * stores app paths in.
858
+ */
859
+ function currentRoute() {
860
+ const { pathname, search, hash } = window.location;
861
+ return normaliseAppPath(`${pathname}${search}${hash}`);
862
+ }
863
+ /** Whether a node is an HTML or SVG link, which the browser follows when it's clicked. */
864
+ function isLink(node) {
865
+ return (node instanceof HTMLAnchorElement || node instanceof SVGElement && node.localName === "a") && node.hasAttribute("href");
866
+ }
867
+ /**
868
+ * Makes Admin the owner of the page's history. A frame's history entries are part of the tab's,
869
+ * and browsers keep them in ways Admin can't follow: Chromium and WebKit keep a removed frame's
870
+ * entries, which left back steps that did nothing once the app's page opened again, and WebKit
871
+ * applies Admin's replace after a frame's push to the entry before it. So the frame keeps a
872
+ * single entry, and Admin keeps one for each of the app's moves.
873
+ *
874
+ * - `history.pushState` and `history.replaceState` replace the frame's entry, then report the
875
+ * move to Admin as a push or a replace, which is how Admin records it. A move to the route the
876
+ * page is already on isn't reported, so Admin never gets an entry that changes nothing.
877
+ * - A click on a link to the app's own origin, which a router hasn't already handled, is reported
878
+ * as a push, and the page then loads the link's address in place of its own entry. A link that
879
+ * opens elsewhere (a `target`, `download`, or a modifier key) is left alone.
880
+ * - When Admin moves the page, `follow` replaces the frame's entry and dispatches `popstate`.
881
+ *
882
+ * Not intercepted: a form that posts adds one entry of the frame's own, and so do a change to the
883
+ * fragment through `location.hash` and the Navigation API, which have added the entry before
884
+ * any event says so.
885
+ */
886
+ function watchHistory(moved, load = (url) => window.location.replace(url)) {
887
+ const { history } = window;
888
+ const { pushState, replaceState } = history;
889
+ let route = currentRoute();
890
+ const states = /* @__PURE__ */ new Map([[route, history.state]]);
891
+ const report = (move) => {
892
+ const next = currentRoute();
893
+ states.set(next, history.state);
894
+ if (next !== route) {
895
+ route = next;
896
+ moved(next, move);
897
+ }
898
+ };
899
+ const push = (data, unused, url) => {
900
+ replaceState.call(history, data, unused, url);
901
+ report("push");
902
+ };
903
+ const replace = (data, unused, url) => {
904
+ replaceState.call(history, data, unused, url);
905
+ report("replace");
906
+ };
907
+ history.pushState = push;
908
+ history.replaceState = replace;
909
+ const onClick = (event) => {
910
+ if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
911
+ const link = event.composedPath().find(isLink);
912
+ const target = link?.getAttribute("target") ?? "";
913
+ if (!link || link.hasAttribute("download") || target !== "" && target !== "_self") return;
914
+ const url = new URL(link.getAttribute("href"), document.baseURI);
915
+ if (url.origin !== window.location.origin) return;
916
+ event.preventDefault();
917
+ const go = () => load(url.href);
918
+ const next = normaliseAppPath(`${url.pathname}${url.search}${url.hash}`);
919
+ if (next === route) {
920
+ go();
921
+ return;
922
+ }
923
+ route = next;
924
+ moved(next, "push").then(go, go);
925
+ };
926
+ document.addEventListener("click", onClick);
927
+ return {
928
+ follow(path) {
929
+ route = path;
930
+ const state = states.get(path) ?? null;
931
+ replaceState.call(history, state, "", path);
932
+ window.dispatchEvent(new PopStateEvent("popstate", { state }));
933
+ },
934
+ stop() {
935
+ if (history.pushState === push) history.pushState = pushState;
936
+ if (history.replaceState === replace) history.replaceState = replaceState;
937
+ document.removeEventListener("click", onClick);
938
+ }
939
+ };
940
+ }
941
+ //#endregion
942
+ //#region src/title.ts
943
+ /**
944
+ * Trims a title to what Admin accepts, without splitting a character in two. Admin refuses a
945
+ * title containing a character that reorders or hides text, so the SDK drops those characters
946
+ * rather than losing the whole title: a right-to-left title often contains a direction mark.
947
+ */
948
+ function clampTitle(title) {
949
+ const trimmed = toPlainText(title).trim();
950
+ if (trimmed.length <= 200) return trimmed;
951
+ const end = /[\uD800-\uDBFF]/.test(trimmed.charAt(199)) ? 199 : 200;
952
+ return trimmed.slice(0, end);
953
+ }
954
+ /**
955
+ * Reports the page's title now and every time it changes, so Admin can show it as its own.
956
+ * Returns a function that stops watching.
957
+ *
958
+ * A title can change in three ways, and frameworks use all three: its text is edited, its
959
+ * element is replaced, or an element is added where there was none. Rather than distinguish
960
+ * them, the SDK reads `document.title` after every batch of changes in `<head>` and reports it
961
+ * only if it differs from the last one. A mutation observer already delivers each batch once,
962
+ * in a microtask.
963
+ */
964
+ function watchTitle(report) {
965
+ let last;
966
+ const check = () => {
967
+ const title = clampTitle(document.title);
968
+ if (title !== last) {
969
+ last = title;
970
+ report(title);
971
+ }
972
+ };
973
+ check();
974
+ const observer = new MutationObserver(check);
975
+ observer.observe(document.head ?? document.documentElement, {
976
+ subtree: true,
977
+ childList: true,
978
+ characterData: true
979
+ });
980
+ return () => observer.disconnect();
981
+ }
982
+ //#endregion
983
+ //#region src/session.ts
984
+ /** Calls each listener the app registered, so that one that throws can't stop the others. */
985
+ function notify(listeners, value) {
986
+ for (const listener of [...listeners]) try {
987
+ listener(value);
988
+ } catch (error) {
989
+ queueMicrotask(() => {
990
+ throw error;
991
+ });
992
+ }
993
+ }
994
+ /**
995
+ * An error that refuses one of Admin's calls. Only its message reaches Admin, so the message
996
+ * starts with the code, as Admin's own refusals do.
997
+ */
998
+ function refusal(code, detail) {
999
+ return new Error(encodeBridgeError(code, detail));
1000
+ }
1001
+ /**
1002
+ * Returns the copy of an argument that will cross the channel, or throws `invalid_argument`
1003
+ * with `message` if it can't cross. The structured clone that carries a call only refuses a
1004
+ * symbol or a DOM node once the call is in progress, and the channel would proxy a function,
1005
+ * though no argument in the bridge's calls is a function. Cloning first refuses all of these
1006
+ * before anything is sent to Admin.
1007
+ */
1008
+ function cloneArgument(value, message) {
1009
+ try {
1010
+ return structuredClone(value);
1011
+ } catch (error) {
1012
+ throw new GhostAppError("invalid_argument", message, { cause: error });
1013
+ }
1014
+ }
1015
+ function subscribe(listeners, listener) {
1016
+ listeners.add(listener);
1017
+ return () => {
1018
+ listeners.delete(listener);
1019
+ };
1020
+ }
1021
+ /**
1022
+ * The channel to Admin over the port Admin handed the page, and the `Ghost` object the app
1023
+ * gets once Admin has called `start`. The channel itself stays inside the SDK.
1024
+ *
1025
+ * The channel ends in three cases: when the port closes, which browsers that fire `close` on
1026
+ * a port (and Node) report when Admin closes its end or its document goes away; when a call
1027
+ * fails because the thread has closed; or when Admin rejects a call with `session_ended`.
1028
+ * After that, every call rejects with the same error.
1029
+ */
1030
+ var Channel = class {
1031
+ #port;
1032
+ #thread;
1033
+ #hostExports;
1034
+ #events;
1035
+ #themeListeners = /* @__PURE__ */ new Set();
1036
+ #pathListeners = /* @__PURE__ */ new Set();
1037
+ #endListeners = /* @__PURE__ */ new Set();
1038
+ #context;
1039
+ #theme;
1040
+ #path = "/";
1041
+ #ended;
1042
+ #stopWatchingTitle;
1043
+ #history;
1044
+ #moves = 0;
1045
+ constructor(port, hostExports, events) {
1046
+ this.#port = port;
1047
+ this.#hostExports = new Set(hostExports);
1048
+ this.#events = events;
1049
+ this.#thread = new ThreadMessagePort(port, { exports: {
1050
+ start: async (context) => this.#start(context),
1051
+ themeChanged: async (theme) => this.#themeChanged(theme),
1052
+ pathChanged: async (path) => this.#pathChanged(path)
1053
+ } });
1054
+ port.addEventListener("close", () => this.end(sessionEnded()));
1055
+ port.addEventListener("messageerror", () => this.end(sessionEnded()));
1056
+ port.start();
1057
+ }
1058
+ #start(context) {
1059
+ if (this.#context) return;
1060
+ if (!isStartContext(context)) {
1061
+ const detail = "Ghost started the app with a context this SDK doesn't understand";
1062
+ setTimeout(() => this.end(new GhostAppError("invalid_context", detail)), 0);
1063
+ throw refusal("invalid_context", detail);
1064
+ }
1065
+ this.#context = {
1066
+ site: Object.freeze({ ...context.site }),
1067
+ user: Object.freeze({ ...context.user }),
1068
+ session: Object.freeze({ ...context.session })
1069
+ };
1070
+ this.#theme = Object.freeze({ ...context.theme });
1071
+ this.#history = watchHistory((route, move) => this.#moved(route, move));
1072
+ this.#path = currentRoute();
1073
+ if (this.#path !== context.path) this.#moved(this.#path, "replace");
1074
+ if (this.#hostExports.has("titleChanged")) this.#stopWatchingTitle = watchTitle((title) => {
1075
+ this.#call("titleChanged", title).catch(() => {});
1076
+ });
1077
+ this.#events.started(this.ghost);
1078
+ }
1079
+ #themeChanged(theme) {
1080
+ this.#assertStarted();
1081
+ if (!isTheme(theme)) throw refusal("invalid_argument", "Ghost sent a theme this SDK doesn't understand");
1082
+ this.#theme = Object.freeze({ ...theme });
1083
+ notify(this.#themeListeners, this.#theme);
1084
+ }
1085
+ #pathChanged(path) {
1086
+ this.#assertStarted();
1087
+ if (!isContainedPath(path)) throw refusal("invalid_argument", "Ghost sent a path this SDK doesn't understand");
1088
+ this.#path = path;
1089
+ this.#history?.follow(path);
1090
+ notify(this.#pathListeners, path);
1091
+ }
1092
+ /**
1093
+ * Reports a move the page made. Resolves once Admin has answered, with the path Admin now has
1094
+ * for the app, or has refused; a refused move leaves the page where it is.
1095
+ */
1096
+ async #moved(route, move) {
1097
+ this.#path = route;
1098
+ this.#moves += 1;
1099
+ const thisMove = this.#moves;
1100
+ try {
1101
+ const adminPath = await this.#call("pathChanged", route, move);
1102
+ if (thisMove === this.#moves && isContainedPath(adminPath)) this.#path = adminPath;
1103
+ } catch {}
1104
+ }
1105
+ #assertStarted() {
1106
+ if (!this.#context) throw refusal("invalid_context", "Ghost has not started the app yet");
1107
+ }
1108
+ async #call(name, ...args) {
1109
+ if (this.#ended) throw this.#ended;
1110
+ if (!this.#hostExports.has(name)) throw unsupported(name);
1111
+ try {
1112
+ const call = this.#thread.imports[name];
1113
+ return await call(...args);
1114
+ } catch (error) {
1115
+ if (this.#thread.closed) throw this.end(sessionEnded());
1116
+ const appError = fromHostError(error, name);
1117
+ if (appError.code === "session_ended") this.end(appError);
1118
+ throw appError;
1119
+ }
1120
+ }
1121
+ /**
1122
+ * Ends the channel. Only the first call has an effect: pending and later calls reject with
1123
+ * its `error`. Returns the error the channel ended with.
1124
+ */
1125
+ end(error) {
1126
+ if (this.#ended) return this.#ended;
1127
+ this.#ended = error;
1128
+ this.#stopWatchingTitle?.();
1129
+ this.#history?.stop();
1130
+ this.#thread.close();
1131
+ this.#port.close();
1132
+ this.#events.ended(error);
1133
+ notify(this.#endListeners, error);
1134
+ this.#endListeners.clear();
1135
+ return error;
1136
+ }
1137
+ /**
1138
+ * The `Ghost` object the app gets once `start` has set the context. It has only the members
1139
+ * its type declares, so no part of the channel, such as `end`, is reachable from the app.
1140
+ */
1141
+ ghost = this.#createGhost();
1142
+ #createGhost() {
1143
+ const context = () => this.#context;
1144
+ const theme = () => this.#theme;
1145
+ const connected = () => this.#ended === void 0;
1146
+ return Object.freeze({
1147
+ get site() {
1148
+ return context().site;
1149
+ },
1150
+ get user() {
1151
+ return context().user;
1152
+ },
1153
+ get theme() {
1154
+ return theme();
1155
+ },
1156
+ get session() {
1157
+ return context().session;
1158
+ },
1159
+ get connected() {
1160
+ return connected();
1161
+ },
1162
+ path: this.#createPath(),
1163
+ onThemeChange: (callback) => subscribe(this.#themeListeners, callback),
1164
+ onPathChange: (callback) => subscribe(this.#pathListeners, callback),
1165
+ onSessionEnd: (callback) => this.#onSessionEnd(callback),
1166
+ fetch: (path, init) => this.#fetch(path, init),
1167
+ open: (place) => this.#open(place)
1168
+ });
1169
+ }
1170
+ #createPath() {
1171
+ const current = () => this.#path;
1172
+ return Object.freeze({ get current() {
1173
+ return current();
1174
+ } });
1175
+ }
1176
+ #onSessionEnd(callback) {
1177
+ const ended = this.#ended;
1178
+ if (ended) {
1179
+ let left = false;
1180
+ queueMicrotask(() => {
1181
+ if (!left) callback(ended);
1182
+ });
1183
+ return () => {
1184
+ left = true;
1185
+ };
1186
+ }
1187
+ return subscribe(this.#endListeners, callback);
1188
+ }
1189
+ async #fetch(path, init) {
1190
+ const request = toFetchRequest(path, init);
1191
+ return toResponse(await this.#call("fetch", request));
1192
+ }
1193
+ async #open(place) {
1194
+ if (!isRecord(place)) throw invalidArgument(ARGUMENT_MESSAGES.place);
1195
+ await this.#call("open", cloneArgument(place, ARGUMENT_MESSAGES.place));
1196
+ }
1197
+ };
1198
+ //#endregion
1199
+ //#region src/version.ts
1200
+ /**
1201
+ * The SDK's version, sent in the hello for Admin's logs. The build and the tests replace
1202
+ * `__SDK_VERSION__` with the version in package.json, because the source stays within `src/`
1203
+ * and doesn't read package.json.
1204
+ */
1205
+ var SDK_VERSION = "0.1.0-alpha.1";
1206
+ //#endregion
1207
+ //#region src/connect.ts
1208
+ /**
1209
+ * How often, in milliseconds, the SDK repeats the hello until Admin answers. Admin may only
1210
+ * start listening after the page has loaded and sent its first hello, so one hello is not
1211
+ * enough.
1212
+ */
1213
+ var HELLO_INTERVAL = 250;
1214
+ /**
1215
+ * The target origin for the hello: the embedding page's origin where the browser exposes it
1216
+ * (`location.ancestorOrigins`, in Chromium and WebKit), and `'*'` elsewhere. The hello grants
1217
+ * nothing: the port goes the other way, and Admin addresses it to this page's origin only.
1218
+ * `document.referrer` doesn't work here: once the page has navigated within itself, it holds
1219
+ * the page's own origin.
1220
+ */
1221
+ function parentOrigin() {
1222
+ const origin = window.location.ancestorOrigins?.[0];
1223
+ return origin && origin !== "null" ? origin : "*";
1224
+ }
1225
+ /**
1226
+ * The global key where the first copy of the SDK to connect claims the page. It is a symbol
1227
+ * from the global registry, so a second copy bundled into the same page finds the same key.
1228
+ */
1229
+ var PAGE_CLAIM = Symbol.for("@tryghost/app-sdk");
1230
+ /**
1231
+ * The claim also holds the hello's `document` ID. It's made when the SDK loads, so every
1232
+ * `connect()` in a document sends the same ID, and a new document (after a reload, a form post
1233
+ * or a link) gets a new one. It's random rather than `performance.timeOrigin`, which some
1234
+ * privacy-focused browsers round to 16–100 ms, so two documents loaded in quick succession
1235
+ * could share it. `Math.random` is enough here, and unlike `crypto.randomUUID` it works on the
1236
+ * plain HTTP origins apps use in development.
1237
+ */
1238
+ var thisCopy = Object.freeze({
1239
+ sdk: SDK_VERSION,
1240
+ document: `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`
1241
+ });
1242
+ /** Claims the page for this copy of the SDK unless another copy has. Returns whether it did. */
1243
+ function claimPage() {
1244
+ const page = globalThis;
1245
+ page[PAGE_CLAIM] ??= thisCopy;
1246
+ return page[PAGE_CLAIM] === thisCopy;
1247
+ }
1248
+ /**
1249
+ * The longest delay `setTimeout` supports. It treats anything longer as 0, so the timeout
1250
+ * would fire immediately.
1251
+ */
1252
+ var TIMEOUT_MAX = 2 ** 31 - 1;
1253
+ function handshake(options, onEnded) {
1254
+ if (!isRecord(options)) return Promise.reject(invalidArgument("Expected options such as { timeout: 10000 }"));
1255
+ const { timeout = START_TIMEOUT_MS } = options;
1256
+ if (typeof timeout !== "number" || !(timeout > 0) || !(timeout <= TIMEOUT_MAX)) return Promise.reject(invalidArgument(`Expected a timeout in milliseconds, above 0 and at most ${TIMEOUT_MAX}`));
1257
+ if (typeof window === "undefined" || window.parent === window) return Promise.reject(new GhostAppError("not_framed", "This page is not open inside Ghost Admin"));
1258
+ const parent = window.parent;
1259
+ const targetOrigin = parentOrigin();
1260
+ return new Promise((resolve, reject) => {
1261
+ const stopWaiting = () => {
1262
+ clearInterval(helloTimer);
1263
+ clearTimeout(timeoutTimer);
1264
+ window.removeEventListener("message", onMessage);
1265
+ };
1266
+ const fail = (error) => {
1267
+ stopWaiting();
1268
+ reject(error);
1269
+ };
1270
+ const onMessage = (event) => {
1271
+ const port = event.ports?.[0];
1272
+ if (event.source !== parent || !isConnectMessage(event.data) || !port || targetOrigin !== "*" && event.origin !== targetOrigin) return;
1273
+ clearInterval(helloTimer);
1274
+ window.removeEventListener("message", onMessage);
1275
+ channel = new Channel(port, event.data.exports, {
1276
+ started: (ghost) => {
1277
+ stopWaiting();
1278
+ resolve(ghost);
1279
+ },
1280
+ ended: (error) => {
1281
+ fail(error);
1282
+ onEnded(error);
1283
+ }
1284
+ });
1285
+ };
1286
+ const hello = {
1287
+ type: HELLO_MESSAGE_TYPE,
1288
+ sdk: SDK_VERSION,
1289
+ document: thisCopy.document
1290
+ };
1291
+ const sayHello = () => {
1292
+ parent.postMessage(hello, targetOrigin);
1293
+ };
1294
+ let channel;
1295
+ window.addEventListener("message", onMessage);
1296
+ sayHello();
1297
+ const helloTimer = setInterval(sayHello, HELLO_INTERVAL);
1298
+ const timeoutTimer = setTimeout(() => {
1299
+ const error = new GhostAppError("not_connected", "Ghost Admin did not start the app in time");
1300
+ fail(error);
1301
+ channel?.end(error);
1302
+ }, timeout);
1303
+ });
1304
+ }
1305
+ var connecting;
1306
+ var spent;
1307
+ function forget(attempt) {
1308
+ if (connecting === attempt) connecting = void 0;
1309
+ }
1310
+ /**
1311
+ * Connects to Ghost Admin, which must frame the page, and resolves once Admin has started the
1312
+ * app. Safe to call as soon as the page loads.
1313
+ *
1314
+ * Every call shares one connection, and the first call's options apply. Only one copy of the
1315
+ * SDK in a page can connect; any other copy rejects with `duplicate_sdk`. Admin answers each
1316
+ * document only once, so after it answers, that connection is the page's only one. Once it
1317
+ * fails or its session ends, every call rejects with the error it ended with, and only a new
1318
+ * document (after a reload, for example) can connect again. A failure before Admin answered,
1319
+ * such as a bad option or a timeout, can be retried.
1320
+ */
1321
+ function connect(options = {}) {
1322
+ if (!claimPage()) return Promise.reject(new GhostAppError("duplicate_sdk", "This page loads the app SDK more than once; load one copy, which every part of the page shares"));
1323
+ if (spent) return Promise.reject(spent);
1324
+ if (!connecting) {
1325
+ const attempt = handshake(options, (error) => {
1326
+ spent = error;
1327
+ forget(attempt);
1328
+ }).catch((error) => {
1329
+ forget(attempt);
1330
+ throw error;
1331
+ });
1332
+ connecting = attempt;
1333
+ }
1334
+ return connecting;
1335
+ }
1336
+ //#endregion
1337
+ export { GhostAppError, connect };
1338
+
1339
+ //# sourceMappingURL=app-sdk.js.map