@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.
- package/LICENSE +22 -0
- package/README.md +310 -2
- package/build/index.d.ts +180 -0
- package/build/index.js +763 -0
- package/build/index.js.map +1 -0
- package/dist/app-sdk.js +1339 -0
- package/dist/app-sdk.js.map +1 -0
- package/package.json +34 -3
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"app-sdk.js","names":["#idsToFunction","#functionsToId","#idsToProxy","#finalizationRegistry","#finalization","#customSerializer","#customDeserializer","#serializeInternal","#deserializeInternal","#abort","#handlerForCall","#idsToResolver","#resolveCall","#callLocal","#waitForResult","#port","#thread","#hostExports","#events","#themeListeners","#pathListeners","#endListeners","#start","#themeChanged","#pathChanged","#context","#theme","#history","#moved","#path","#stopWatchingTitle","#call","#assertStarted","#moves","#ended","#createGhost","#createPath","#onSessionEnd","#fetch","#open"],"sources":["../../app-contracts/build/plain-text.js","../../app-contracts/build/bridge/rules.js","../src/errors.ts","node_modules/@quilted/threads/build/esm/constants.mjs","node_modules/@quilted/events/build/esm/abort/NestedAbortController.mjs","node_modules/@quilted/threads/build/esm/errors.mjs","node_modules/@quilted/threads/build/esm/nanoid.mjs","node_modules/@quilted/threads/build/esm/functions/ThreadFunctionsAutomatic.mjs","node_modules/@quilted/threads/build/esm/serialization/shared.mjs","node_modules/@quilted/threads/build/esm/serialization/ThreadSerializationStructuredClone.mjs","node_modules/@quilted/threads/build/esm/Thread.mjs","node_modules/@quilted/threads/build/esm/threads/ThreadMessagePort.mjs","../src/fetch.ts","../src/history.ts","../src/title.ts","../src/session.ts","../src/version.ts","../src/connect.ts"],"sourcesContent":["// What plain text may contain: letters, combining marks, digits, punctuation, symbols and\n// spaces, plus the two joiners that emoji sequences and scripts such as Persian need.\n// Everything else is refused by not being listed: control and formatting characters, line\n// breaks, the characters that reorder text, private-use and unassigned code points. Those can\n// make text display as something other than what it is, such as a title that reverses\n// whatever Admin shows after it.\nconst ALLOWED = '\\\\p{L}\\\\p{M}\\\\p{N}\\\\p{P}\\\\p{S}\\\\p{Zs}\\\\u200C\\\\u200D';\nconst PLAIN_TEXT = new RegExp(`^[${ALLOWED}]*$`, 'u');\nconst NOT_PLAIN_TEXT = new RegExp(`[^${ALLOWED}]`, 'gu');\n/** Whether text is one line of plain text, as a name, a description or a title must be. */\nexport function isPlainText(value) {\n return PLAIN_TEXT.test(value);\n}\n/** Returns the text with the characters `isPlainText` refuses removed. */\nexport function toPlainText(value) {\n return value.replace(NOT_PLAIN_TEXT, '');\n}\n//# sourceMappingURL=plain-text.js.map","/**\n * The bridge's rules that have no dependencies. The root entry point exports them so the SDK\n * can use them without zod. The schemas in this folder build on them, so the SDK and Admin\n * read a path or a refusal the same way.\n *\n * What Admin sends the page has no schema, because Admin builds it and never parses it. Its\n * types are declared here, next to the guards the SDK checks it with. The SDK trusts Admin, so\n * the guards only check shape and path containment. They turn a mismatch into a clear error\n * rather than `undefined` somewhere in the app. Only the schemas check limits.\n */\n/** Posted by the app's page to `window.parent` once the SDK has loaded. */\nexport const HELLO_MESSAGE_TYPE = 'ghost-app:hello';\n/** Posted by Admin to the frame that sent the hello, with the channel's port attached. */\nexport const CONNECT_MESSAGE_TYPE = 'ghost-app:connect';\n/**\n * How long an app's page has to start, in milliseconds. Admin gives up on a frame this long\n * after mounting it, and the SDK waits this long for Admin to start the app unless the app\n * passes its own `timeout`. Long enough for a slow page on a slow connection to load and send\n * its hello.\n */\nexport const START_TIMEOUT_MS = 10_000;\n/** Long enough for any real page title, short enough that Admin's own name still shows. */\nexport const TITLE_MAX_LENGTH = 200;\n/**\n * The methods an app may use, in uppercase: the ones the allowlist has routes for. The SDK\n * uppercases what apps pass.\n */\nexport const FETCH_METHODS = ['GET', 'POST', 'PUT', 'DELETE'];\n/**\n * Whether a request with this method may carry a body. Expects an uppercase method from\n * `FETCH_METHODS`. The Admin API reads no body on a `GET`, and fetch refuses to send one.\n */\nexport function methodAllowsBody(method) {\n return method !== 'GET';\n}\n// The headers Admin sets itself on a request it makes for an app: the credentials, which only\n// Admin may send; Admin's own markers, which Ghost core treats as coming from Admin; the headers\n// that describe the connection, or the proxies along the way, rather than the request; and the\n// ones that say how to read the body. A body is always JSON, which Admin labels itself: the Admin\n// API also reads forms and uploads, and decodes JSON in any charset it's told, so a content type\n// of the app's choosing could carry a write past the checks on what it contains.\nconst 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;\n/**\n * Whether a request header is one that apps may not set, in any case. Admin refuses a request\n * that sets one rather than dropping the header, so the app gets an error instead of wondering\n * why the header never arrived. The browser refuses some of these anyway; they are listed here\n * so that none of them relies on the browser.\n */\nexport function isReservedRequestHeader(name) {\n return RESERVED_REQUEST_HEADER.test(name);\n}\n/**\n * The messages Admin and the SDK use when they refuse an argument for the same reason, so an\n * app gets the same message whichever side catches the problem. The SDK checks only for obvious\n * mistakes, before anything crosses the channel; Admin's schemas check everything again.\n */\nexport const ARGUMENT_MESSAGES = {\n fetchPath: 'Expected an Admin API path such as /posts/, not a URL',\n fetchMethod: `Expected a method of: ${FETCH_METHODS.join(', ')}`,\n fetchBody: 'Expected no body on a GET request',\n // Header names are case-insensitive, and `Headers` lowercases them on the SDK's side, so the\n // name is lowercased here too and both sides produce the same message.\n reservedHeader: (name) => `Expected no ${name.toLowerCase()} header, which only Admin sets`,\n jsonBody: 'Expected the body as JSON text',\n appPath: 'Expected a path within the app, starting with a single /',\n pathMove: 'Expected a move of push or replace',\n place: 'Expected a place such as { post: { id } }, { page: { id } }, { member: { id } } or { apps: true }',\n};\n/**\n * The statuses a `fetch` response may have. The SDK turns the response back into a\n * `Response`, which only accepts statuses from 200 to 599. Fetch never returns an\n * informational (1xx) status to scripts anyway.\n */\nexport const FETCH_RESPONSE_STATUS_MIN = 200;\nexport const FETCH_RESPONSE_STATUS_MAX = 599;\n/**\n * The codes a refused call carries across the channel. The structured clone that carries an\n * error keeps only its message, so the refusing side puts the code at the start of the\n * message, as in `blocked: Apps can't use GET /db/`, and the other side parses it back out. Codes\n * are only ever added: an SDK that doesn't know a code treats the whole message as a generic\n * refusal.\n *\n * The host codes, which Admin refuses the page's calls with:\n *\n * - `session_ended`: the session is over; the page is about to be replaced.\n * - `invalid_argument`: an argument Admin does not take.\n * - `invalid_path`: a path that is not an Admin API path or a route within the app, or one\n * the Admin API only responds to with a redirect, such as a path without its trailing `/`.\n * - `blocked`: a request the allowlist doesn't allow, or a write it refuses.\n * - `network_error`: Admin could not reach its own API.\n * - `rejected`: anything else; the detail says why.\n */\nexport const HOST_ERROR_CODES = [\n 'session_ended',\n 'invalid_argument',\n 'invalid_path',\n 'blocked',\n 'network_error',\n 'rejected',\n];\n/**\n * The app codes, which the page refuses Admin's calls with:\n *\n * - `invalid_context`: a start context the SDK cannot read, or a call before the app has\n * started.\n * - `invalid_argument`: an argument the SDK does not take, such as a theme it cannot read.\n */\nexport const APP_ERROR_CODES = ['invalid_context', 'invalid_argument'];\n/** Every code a refusal can carry, in either direction. */\nexport const BRIDGE_ERROR_CODES = [...HOST_ERROR_CODES, 'invalid_context'];\nconst CODED_MESSAGE = /^([a-z_]+): ([\\s\\S]*)$/;\n/**\n * Builds the message a refusal crosses the channel as: `code: detail`. Each side should pass\n * only its own codes; typing its refusals as `HostErrorCode` or `AppErrorCode` enforces that.\n */\nexport function encodeBridgeError(code, detail) {\n return `${code}: ${detail}`;\n}\n/**\n * Reads the code and detail back from a refusal's `code: detail` message. Takes the codes the\n * other side may send: `HOST_ERROR_CODES` for a refusal from Admin, and `APP_ERROR_CODES` for\n * one from the page. Returns `undefined` for a message that doesn't start with one of them.\n */\nexport function decodeBridgeError(message, codes) {\n const [, code = '', detail = ''] = CODED_MESSAGE.exec(message) ?? [];\n return codes.includes(code) ? { code: code, detail } : undefined;\n}\nconst THEME_MODES = ['light', 'dark'];\n// URL parsers and routers don't agree on whether to strip or refuse control characters, so a\n// path containing one can mean something different to each of them.\nconst CONTROL_CHARACTER = /\\p{Cc}/u;\n/**\n * Whether a value is a path that stays within the base it is resolved against, rather than\n * escaping it. It must start with a single `/`, so it can't carry a scheme or be read as\n * `//host`. It must not contain `\\`, which URL parsers read as `/`, or any control character.\n */\nexport function isContainedPath(value) {\n return (typeof value === 'string' &&\n value.startsWith('/') &&\n !value.startsWith('//') &&\n !value.includes('\\\\') &&\n !CONTROL_CHARACTER.test(value));\n}\n// Used only as a base for parsing, never requested. Parsing against it gives a path the URL\n// parser's normalised form.\nconst APP_PATH_BASE = 'https://app.invalid';\n/**\n * Returns an app path in the URL parser's normalised form, the one form Admin and the SDK\n * store it in. `.` and `..` are resolved within the app, so a path can never climb out of it.\n * Characters that need escaping are escaped once, so a path the app reported compares equal to\n * the same path read back from Admin's URL. `/search?q=a b` becomes `/search?q=a%20b`, and\n * `/x/../episodes/1` becomes `/episodes/1`.\n *\n * Expects a path that `isContainedPath` accepts; anything else may not be a path within the\n * app at all. `AppPathSchema` already returns this form, so Admin never calls this directly.\n * The SDK, which doesn't load zod, does.\n */\nexport function normaliseAppPath(path) {\n const url = new URL(path, APP_PATH_BASE);\n return `${url.pathname}${url.search}${url.hash}`;\n}\n/** An object, or an array: anything whose fields can be read. */\nexport function isRecord(value) {\n return typeof value === 'object' && value !== null;\n}\nfunction hasStrings(value, keys) {\n return isRecord(value) && keys.every((key) => typeof value[key] === 'string');\n}\nexport function isTheme(value) {\n return (hasStrings(value, ['accent_color']) && THEME_MODES.includes(value.mode));\n}\nexport function isStartContext(value) {\n return (isRecord(value) &&\n hasStrings(value.site, ['url', 'title', 'timezone', 'locale']) &&\n hasStrings(value.user, ['id', 'role']) &&\n isTheme(value.theme) &&\n isRecord(value.session) &&\n Number.isSafeInteger(value.session.revision) &&\n value.session.revision >= 0 &&\n isContainedPath(value.path));\n}\nexport function isConnectMessage(value) {\n return (isRecord(value) &&\n value.type === CONNECT_MESSAGE_TYPE &&\n Array.isArray(value.exports) &&\n value.exports.every((name) => typeof name === 'string'));\n}\nexport function isFetchResponse(value) {\n return (isRecord(value) &&\n Number.isSafeInteger(value.status) &&\n value.status >= FETCH_RESPONSE_STATUS_MIN &&\n value.status <= FETCH_RESPONSE_STATUS_MAX &&\n typeof value.statusText === 'string' &&\n isRecord(value.headers) &&\n !Array.isArray(value.headers) &&\n Object.values(value.headers).every((header) => typeof header === 'string') &&\n typeof value.body === 'string');\n}\n//# sourceMappingURL=rules.js.map","import { HOST_ERROR_CODES, decodeBridgeError, type BridgeErrorCode } from '@tryghost/app-contracts';\n\n/**\n * Why an SDK call failed:\n *\n * - `not_framed`: the page is not framed in Admin, so there is nothing to connect to.\n * - `not_connected`: Admin did not start the app in time.\n * - `duplicate_sdk`: another copy of the SDK in the page has already connected, or tried to.\n * - `invalid_context`: Admin started the app with a context this SDK cannot read.\n * - `session_ended`: this document has left the app session, or the session has ended.\n * - `invalid_argument`: the app passed something that cannot be sent.\n * - `invalid_path`: a path that is not an Admin API path, or not a route within the app; or\n * one the Admin API only redirects, such as a path without its trailing `/`.\n * - `unsupported`: this site's version of Ghost doesn't have the call the app made yet. The\n * SDK knows this from the calls Admin listed when it connected.\n * - `blocked`: Admin refused by policy, such as a request the allowlist doesn't allow.\n * - `network_error`: Admin could not reach its own API.\n * - `rejected`: Admin refused for any other reason; the message says why.\n *\n * `not_framed`, `not_connected`, `duplicate_sdk` and `unsupported` are the SDK's own codes; the\n * rest are bridge codes, which cross the channel.\n */\nexport type GhostAppErrorCode =\n | 'not_framed'\n | 'not_connected'\n | 'duplicate_sdk'\n | 'unsupported'\n | BridgeErrorCode;\n\n/** The only error type the SDK rejects with, so an app can branch on `code`. */\nexport class GhostAppError extends Error {\n readonly code: GhostAppErrorCode;\n\n constructor(code: GhostAppErrorCode, message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = 'GhostAppError';\n this.code = code;\n }\n}\n\n/**\n * Converts whatever a call to Admin rejected with into a `GhostAppError`, with the code Admin\n * gave or, if there is none, `rejected` with Admin's message.\n */\nexport function fromHostError(error: unknown, operation: string): GhostAppError {\n const message =\n typeof error === 'object' && error !== null && 'message' in error\n ? String(error.message)\n : undefined;\n if (message === undefined) {\n return new GhostAppError('rejected', `Ghost refused ${operation}`, { cause: error });\n }\n // Only the codes Admin refuses with are parsed; any other prefix stays part of the message.\n const coded = decodeBridgeError(message, HOST_ERROR_CODES);\n if (coded) {\n return new GhostAppError(coded.code, coded.detail, { cause: error });\n }\n return new GhostAppError('rejected', message, { cause: error });\n}\n\nexport function invalidArgument(message: string): GhostAppError {\n return new GhostAppError('invalid_argument', message);\n}\n\nexport function invalidPath(message: string): GhostAppError {\n return new GhostAppError('invalid_path', message);\n}\n\nexport function unsupported(operation: string): GhostAppError {\n return new GhostAppError('unsupported', `This site's Ghost doesn't support ${operation} yet`);\n}\n\nexport function sessionEnded(): GhostAppError {\n return new GhostAppError('session_ended', 'The session with Ghost has ended');\n}\n","const MESSAGE_CALL = 1;\nconst MESSAGE_CALL_RESULT = 2;\nconst MESSAGE_FUNCTION_CALL = 3;\nconst MESSAGE_FUNCTION_RESULT = 4;\nconst MESSAGE_FUNCTION_RELEASE = 5;\nconst SERIALIZE_METHOD = Symbol.for('quilt.threads.serialize');\nconst TRANSFERABLE = Symbol.for('quilt.threads.transferable');\n\nexport { MESSAGE_CALL, MESSAGE_CALL_RESULT, MESSAGE_FUNCTION_CALL, MESSAGE_FUNCTION_RELEASE, MESSAGE_FUNCTION_RESULT, SERIALIZE_METHOD, TRANSFERABLE };\n","/**\n * An `AbortController` that will automatically abort when any of\n * its \"parent\" `AbortController`s abort. This is useful for when\n * you have nested asynchronous operations that may abort independently.\n * The `AbortController` can also be independently aborted.\n *\n * To associate the parent `AbortController`s, pass their signals\n * as arguments to the constructor.\n *\n * @example\n * import {NestedAbortController} from '@shopify/events';\n *\n * const parent = new AbortController();\n * const nested = new NestedAbortController(parent.signal);\n *\n * parent.abort();\n * nested.signal.aborted; // true\n */\nclass NestedAbortController extends AbortController {\n constructor(...parents) {\n super();\n const abortedSignal = parents.find(signal => signal.aborted);\n if (abortedSignal) {\n this.abort(abortedSignal.reason);\n } else {\n const abort = event => this.abort(event.target.reason);\n const options = {\n signal: this.signal\n };\n for (const signal of parents) {\n signal.addEventListener('abort', abort, options);\n }\n }\n }\n}\n\nexport { NestedAbortController };\n","class ThreadClosedError extends Error {\n constructor() {\n super('You attempted to call a function on a closed thread.');\n }\n}\n\nexport { ThreadClosedError };\n","// Copied from https://github.com/ai/nanoid/blob/main/nanoid.js\nlet a = 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict';\nfunction nanoid(e = 21) {\n let t = '',\n r = crypto.getRandomValues(new Uint8Array(e));\n for (let n = 0; n < e; n++) t += a[63 & r[n]];\n return t;\n}\n\nexport { nanoid };\n","import { MESSAGE_FUNCTION_CALL, MESSAGE_FUNCTION_RELEASE } from '../constants.mjs';\nimport { nanoid } from '../nanoid.mjs';\n\n/**\n * A strategy for managing functions across threads that automatically releases\n * functions when they are no longer needed. This is done by deserializing functions\n * into a proxy that can be called, and wrapping that proxy in a `FinalizationRegistry`,\n * which allows us to send a message to the parent thread when the function is no\n * longer used.\n *\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry\n */\nclass ThreadFunctionsAutomatic {\n #functionsToId = (() => new Map())();\n #idsToFunction = (() => new Map())();\n #idsToProxy = (() => new Map())();\n #finalization = (() => new WeakMap())();\n get(id) {\n return this.#idsToFunction.get(id);\n }\n release(id) {\n const func = this.#idsToFunction.get(id);\n if (func) {\n this.#idsToFunction.delete(id);\n this.#functionsToId.delete(func);\n }\n return Boolean(func);\n }\n serialize(func) {\n let id = this.#functionsToId.get(func);\n if (id == null) {\n id = nanoid();\n this.#functionsToId.set(func, id);\n this.#idsToFunction.set(id, func);\n }\n return id;\n }\n deserialize(id, thread) {\n let proxy = this.#idsToProxy.get(id)?.deref();\n if (proxy) return proxy;\n proxy = (...args) => {\n if (!this.#idsToProxy.has(id)) {\n throw new Error('You attempted to call a function that was already revoked.');\n }\n return thread.call((callID, args, transferable) => {\n thread.messages.send([MESSAGE_FUNCTION_CALL, callID, id, args], transferable);\n }, args);\n };\n this.#finalizationRegistry(thread)?.register(proxy, id);\n this.#idsToProxy.set(id, new WeakRef(proxy));\n return proxy;\n }\n #finalizationRegistry(thread) {\n let finalization = this.#finalization.get(thread);\n if (typeof FinalizationRegistry === 'undefined') {\n return undefined;\n }\n if (!finalization) {\n finalization = new FinalizationRegistry(id => {\n thread.messages.send([MESSAGE_FUNCTION_RELEASE, id]);\n });\n this.#finalization.set(thread, finalization);\n }\n return finalization;\n }\n}\n\nexport { ThreadFunctionsAutomatic };\n","function isIterator(value) {\n return value != null && (Symbol.asyncIterator in value || Symbol.iterator in value) && typeof value.next === 'function';\n}\nfunction isBasicObject(value) {\n if (value == null || typeof value !== 'object') return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype == null || prototype === Object.prototype;\n}\n\nexport { isBasicObject, isIterator };\n","import { TRANSFERABLE, SERIALIZE_METHOD } from '../constants.mjs';\nimport { isIterator, isBasicObject } from './shared.mjs';\n\nconst FUNCTION = '_@f';\nconst ASYNC_ITERATOR = '_@i';\n\n/**\n * A thread encoder that can transfer supports a wide variety of JavaScript types by\n * converting them to a format that the [`structuredClone`](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm)\n * algorithm can process. This\n *\n * Additionally, this encoder will convert functions into a JSON-friendly representation.\n * These functions will use a manual memory management technique to ensure they can be\n * garbage collected by default, but can be configured to use a `WeakRef`-based automatic\n * memory management system by setting the `garbageCollection: 'weak-ref'` option.\n */\nclass ThreadSerializationStructuredClone {\n #customSerializer;\n #customDeserializer;\n constructor(options) {\n this.#customSerializer = options?.serialize;\n this.#customDeserializer = options?.deserialize;\n }\n\n /**\n * Serializes a value into a structured cloning-compatible format that can be transferred between threads.\n */\n serialize(value, thread, transferable) {\n return this.#serializeInternal(value, thread, transferable);\n }\n #serializeInternal(value, thread, transferable, seen = new Map(), isApplyingDefault = false) {\n if (value == null) return value;\n if (seen.has(value)) return seen.get(value);\n\n // Prevent circular references\n seen.set(value, undefined);\n if (typeof value === 'object') {\n if (this.#customSerializer && !isApplyingDefault) {\n const customValue = this.#customSerializer(value, value => this.#serializeInternal(value, thread, transferable, seen, true), thread, transferable);\n if (customValue !== undefined) {\n seen.set(value, customValue);\n return customValue;\n }\n }\n if (value[TRANSFERABLE]) {\n transferable?.push(value);\n seen.set(value, value);\n return value;\n }\n const serializeValue = value => {\n return this.#serializeInternal(value, thread, transferable, seen);\n };\n if (typeof value[SERIALIZE_METHOD] === 'function') {\n const result = value[SERIALIZE_METHOD]({\n serialize: serializeValue\n });\n seen.set(value, result);\n return result;\n }\n if (Array.isArray(value)) {\n const result = value.map(item => serializeValue(item));\n seen.set(value, result);\n return result;\n }\n if (value instanceof Map) {\n const entries = [...value.entries()].map(([key, value]) => {\n return [serializeValue(key), serializeValue(value)];\n });\n const result = new Map(entries);\n seen.set(value, result);\n return result;\n }\n if (value instanceof Set) {\n const entries = [...value].map(entry => serializeValue(entry));\n const result = new Set(entries);\n seen.set(value, result);\n return result;\n }\n const valueIsIterator = isIterator(value);\n if (isBasicObject(value) || valueIsIterator) {\n const result = {};\n for (const key of Object.keys(value)) {\n result[key] = serializeValue(value[key]);\n }\n if (valueIsIterator) {\n result.next ??= serializeValue(value.next.bind(value));\n result.return ??= serializeValue(value.return.bind(value));\n result.throw ??= serializeValue(value.throw.bind(value));\n result[ASYNC_ITERATOR] = true;\n }\n seen.set(value, result);\n return result;\n }\n }\n if (typeof value === 'function') {\n const serialized = thread.functions.serialize(value, thread, transferable);\n const result = {\n [FUNCTION]: serialized\n };\n seen.set(value, result);\n return result;\n }\n seen.set(value, value);\n return value;\n }\n\n /**\n * Deserializes a structured cloning-compatible value from another thread.\n */\n deserialize(value, thread) {\n return this.#deserializeInternal(value, thread);\n }\n #deserializeInternal(value, thread, isApplyingDefault = false) {\n if (value == null) return value;\n if (typeof value === 'object') {\n if (this.#customDeserializer && !isApplyingDefault) {\n const customValue = this.#customDeserializer(value, value => this.#deserializeInternal(value, thread, true), thread);\n if (customValue !== undefined) {\n return customValue;\n }\n }\n if (value == null) {\n return value;\n }\n if (Array.isArray(value)) {\n return value.map(value => this.#deserializeInternal(value, thread));\n }\n if (value instanceof Map) {\n return new Map([...value].map(([key, value]) => [this.#deserializeInternal(key, thread), this.#deserializeInternal(value, thread)]));\n }\n if (value instanceof Set) {\n return new Set([...value].map(entry => this.#deserializeInternal(entry, thread)));\n }\n if (FUNCTION in value) {\n const func = thread.functions.deserialize(value[FUNCTION], thread);\n return func;\n }\n if (!isBasicObject(value)) {\n return value;\n }\n const result = {};\n for (const key of Object.keys(value)) {\n if (key === ASYNC_ITERATOR) {\n result[Symbol.asyncIterator] = () => result;\n } else {\n result[key] = this.#deserializeInternal(value[key], thread);\n }\n }\n return result;\n }\n return value;\n }\n}\n\nexport { ThreadSerializationStructuredClone };\n","import { NestedAbortController } from '@quilted/events';\nimport { ThreadClosedError } from './errors.mjs';\nimport { nanoid } from './nanoid.mjs';\nimport { MESSAGE_FUNCTION_RELEASE, MESSAGE_FUNCTION_RESULT, MESSAGE_CALL_RESULT, MESSAGE_FUNCTION_CALL, MESSAGE_CALL } from './constants.mjs';\nimport { ThreadFunctionsAutomatic } from './functions/ThreadFunctionsAutomatic.mjs';\nimport { ThreadSerializationStructuredClone } from './serialization/ThreadSerializationStructuredClone.mjs';\n\n/**\n * An object that can serialize and deserialize values communicated between two threads.\n */\n\n/**\n * An object that can serialize and deserialize values communicated between two threads.\n */\n\n/**\n * Options to customize the creation of a `ThreadSerialization` instance.\n */\n\n/**\n * Options to customize the creation of a `Thread` instance.\n */\n\n/**\n * An object backing a `Thread` that provides the message-passing interface\n * that allows communication to flow between environments. This message-passing\n * interface is based on the [`postMessage` interface](https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage),\n * which is easily adaptable to many JavaScript objects and environments.\n */\n\n/**\n * A map of messages that can be sent between threads.\n */\n\n/**\n * The possible data payloads that can be transferred between threads.\n */\n\n/**\n * A helper type that extracts all callable methods that can be safely proxied\n * between threads; that is, ones which return a promise or async iterator.\n */\n\n/**\n * A thread represents a target JavaScript environment that exposes a set\n * of callable, asynchronous methods. The thread takes care of automatically\n * encoding and decoding its arguments and return values, so you can interact\n * with it as if its methods were implemented in the same environment as your\n * own code.\n */\nclass Thread {\n /**\n * An object that exposes the methods that can be called on the paired thread.\n * This object will automatically encode and decode arguments and return values\n * as necessary.\n */\n\n /**\n * An object that exposes the methods that can be called on this thread by the\n * paired thread. To set these methods, pass the `exports` option when creating\n * a new `Thread`.\n */\n\n /**\n * An object that provides the message-passing interface that allows communication\n * to flow between environments.\n */\n\n /**\n * An object that manages how functions are proxied between threads.\n */\n\n /**\n * An object that manages how values are serialized and deserialized between threads.\n */\n\n /**\n * An `AbortSignal` that indicates whether the communication channel is still open.\n */\n get signal() {\n return this.#abort.signal;\n }\n\n /**\n * A boolean indicating whether the communication channel is still open.\n */\n get closed() {\n return this.#abort.signal.aborted;\n }\n #abort;\n #idsToResolver = (() => new Map())();\n constructor(messages, {\n imports,\n exports,\n functions = new ThreadFunctionsAutomatic(),\n serialization = new ThreadSerializationStructuredClone(),\n signal\n } = {}) {\n this.messages = messages;\n this.#abort = signal ? new NestedAbortController(signal) : new AbortController();\n this.exports = exports ?? {};\n this.imports = createThreadImports(this.#handlerForCall.bind(this), imports);\n this.functions = functions;\n this.serialization = serialization;\n this.functions.start?.(this);\n this.serialization.start?.(this);\n this.signal.addEventListener('abort', () => {\n for (const id of this.#idsToResolver.keys()) {\n this.#resolveCall(id, undefined, new ThreadClosedError());\n }\n this.#idsToResolver.clear();\n }, {\n once: true\n });\n messages.listen(async rawData => {\n const isThreadMessageData = Array.isArray(rawData) && typeof rawData[0] === 'number';\n if (!isThreadMessageData) {\n return;\n }\n const data = rawData;\n switch (data[0]) {\n case MESSAGE_CALL:\n {\n const [, id, property, args] = data;\n const func = this.exports[property] ?? (() => {\n throw new Error(`No '${property}' method is exported from this thread`);\n });\n await this.#callLocal(func, args, (value, error, transferable) => {\n this.messages.send([MESSAGE_CALL_RESULT, id, value, error], transferable);\n });\n break;\n }\n case MESSAGE_FUNCTION_CALL:\n {\n const [, callID, funcID, args] = data;\n const func = this.functions.get(funcID, this) ?? missingThreadFunction;\n await this.#callLocal(func, args, (value, error, transferable) => {\n this.messages.send([MESSAGE_FUNCTION_RESULT, callID, value, error], transferable);\n });\n break;\n }\n case MESSAGE_CALL_RESULT:\n case MESSAGE_FUNCTION_RESULT:\n {\n this.#resolveCall(...data.slice(1));\n break;\n }\n case MESSAGE_FUNCTION_RELEASE:\n {\n const id = data[1];\n this.functions.release(id, this);\n break;\n }\n }\n }, {\n signal: this.signal\n });\n }\n\n /**\n * Closes the communication channel between the two threads. This will prevent\n * any further communication between the threads, and will clean up any memory\n * associated with in-progress communication. It will also reject any inflight\n * function calls between threads with a `ThreadClosedError`.\n */\n close() {\n this.#abort.abort();\n }\n\n /**\n * Requests that the thread provide the context needed to make a function\n * call between threads. You provide this method a function to call and the\n * unserialized arguments you wish to call it with, and the thread will call\n * the function you provided with a serialized call ID, the serialized arguments,\n * and any transferable objects that need to be passed between threads.\n */\n call(func, args) {\n if (this.closed) {\n return Promise.reject(new ThreadClosedError());\n }\n const transferable = [];\n const serialized = this.serialization.serialize(args, this, transferable);\n const id = nanoid();\n const done = this.#waitForResult(id);\n func(id, serialized, transferable);\n return done;\n }\n async #callLocal(func, args, withResult) {\n try {\n const result = this.functions.call ? await this.functions.call(func, args, this) : await func(...this.serialization.deserialize(args, this));\n const transferable = [];\n const serialized = this.serialization.serialize(result, this, transferable);\n withResult(serialized, undefined, transferable);\n } catch (error) {\n withResult(undefined, this.serialization.serialize(error, this));\n }\n }\n #handlerForCall(property) {\n return (...args) => {\n try {\n if (typeof property !== 'string' && typeof property !== 'number') {\n throw new Error(`Can’t call a symbol method on a thread: ${property.toString()}`);\n }\n return this.call((id, serializedArgs, transferable) => {\n this.messages.send([MESSAGE_CALL, id, property, serializedArgs], transferable);\n }, args);\n } catch (error) {\n return Promise.reject(error);\n }\n };\n }\n #resolveCall(...args) {\n const callID = args[0];\n const resolver = this.#idsToResolver.get(callID);\n if (resolver) {\n resolver(...args);\n this.#idsToResolver.delete(callID);\n }\n }\n #waitForResult(id) {\n const promise = new Promise((resolve, reject) => {\n this.#idsToResolver.set(id, (_, value, error) => {\n if (error == null) {\n resolve(this.serialization.deserialize(value, this));\n } else {\n reject(this.serialization.deserialize(error, this));\n }\n });\n });\n Object.defineProperty(promise, Symbol.asyncIterator, {\n async *value() {\n const result = await promise;\n Object.defineProperty(result, Symbol.asyncIterator, {\n value: () => result\n });\n yield* result;\n }\n });\n return promise;\n }\n}\nfunction createThreadImports(handlerForImport, imported) {\n let call;\n if (imported == null) {\n if (typeof Proxy !== 'function') {\n throw new Error(`You must pass an array of callable methods in environments without Proxies.`);\n }\n const cache = new Map();\n call = new Proxy({}, {\n get(_target, property) {\n if (cache.has(property)) {\n return cache.get(property);\n }\n const handler = handlerForImport(property);\n cache.set(property, handler);\n return handler;\n }\n });\n } else {\n call = {};\n for (const method of imported) {\n Object.defineProperty(call, method, {\n value: handlerForImport(method),\n writable: false,\n configurable: true,\n enumerable: true\n });\n }\n }\n return call;\n}\nfunction missingThreadFunction() {\n throw new Error(`You attempted to call a function that is not stored. It may have already been released.`);\n}\n\nexport { Thread };\n","import { Thread } from '../Thread.mjs';\n\n/**\n * Creates a thread from a `MessagePort` instance in the browser.\n *\n * @see https://developer.mozilla.org/en-US/docs/Web/API/MessagePort\n *\n * @example\n * import {ThreadMessagePort} from '@quilted/threads';\n *\n * const channel = new MessageChannel();\n *\n * const threadOne = new ThreadMessagePort(channel.port1);\n * const threadTwo = new ThreadMessagePort(channel.port2, {\n * exports: {\n * async sendMessage(message) {\n * console.log(message);\n * },\n * },\n * });\n *\n * channel.port1.start();\n * channel.port2.start();\n *\n * await threadOne.imports.sendMessage('Hello world!');\n */\nclass ThreadMessagePort extends Thread {\n /**\n * Starts a thread wrapped around a `MessagePort` object, and returns the imports\n * of the thread.\n *\n * @example\n * ```ts\n * import {ThreadMessagePort} from '@quilted/threads';\n *\n * const channel = new MessageChannel();\n *\n * ThreadMessagePort.export(channel.port1, {\n * async getMessage() {\n * return 'Hello, world!';\n * },\n * });\n *\n * const {getMessage} = ThreadMessagePort.import(channel.port2);\n *\n * channel.port1.start();\n * channel.port2.start();\n *\n * const message = await getMessage(); // 'Hello, world!'\n * ```\n */\n static import(port, options) {\n return new ThreadMessagePort(port, options).imports;\n }\n\n /**\n * Starts a thread wrapped around a `MessagePort` object, providing the second\n * argument as the exports of the thread.\n *\n * @example\n * ```ts\n * import {ThreadMessagePort} from '@quilted/threads';\n *\n * const channel = new MessageChannel();\n *\n * ThreadMessagePort.export(channel.port1, {\n * async getMessage() {\n * return 'Hello, world!';\n * },\n * });\n *\n * const {getMessage} = ThreadMessagePort.import(channel.port2);\n *\n * channel.port1.start();\n * channel.port2.start();\n *\n * const message = await getMessage(); // 'Hello, world!'\n * ```\n */\n static export(port, exports, options) {\n new ThreadMessagePort(port, {\n ...options,\n exports\n });\n }\n constructor(port, options) {\n super(portToMessageTarget(port), options);\n this.port = port;\n }\n}\nfunction portToMessageTarget(port) {\n return {\n send(...args) {\n port.postMessage(...args);\n },\n listen(listener, {\n signal\n }) {\n port.addEventListener('message', event => {\n listener(event.data);\n }, {\n signal\n });\n }\n };\n}\n\nexport { ThreadMessagePort, portToMessageTarget };\n","import {\n ARGUMENT_MESSAGES,\n FETCH_METHODS,\n isContainedPath,\n isFetchResponse,\n isRecord,\n isReservedRequestHeader,\n methodAllowsBody,\n type FetchMethod,\n type FetchRequest,\n} from '@tryghost/app-contracts';\n\nimport { GhostAppError, invalidArgument, invalidPath } from './errors.ts';\nimport type { GhostFetchInit, JsonBody } from './types.ts';\n\nconst JSON_BODY = 'Expected a body that can be sent as JSON';\n\n// The statuses a `Response` must be built without a body for, or its constructor throws.\nconst NULL_BODY_STATUSES = new Set([204, 205, 304]);\n\nfunction isJsonBody(value: unknown): value is JsonBody {\n if (Array.isArray(value)) {\n return true;\n }\n if (!isRecord(value)) {\n return false;\n }\n const prototype: unknown = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\n// A cycle or a BigInt makes `JSON.stringify` throw, and a `toJSON` that returns `undefined`\n// makes it return `undefined`.\nfunction toJson(body: JsonBody): string {\n let json: string | undefined;\n try {\n json = JSON.stringify(body) as string | undefined;\n } catch (error) {\n throw new GhostAppError('invalid_argument', JSON_BODY, { cause: error });\n }\n if (json === undefined) {\n throw invalidArgument(JSON_BODY);\n }\n return json;\n}\n\nfunction toHeaders(init: HeadersInit | undefined): Record<string, string> {\n let headers: Headers;\n try {\n headers = new Headers(init);\n } catch (error) {\n throw new GhostAppError('invalid_argument', 'Expected headers with valid names and values', {\n cause: error,\n });\n }\n // `Headers` lowercases the names, so a reserved header the app set is found in any case.\n const entries = [...headers.entries()];\n const reserved = entries.find(([name]) => isReservedRequestHeader(name));\n if (reserved) {\n throw invalidArgument(ARGUMENT_MESSAGES.reservedHeader(reserved[0]));\n }\n return Object.fromEntries(entries);\n}\n\n/**\n * Converts `fetch(path, init)` into the plain request Admin accepts. Only obvious mistakes are\n * refused here, using the same rules Admin applies; Admin checks everything again.\n */\nexport function toFetchRequest(path: string, init: GhostFetchInit = {}): FetchRequest {\n if (!isContainedPath(path)) {\n throw invalidPath(ARGUMENT_MESSAGES.fetchPath);\n }\n // The types rule this out, but a page without TypeScript can pass anything.\n if (typeof init !== 'object' || init === null) {\n throw invalidArgument('Expected options such as { method, headers, body }');\n }\n\n const { method: given = 'GET' } = init as { method?: unknown };\n const method = (typeof given === 'string' ? given.toUpperCase() : given) as FetchMethod;\n if (!FETCH_METHODS.includes(method)) {\n throw invalidArgument(ARGUMENT_MESSAGES.fetchMethod);\n }\n\n const headers = toHeaders(init.headers);\n const request: FetchRequest = { path, method };\n\n if (init.body !== undefined && init.body !== null) {\n if (!methodAllowsBody(method)) {\n throw invalidArgument(ARGUMENT_MESSAGES.fetchBody);\n }\n if (typeof init.body === 'string') {\n request.body = init.body;\n } else if (isJsonBody(init.body)) {\n request.body = toJson(init.body);\n } else {\n // Binary and streamed bodies cannot cross the channel as text.\n throw invalidArgument('Expected the body as text, or as an object or array to send as JSON');\n }\n }\n\n if (Object.keys(headers).length > 0) {\n request.headers = headers;\n }\n return request;\n}\n\nconst UNREADABLE_ANSWER = \"Ghost answered with a response this SDK doesn't understand\";\n\n/** Rebuilds Admin's response as the `Response` the app would have got from `fetch`. */\nexport function toResponse(answer: unknown): Response {\n if (!isFetchResponse(answer)) {\n throw new GhostAppError('rejected', UNREADABLE_ANSWER);\n }\n // The `Response` constructor throws on a header name or status text it can't hold.\n try {\n return new Response(NULL_BODY_STATUSES.has(answer.status) ? null : answer.body, {\n status: answer.status,\n statusText: answer.statusText,\n headers: answer.headers,\n });\n } catch (error) {\n throw new GhostAppError('rejected', UNREADABLE_ANSWER, { cause: error });\n }\n}\n","import { normaliseAppPath, type PathMove } from '@tryghost/app-contracts';\n\n/**\n * The page's route: the path, query and fragment of its URL, in the normalised form Admin\n * stores app paths in.\n */\nexport function currentRoute(): string {\n const { pathname, search, hash } = window.location;\n return normaliseAppPath(`${pathname}${search}${hash}`);\n}\n\n/** Whether a node is an HTML or SVG link, which the browser follows when it's clicked. */\nfunction isLink(node: EventTarget): node is Element {\n return (\n (node instanceof HTMLAnchorElement || (node instanceof SVGElement && node.localName === 'a')) &&\n node.hasAttribute('href')\n );\n}\n\nexport interface HistoryWatch {\n /**\n * Puts the page at `path` without adding a history entry, because Admin moved it there, and\n * dispatches `popstate` so the app's router shows it.\n */\n follow(path: string): void;\n /** Gives the page its own history methods and links back. */\n stop(): void;\n}\n\n/**\n * Makes Admin the owner of the page's history. A frame's history entries are part of the tab's,\n * and browsers keep them in ways Admin can't follow: Chromium and WebKit keep a removed frame's\n * entries, which left back steps that did nothing once the app's page opened again, and WebKit\n * applies Admin's replace after a frame's push to the entry before it. So the frame keeps a\n * single entry, and Admin keeps one for each of the app's moves.\n *\n * - `history.pushState` and `history.replaceState` replace the frame's entry, then report the\n * move to Admin as a push or a replace, which is how Admin records it. A move to the route the\n * page is already on isn't reported, so Admin never gets an entry that changes nothing.\n * - A click on a link to the app's own origin, which a router hasn't already handled, is reported\n * as a push, and the page then loads the link's address in place of its own entry. A link that\n * opens elsewhere (a `target`, `download`, or a modifier key) is left alone.\n * - When Admin moves the page, `follow` replaces the frame's entry and dispatches `popstate`.\n *\n * Not intercepted: a form that posts adds one entry of the frame's own, and so do a change to the\n * fragment through `location.hash` and the Navigation API, which have added the entry before\n * any event says so.\n */\nexport function watchHistory(\n moved: (route: string, move: PathMove) => Promise<void>,\n // How the page loads a link's address in place of its own entry. Tests pass their own.\n load: (url: string) => void = (url) => window.location.replace(url),\n): HistoryWatch {\n const { history } = window;\n const { pushState, replaceState } = history;\n let route = currentRoute();\n // The state the app gave each route, so following Admin back to one gives it back.\n const states = new Map<string, unknown>([[route, history.state]]);\n\n const report = (move: PathMove) => {\n const next = currentRoute();\n states.set(next, history.state);\n if (next !== route) {\n route = next;\n void moved(next, move);\n }\n };\n\n const push: History['pushState'] = (data, unused, url) => {\n replaceState.call(history, data, unused, url);\n report('push');\n };\n const replace: History['replaceState'] = (data, unused, url) => {\n replaceState.call(history, data, unused, url);\n report('replace');\n };\n history.pushState = push;\n history.replaceState = replace;\n\n const onClick = (event: MouseEvent) => {\n if (\n event.defaultPrevented ||\n event.button !== 0 ||\n event.metaKey ||\n event.ctrlKey ||\n event.shiftKey ||\n event.altKey\n ) {\n return;\n }\n // Found through the event's path, which reaches into shadow roots, and read through its\n // attributes, because an SVG link has none of `HTMLAnchorElement`'s properties.\n const link = event.composedPath().find(isLink);\n const target = link?.getAttribute('target') ?? '';\n if (!link || link.hasAttribute('download') || (target !== '' && target !== '_self')) {\n return;\n }\n const url = new URL(link.getAttribute('href') as string, document.baseURI);\n if (url.origin !== window.location.origin) {\n return;\n }\n event.preventDefault();\n const go = () => load(url.href);\n const next = normaliseAppPath(`${url.pathname}${url.search}${url.hash}`);\n if (next === route) {\n go();\n return;\n }\n route = next;\n // Admin records the move before the page leaves, so the next document starts where it is.\n moved(next, 'push').then(go, go);\n };\n document.addEventListener('click', onClick);\n\n return {\n follow(path) {\n route = path;\n const state = states.get(path) ?? null;\n replaceState.call(history, state, '', path);\n window.dispatchEvent(new PopStateEvent('popstate', { state }));\n },\n stop() {\n if (history.pushState === push) {\n history.pushState = pushState;\n }\n if (history.replaceState === replace) {\n history.replaceState = replaceState;\n }\n document.removeEventListener('click', onClick);\n },\n };\n}\n","import { TITLE_MAX_LENGTH, toPlainText } from '@tryghost/app-contracts';\n\n/**\n * Trims a title to what Admin accepts, without splitting a character in two. Admin refuses a\n * title containing a character that reorders or hides text, so the SDK drops those characters\n * rather than losing the whole title: a right-to-left title often contains a direction mark.\n */\nfunction clampTitle(title: string): string {\n const trimmed = toPlainText(title).trim();\n if (trimmed.length <= TITLE_MAX_LENGTH) {\n return trimmed;\n }\n const end = /[\\uD800-\\uDBFF]/.test(trimmed.charAt(TITLE_MAX_LENGTH - 1))\n ? TITLE_MAX_LENGTH - 1\n : TITLE_MAX_LENGTH;\n return trimmed.slice(0, end);\n}\n\n/**\n * Reports the page's title now and every time it changes, so Admin can show it as its own.\n * Returns a function that stops watching.\n *\n * A title can change in three ways, and frameworks use all three: its text is edited, its\n * element is replaced, or an element is added where there was none. Rather than distinguish\n * them, the SDK reads `document.title` after every batch of changes in `<head>` and reports it\n * only if it differs from the last one. A mutation observer already delivers each batch once,\n * in a microtask.\n */\nexport function watchTitle(report: (title: string) => void): () => void {\n let last: string | undefined;\n const check = () => {\n const title = clampTitle(document.title);\n if (title !== last) {\n last = title;\n report(title);\n }\n };\n\n check();\n const observer = new MutationObserver(check);\n observer.observe(document.head ?? document.documentElement, {\n subtree: true,\n childList: true,\n characterData: true,\n });\n return () => observer.disconnect();\n}\n","import { ThreadMessagePort } from '@quilted/threads';\nimport {\n ARGUMENT_MESSAGES,\n encodeBridgeError,\n type AppErrorCode,\n isContainedPath,\n isRecord,\n isStartContext,\n isTheme,\n type AppExports,\n type HostExports,\n type PathMove,\n type Place,\n type Theme,\n} from '@tryghost/app-contracts';\n\nimport {\n GhostAppError,\n fromHostError,\n invalidArgument,\n sessionEnded,\n unsupported,\n} from './errors.ts';\nimport { toFetchRequest, toResponse } from './fetch.ts';\nimport { currentRoute, watchHistory, type HistoryWatch } from './history.ts';\nimport { watchTitle } from './title.ts';\nimport type {\n Ghost,\n GhostFetchInit,\n GhostPath,\n Session,\n Site,\n Unsubscribe,\n User,\n} from './types.ts';\n\ntype HostCall<K extends keyof HostExports> = (\n ...args: Parameters<HostExports[K]>\n) => ReturnType<HostExports[K]>;\n\n/** Calls each listener the app registered, so that one that throws can't stop the others. */\nfunction notify<T>(listeners: ReadonlySet<(value: T) => void>, value: T) {\n for (const listener of [...listeners]) {\n try {\n listener(value);\n } catch (error) {\n // Rethrown outside the SDK, where the page's own error handling sees it.\n queueMicrotask(() => {\n throw error;\n });\n }\n }\n}\n\n/**\n * An error that refuses one of Admin's calls. Only its message reaches Admin, so the message\n * starts with the code, as Admin's own refusals do.\n */\nfunction refusal(code: AppErrorCode, detail: string): Error {\n return new Error(encodeBridgeError(code, detail));\n}\n\n/**\n * Returns the copy of an argument that will cross the channel, or throws `invalid_argument`\n * with `message` if it can't cross. The structured clone that carries a call only refuses a\n * symbol or a DOM node once the call is in progress, and the channel would proxy a function,\n * though no argument in the bridge's calls is a function. Cloning first refuses all of these\n * before anything is sent to Admin.\n */\nfunction cloneArgument<T>(value: T, message: string): T {\n try {\n return structuredClone(value);\n } catch (error) {\n throw new GhostAppError('invalid_argument', message, { cause: error });\n }\n}\n\nfunction subscribe<T>(listeners: Set<T>, listener: T): Unsubscribe {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n}\n\n/**\n * The parts of Admin's start context that `start` keeps. The theme and path can change, so\n * they are stored separately.\n */\ninterface StartedContext {\n site: Site;\n user: User;\n session: Session;\n}\n\nexport interface ChannelEvents {\n /** Admin started the app, and the connection is ready for it to use. */\n started(ghost: Ghost): void;\n /** The channel ended, before or after the start. */\n ended(error: GhostAppError): void;\n}\n\n/**\n * The channel to Admin over the port Admin handed the page, and the `Ghost` object the app\n * gets once Admin has called `start`. The channel itself stays inside the SDK.\n *\n * The channel ends in three cases: when the port closes, which browsers that fire `close` on\n * a port (and Node) report when Admin closes its end or its document goes away; when a call\n * fails because the thread has closed; or when Admin rejects a call with `session_ended`.\n * After that, every call rejects with the same error.\n */\nexport class Channel {\n readonly #port: MessagePort;\n readonly #thread: ThreadMessagePort<HostExports, AppExports>;\n // What this Admin exports, from its connect message.\n readonly #hostExports: ReadonlySet<string>;\n readonly #events: ChannelEvents;\n readonly #themeListeners = new Set<(theme: Readonly<Theme>) => void>();\n readonly #pathListeners = new Set<(path: string) => void>();\n readonly #endListeners = new Set<(error: GhostAppError) => void>();\n #context: StartedContext | undefined;\n #theme: Readonly<Theme> | undefined;\n #path = '/';\n #ended: GhostAppError | undefined;\n #stopWatchingTitle: (() => void) | undefined;\n #history: HistoryWatch | undefined;\n // Counts the page's moves, so an answer to one the page has since moved on from is ignored.\n #moves = 0;\n\n constructor(port: MessagePort, hostExports: readonly string[], events: ChannelEvents) {\n this.#port = port;\n this.#hostExports = new Set(hostExports);\n this.#events = events;\n this.#thread = new ThreadMessagePort<HostExports, AppExports>(port, {\n exports: {\n start: async (context) => this.#start(context),\n themeChanged: async (theme) => this.#themeChanged(theme),\n pathChanged: async (path) => this.#pathChanged(path),\n },\n });\n port.addEventListener('close', () => this.end(sessionEnded()));\n // A message that could not be read is a call that will never be answered.\n port.addEventListener('messageerror', () => this.end(sessionEnded()));\n port.start();\n }\n\n #start(context: unknown) {\n if (this.#context) {\n return;\n }\n if (!isStartContext(context)) {\n const detail = \"Ghost started the app with a context this SDK doesn't understand\";\n // End the channel only after Admin has received the refusal, so Admin learns why instead\n // of waiting for its timeout.\n setTimeout(() => this.end(new GhostAppError('invalid_context', detail)), 0);\n throw refusal('invalid_context', detail);\n }\n this.#context = {\n site: Object.freeze({ ...context.site }),\n user: Object.freeze({ ...context.user }),\n session: Object.freeze({ ...context.session }),\n };\n this.#theme = Object.freeze({ ...context.theme });\n // Admin owns the history from here on. The page's own address is its route: Admin loads a\n // new frame at its own path, so the two differ only when the page's server redirected it or\n // a form or link loaded another page in place, and then Admin follows the page.\n this.#history = watchHistory((route, move) => this.#moved(route, move));\n this.#path = currentRoute();\n if (this.#path !== context.path) {\n void this.#moved(this.#path, 'replace');\n }\n // Report the title before `start` returns, so Admin has it by the time it shows the page.\n // An older Admin without `titleChanged` keeps its own title.\n if (this.#hostExports.has('titleChanged')) {\n this.#stopWatchingTitle = watchTitle((title) => {\n this.#call('titleChanged', title).catch(() => {\n // If Admin refuses a title, it keeps showing its own.\n });\n });\n }\n this.#events.started(this.ghost);\n }\n\n #themeChanged(theme: unknown) {\n this.#assertStarted();\n if (!isTheme(theme)) {\n throw refusal('invalid_argument', \"Ghost sent a theme this SDK doesn't understand\");\n }\n this.#theme = Object.freeze({ ...theme });\n notify(this.#themeListeners, this.#theme);\n }\n\n #pathChanged(path: unknown) {\n this.#assertStarted();\n if (!isContainedPath(path)) {\n throw refusal('invalid_argument', \"Ghost sent a path this SDK doesn't understand\");\n }\n this.#path = path;\n this.#history?.follow(path);\n notify(this.#pathListeners, path);\n }\n\n /**\n * Reports a move the page made. Resolves once Admin has answered, with the path Admin now has\n * for the app, or has refused; a refused move leaves the page where it is.\n */\n async #moved(route: string, move: PathMove): Promise<void> {\n this.#path = route;\n this.#moves += 1;\n const thisMove = this.#moves;\n try {\n const adminPath = await this.#call('pathChanged', route, move);\n // Admin's answer, rather than `route`: it's Admin's own path when Admin didn't follow\n // the move, such as when the publisher is leaving the app, and Admin then moves the page\n // back with `pathChanged`. An answer to an earlier move is out of date.\n if (thisMove === this.#moves && isContainedPath(adminPath)) {\n this.#path = adminPath;\n }\n } catch {\n // Refused, or the session ended: either way there's nothing for the page to do.\n }\n }\n\n #assertStarted() {\n if (!this.#context) {\n throw refusal('invalid_context', 'Ghost has not started the app yet');\n }\n }\n\n async #call<K extends keyof HostExports>(\n name: K,\n ...args: Parameters<HostExports[K]>\n ): Promise<Awaited<ReturnType<HostExports[K]>>> {\n if (this.#ended) {\n throw this.#ended;\n }\n if (!this.#hostExports.has(name)) {\n throw unsupported(name);\n }\n try {\n const call = this.#thread.imports[name] as HostCall<K>;\n return await call(...args);\n } catch (error) {\n if (this.#thread.closed) {\n throw this.end(sessionEnded());\n }\n const appError = fromHostError(error, name);\n if (appError.code === 'session_ended') {\n this.end(appError);\n }\n throw appError;\n }\n }\n\n /**\n * Ends the channel. Only the first call has an effect: pending and later calls reject with\n * its `error`. Returns the error the channel ended with.\n */\n end(error: GhostAppError): GhostAppError {\n if (this.#ended) {\n return this.#ended;\n }\n this.#ended = error;\n this.#stopWatchingTitle?.();\n this.#history?.stop();\n this.#thread.close();\n this.#port.close();\n this.#events.ended(error);\n notify(this.#endListeners, error);\n this.#endListeners.clear();\n return error;\n }\n\n /**\n * The `Ghost` object the app gets once `start` has set the context. It has only the members\n * its type declares, so no part of the channel, such as `end`, is reachable from the app.\n */\n readonly ghost: Ghost = this.#createGhost();\n\n #createGhost(): Ghost {\n const context = () => this.#context as StartedContext;\n const theme = () => this.#theme as Readonly<Theme>;\n const connected = () => this.#ended === undefined;\n return Object.freeze({\n get site(): Site {\n return context().site;\n },\n get user(): User {\n return context().user;\n },\n get theme(): Readonly<Theme> {\n return theme();\n },\n get session(): Session {\n return context().session;\n },\n get connected(): boolean {\n return connected();\n },\n path: this.#createPath(),\n onThemeChange: (callback: (theme: Readonly<Theme>) => void): Unsubscribe =>\n subscribe(this.#themeListeners, callback),\n onPathChange: (callback: (path: string) => void): Unsubscribe =>\n subscribe(this.#pathListeners, callback),\n onSessionEnd: (callback: (error: GhostAppError) => void): Unsubscribe =>\n this.#onSessionEnd(callback),\n fetch: (path: string, init?: GhostFetchInit): Promise<Response> => this.#fetch(path, init),\n open: (place: Place): Promise<void> => this.#open(place),\n });\n }\n\n #createPath(): GhostPath {\n const current = () => this.#path;\n return Object.freeze({\n get current(): string {\n return current();\n },\n });\n }\n\n #onSessionEnd(callback: (error: GhostAppError) => void): Unsubscribe {\n const ended = this.#ended;\n if (ended) {\n // Notify it in a microtask, as an earlier subscriber would be, unless it has\n // unsubscribed by then.\n let left = false;\n queueMicrotask(() => {\n if (!left) {\n callback(ended);\n }\n });\n return () => {\n left = true;\n };\n }\n return subscribe(this.#endListeners, callback);\n }\n\n async #fetch(path: string, init?: GhostFetchInit): Promise<Response> {\n const request = toFetchRequest(path, init);\n return toResponse(await this.#call('fetch', request));\n }\n\n async #open(place: Place): Promise<void> {\n if (!isRecord(place)) {\n throw invalidArgument(ARGUMENT_MESSAGES.place);\n }\n await this.#call('open', cloneArgument(place, ARGUMENT_MESSAGES.place));\n }\n}\n","declare const __SDK_VERSION__: string;\n\n/**\n * The SDK's version, sent in the hello for Admin's logs. The build and the tests replace\n * `__SDK_VERSION__` with the version in package.json, because the source stays within `src/`\n * and doesn't read package.json.\n */\nexport const SDK_VERSION: string = __SDK_VERSION__;\n","import {\n HELLO_MESSAGE_TYPE,\n START_TIMEOUT_MS,\n isConnectMessage,\n isRecord,\n type HelloMessage,\n} from '@tryghost/app-contracts';\n\nimport { GhostAppError, invalidArgument } from './errors.ts';\nimport { Channel } from './session.ts';\nimport type { ConnectOptions, Ghost } from './types.ts';\nimport { SDK_VERSION } from './version.ts';\n\n/**\n * How often, in milliseconds, the SDK repeats the hello until Admin answers. Admin may only\n * start listening after the page has loaded and sent its first hello, so one hello is not\n * enough.\n */\nconst HELLO_INTERVAL = 250;\n\n/**\n * The target origin for the hello: the embedding page's origin where the browser exposes it\n * (`location.ancestorOrigins`, in Chromium and WebKit), and `'*'` elsewhere. The hello grants\n * nothing: the port goes the other way, and Admin addresses it to this page's origin only.\n * `document.referrer` doesn't work here: once the page has navigated within itself, it holds\n * the page's own origin.\n */\nfunction parentOrigin(): string {\n const origin = window.location.ancestorOrigins?.[0];\n return origin && origin !== 'null' ? origin : '*';\n}\n\n/**\n * The global key where the first copy of the SDK to connect claims the page. It is a symbol\n * from the global registry, so a second copy bundled into the same page finds the same key.\n */\nconst PAGE_CLAIM = Symbol.for('@tryghost/app-sdk');\n\n/**\n * The claim also holds the hello's `document` ID. It's made when the SDK loads, so every\n * `connect()` in a document sends the same ID, and a new document (after a reload, a form post\n * or a link) gets a new one. It's random rather than `performance.timeOrigin`, which some\n * privacy-focused browsers round to 16–100 ms, so two documents loaded in quick succession\n * could share it. `Math.random` is enough here, and unlike `crypto.randomUUID` it works on the\n * plain HTTP origins apps use in development.\n */\nconst thisCopy = Object.freeze({\n sdk: SDK_VERSION,\n document: `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,\n});\n\n/** Claims the page for this copy of the SDK unless another copy has. Returns whether it did. */\nfunction claimPage(): boolean {\n const page = globalThis as unknown as Record<symbol, unknown>;\n page[PAGE_CLAIM] ??= thisCopy;\n return page[PAGE_CLAIM] === thisCopy;\n}\n\n/**\n * The longest delay `setTimeout` supports. It treats anything longer as 0, so the timeout\n * would fire immediately.\n */\nconst TIMEOUT_MAX = 2 ** 31 - 1;\n\nfunction handshake(\n options: ConnectOptions,\n onEnded: (error: GhostAppError) => void,\n): Promise<Ghost> {\n if (!isRecord(options)) {\n return Promise.reject(invalidArgument('Expected options such as { timeout: 10000 }'));\n }\n // By default, wait as long as Admin gives the page. Waiting longer would mean waiting on a\n // frame Admin has already given up on.\n const { timeout = START_TIMEOUT_MS } = options;\n if (typeof timeout !== 'number' || !(timeout > 0) || !(timeout <= TIMEOUT_MAX)) {\n return Promise.reject(\n invalidArgument(`Expected a timeout in milliseconds, above 0 and at most ${TIMEOUT_MAX}`),\n );\n }\n if (typeof window === 'undefined' || window.parent === window) {\n return Promise.reject(\n new GhostAppError('not_framed', 'This page is not open inside Ghost Admin'),\n );\n }\n\n const parent = window.parent;\n const targetOrigin = parentOrigin();\n\n return new Promise<Ghost>((resolve, reject) => {\n const stopWaiting = () => {\n clearInterval(helloTimer);\n clearTimeout(timeoutTimer);\n window.removeEventListener('message', onMessage);\n };\n\n // A promise ignores `reject` once it has settled, so a failure after `started` changes\n // nothing.\n const fail = (error: GhostAppError) => {\n stopWaiting();\n reject(error);\n };\n\n // The channel is bound to the first valid answer from the parent window. The listener is\n // removed as soon as that answer arrives, so later answers are ignored.\n const onMessage = (event: MessageEvent) => {\n const port = event.ports?.[0];\n if (\n event.source !== parent ||\n !isConnectMessage(event.data) ||\n !port ||\n (targetOrigin !== '*' && event.origin !== targetOrigin)\n ) {\n return;\n }\n clearInterval(helloTimer);\n window.removeEventListener('message', onMessage);\n channel = new Channel(port, event.data.exports, {\n started: (ghost) => {\n stopWaiting();\n resolve(ghost);\n },\n ended: (error) => {\n fail(error);\n onEnded(error);\n },\n });\n };\n\n const hello: HelloMessage = {\n type: HELLO_MESSAGE_TYPE,\n sdk: SDK_VERSION,\n document: thisCopy.document,\n };\n const sayHello = () => {\n parent.postMessage(hello, targetOrigin);\n };\n\n let channel: Channel | undefined;\n window.addEventListener('message', onMessage);\n sayHello();\n const helloTimer = setInterval(sayHello, HELLO_INTERVAL);\n const timeoutTimer = setTimeout(() => {\n const error = new GhostAppError('not_connected', 'Ghost Admin did not start the app in time');\n fail(error);\n channel?.end(error);\n }, timeout);\n });\n}\n\nlet connecting: Promise<Ghost> | undefined;\n// The error the page's connection ended with, after Admin answered it. Admin answers each\n// document only once, so this connection was the page's only one.\nlet spent: GhostAppError | undefined;\n\n// Forgets an attempt only if it is still the shared one: an attempt that ended may report\n// that after a newer attempt has started.\nfunction forget(attempt: Promise<Ghost>) {\n if (connecting === attempt) {\n connecting = undefined;\n }\n}\n\n/**\n * Connects to Ghost Admin, which must frame the page, and resolves once Admin has started the\n * app. Safe to call as soon as the page loads.\n *\n * Every call shares one connection, and the first call's options apply. Only one copy of the\n * SDK in a page can connect; any other copy rejects with `duplicate_sdk`. Admin answers each\n * document only once, so after it answers, that connection is the page's only one. Once it\n * fails or its session ends, every call rejects with the error it ended with, and only a new\n * document (after a reload, for example) can connect again. A failure before Admin answered,\n * such as a bad option or a timeout, can be retried.\n */\nexport function connect(options: ConnectOptions = {}): Promise<Ghost> {\n // Two copies would both send a hello for the same document, and Admin answers each document\n // only once.\n if (!claimPage()) {\n return Promise.reject(\n new GhostAppError(\n 'duplicate_sdk',\n 'This page loads the app SDK more than once; load one copy, which every part of the page shares',\n ),\n );\n }\n if (spent) {\n return Promise.reject(spent);\n }\n if (!connecting) {\n const attempt: Promise<Ghost> = handshake(options, (error) => {\n spent = error;\n forget(attempt);\n }).catch((error: unknown) => {\n forget(attempt);\n throw error;\n });\n connecting = attempt;\n }\n return connecting;\n}\n"],"x_google_ignoreList":[3,4,5,6,7,8,9,10,11],"mappings":";AAMA,IAAM,UAAU;AACG,IAAI,OAAO,KAAK,QAAQ,MAAM,GAAG;AACpD,IAAM,iBAAiB,IAAI,OAAO,KAAK,QAAQ,IAAI,IAAI;;AAMvD,SAAgB,YAAY,OAAO;CAC/B,OAAO,MAAM,QAAQ,gBAAgB,EAAE;AAC3C;;;;;;;;;;;;;;ACLA,IAAa,qBAAqB;;;;;;;AASlC,IAAa,mBAAmB;;;;;AAOhC,IAAa,gBAAgB;CAAC;CAAO;CAAQ;CAAO;AAAQ;;;;;AAK5D,SAAgB,iBAAiB,QAAQ;CACrC,OAAO,WAAW;AACtB;AAOA,IAAM,0BAA0B;;;;;;;AAOhC,SAAgB,wBAAwB,MAAM;CAC1C,OAAO,wBAAwB,KAAK,IAAI;AAC5C;;;;;;AAMA,IAAa,oBAAoB;CAC7B,WAAW;CACX,aAAa,yBAAyB,cAAc,KAAK,IAAI;CAC7D,WAAW;CAGX,iBAAiB,SAAS,eAAe,KAAK,YAAY,EAAE;CAC5D,UAAU;CACV,SAAS;CACT,U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AAK;CAE7B,IAAI,CAAC,YAAY;EACf,MAAM,UAA0B,UAAU,UAAU,UAAU;GAC5D,QAAQ;GACR,OAAO,OAAO;EAChB,CAAC,CAAC,CAAC,OAAO,UAAmB;GAC3B,OAAO,OAAO;GACd,MAAM;EACR,CAAC;EACD,aAAa;CACf;CACA,OAAO;AACT"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,37 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tryghost/app-sdk",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.0-alpha.1",
|
|
4
|
+
"description": "The SDK apps use to talk to Ghost from inside Admin",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"author": "Ghost Foundation",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/TryGhost/Ghost.git",
|
|
10
|
+
"directory": "packages/app-sdk"
|
|
11
|
+
},
|
|
12
|
+
"files": [
|
|
13
|
+
"build",
|
|
14
|
+
"dist"
|
|
15
|
+
],
|
|
16
|
+
"type": "module",
|
|
17
|
+
"main": "build/index.js",
|
|
18
|
+
"types": "build/index.d.ts",
|
|
19
|
+
"exports": {
|
|
20
|
+
".": {
|
|
21
|
+
"types": "./build/index.d.ts",
|
|
22
|
+
"default": "./build/index.js"
|
|
23
|
+
}
|
|
24
|
+
},
|
|
25
|
+
"dependencies": {
|
|
26
|
+
"@quilted/threads": "4.1.0"
|
|
27
|
+
},
|
|
28
|
+
"scripts": {
|
|
29
|
+
"build": "vite build --mode package && vite build",
|
|
30
|
+
"test:unit": "NODE_ENV=testing vitest run --coverage",
|
|
31
|
+
"test": "pnpm run '/^test:/'",
|
|
32
|
+
"test:types": "tsc --noEmit -p test/tsconfig.json",
|
|
33
|
+
"lint:code": "eslint src/ --cache",
|
|
34
|
+
"lint:test": "eslint test/ --cache",
|
|
35
|
+
"lint": "pnpm run '/^lint:/'"
|
|
36
|
+
}
|
|
6
37
|
}
|