@dioramajs/core 0.1.0 → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/index.d.ts +23 -9
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +106 -19
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/src/index.ts +1 -1
- package/src/web/follow.ts +109 -17
- package/src/web/stage.ts +43 -11
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["defaults"],"sources":["../package.json","../src/version.ts","../src/kernel/errors.ts","../src/kernel/order.ts","../src/kernel/util.ts","../src/kernel/plugin.ts","../src/kernel/semver.ts","../src/kernel/config.ts","../src/kernel/events.ts","../src/kernel/hooks.ts","../src/kernel/drivers.ts","../src/kernel/loop.ts","../src/kernel/scope.ts","../src/kernel/signals.ts","../src/kernel/view.ts","../src/kernel/app.ts","../src/web/body.ts","../src/web/anchors.ts","../src/web/motion.ts","../src/web/pointer.ts","../src/web/scroll.ts","../src/web/follow.ts","../src/web/stage.ts","../src/web/visibility.ts","../src/index.ts"],"sourcesContent":["","import { version } from '../package.json'\n\n/** Version of @dioramajs/core. */\nexport const VERSION: string = version\n","import { withDocs } from '../dev'\nimport type { DioramaErrorOptions, ErrorCode, ErrorSource } from './types'\n\nconst CODE_BY_SOURCE: Record<ErrorSource, ErrorCode> = {\n config: 'CONFIG_INVALID',\n setup: 'PLUGIN_SETUP',\n listener: 'LISTENER',\n hook: 'HOOK',\n system: 'SYSTEM',\n effect: 'EFFECT',\n dispose: 'DISPOSE',\n loop: 'LOOP',\n report: 'REPORTED',\n}\n\n/** An error of the kernel or a plugin. Its message reads `[diorama] CODE: message`. */\nexport class DioramaError extends Error {\n /** Error code, the key of its page in the docs. */\n readonly code: ErrorCode\n /** Plugin the error comes from, if any. */\n readonly plugin: string | undefined\n /** Every problem found, when the error collects several. */\n readonly problems: readonly DioramaError[]\n\n constructor(code: ErrorCode, message: string, options: DioramaErrorOptions = {}) {\n const prefix = options.plugin ? `[diorama:${options.plugin}]` : '[diorama]'\n super(\n withDocs(`${prefix} ${code}: ${message}`, code),\n options.cause === undefined ? undefined : { cause: options.cause },\n )\n this.name = 'DioramaError'\n this.code = code\n this.plugin = options.plugin\n this.problems = options.problems ?? []\n }\n}\n\n/** Whether `value` is a `DioramaError`, with `code` if one is given. */\nexport function isDioramaError(value: unknown, code?: ErrorCode): value is DioramaError {\n if (typeof value !== 'object' || value === null) return false\n // Checks the shape, not the class, so errors from another copy of the package match too.\n const candidate = value as { name?: unknown; code?: unknown }\n return (\n candidate.name === 'DioramaError' &&\n typeof candidate.code === 'string' &&\n (!code || candidate.code === code)\n )\n}\n\nexport function messageOf(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n\n/** Wraps anything thrown as a `DioramaError` whose code says where it was caught. */\nexport function toDioramaError(\n error: unknown,\n source: ErrorSource,\n plugin: string | undefined,\n): DioramaError {\n if (isDioramaError(error)) return error\n return new DioramaError(CODE_BY_SOURCE[source], messageOf(error), { plugin, cause: error })\n}\n","/** An entry ordered by `before`/`after` labels: a hook handler or a system. */\nexport interface Orderable {\n /** Names that `before` and `after` of other entries can refer to. */\n readonly labels: readonly string[]\n readonly before: readonly string[]\n readonly after: readonly string[]\n /** Owning plugin's ordinal. App code uses Infinity and runs after plugins. */\n readonly rank: number\n /** Registration order, the last tie-breaker. */\n readonly seq: number\n}\n\nexport const orderRefs = (ref: string | readonly string[] | undefined): readonly string[] => {\n if (ref === undefined) return []\n return typeof ref === 'string' ? [ref] : ref\n}\n\n/**\n * Topological sort (Kahn's algorithm) over nodes `0..count-1`, where `edges[a]` lists the nodes\n * that must come after `a`. Among the nodes ready at each step it takes the `less`-smallest, so\n * the result is deterministic. Returns the order, or the nodes left inside cycles.\n */\nexport function topologicalSort(\n count: number,\n edges: readonly (readonly number[])[],\n less: (a: number, b: number) => boolean,\n): number[] | { stuck: number[] } {\n const indegree = new Array<number>(count).fill(0)\n for (const targets of edges) {\n for (const target of targets) indegree[target] = (indegree[target] ?? 0) + 1\n }\n const done = new Array<boolean>(count).fill(false)\n const order: number[] = []\n for (;;) {\n let next = -1\n for (let i = 0; i < count; i++) {\n if (!done[i] && indegree[i] === 0 && (next < 0 || less(i, next))) next = i\n }\n if (next < 0) break\n done[next] = true\n order.push(next)\n for (const target of edges[next] ?? []) indegree[target] = (indegree[target] ?? 0) - 1\n }\n if (order.length === count) return order\n return { stuck: [...done.keys()].filter((i) => !done[i]) }\n}\n\n/** One concrete cycle among `stuck` nodes, for error messages. */\nexport function findCycle(\n edges: readonly (readonly number[])[],\n stuck: readonly number[],\n): number[] {\n const inStuck = new Set(stuck)\n const visiting = new Set<number>()\n const visited = new Set<number>()\n const path: number[] = []\n // Depth-first search. Reaching a node still on the path closes a cycle.\n const visit = (node: number): number[] | undefined => {\n visiting.add(node)\n path.push(node)\n for (const next of edges[node] ?? []) {\n if (!inStuck.has(next) || visited.has(next)) continue\n if (visiting.has(next)) return [...path.slice(path.indexOf(next)), next]\n const found = visit(next)\n if (found) return found\n }\n path.pop()\n visiting.delete(node)\n visited.add(node)\n return undefined\n }\n for (const node of stuck) {\n const found = visited.has(node) ? undefined : visit(node)\n if (found) return found\n }\n return [...stuck]\n}\n\n/** Orders entries by before/after, then by (rank, seq). Returns the cycle if there is one. */\nexport function sortOrderables<T extends Orderable>(items: readonly T[]): T[] | { cycle: T[] } {\n const edges: number[][] = items.map(() => [])\n items.forEach((a, i) => {\n items.forEach((b, j) => {\n if (i === j) return\n if (a.before.some((label) => b.labels.includes(label))) edges[i]?.push(j)\n if (a.after.some((label) => b.labels.includes(label))) edges[j]?.push(i)\n })\n })\n const less = (a: number, b: number): boolean => {\n const first = items[a] as T\n const second = items[b] as T\n return first.rank !== second.rank ? first.rank < second.rank : first.seq < second.seq\n }\n const result = topologicalSort(items.length, edges, less)\n if (Array.isArray(result)) return result.map((i) => items[i] as T)\n return { cycle: findCycle(edges, result.stuck).map((i) => items[i] as T) }\n}\n","import type { Logger, LogLevel } from './types'\n\nconst LEVELS: Record<LogLevel, number> = { debug: 0, info: 1, warn: 2, error: 3, silent: 4 }\n\nexport const noop = (): void => {}\n\nexport const resolved: Promise<void> = Promise.resolve()\n\nexport function isThenable(value: unknown): value is PromiseLike<unknown> {\n return (\n (typeof value === 'object' || typeof value === 'function') &&\n value !== null &&\n typeof (value as { then?: unknown }).then === 'function'\n )\n}\n\n/** Copies `base` and overwrites it with the keys of `next` that are not `undefined`. */\nexport function mergeOptions(base: object, next: object | undefined): Record<string, unknown> {\n const result: Record<string, unknown> = { ...base }\n if (!next) return result\n for (const [key, value] of Object.entries(next)) {\n if (value !== undefined) result[key] = value\n }\n return result\n}\n\nexport function shallowEqual(a: object, b: object): boolean {\n const keys = Object.keys(a)\n if (keys.length !== Object.keys(b).length) return false\n const first = a as Record<string, unknown>\n const second = b as Record<string, unknown>\n return keys.every((key) => Object.is(first[key], second[key]))\n}\n\nexport function perfNow(): number {\n return typeof performance === 'undefined' ? Date.now() : performance.now()\n}\n\n/** Forwards to `sink` the calls at `level` or above, after `prefix` if one is given. */\nexport function createLogger(sink: Logger, level: LogLevel, prefix: string): Logger {\n const threshold = LEVELS[level]\n const forward =\n (method: keyof Logger) =>\n (...data: unknown[]): void => {\n if (LEVELS[method] < threshold) return\n if (prefix) sink[method](prefix, ...data)\n else sink[method](...data)\n }\n return {\n debug: forward('debug'),\n info: forward('info'),\n warn: forward('warn'),\n error: forward('error'),\n }\n}\n","import type {\n AnyPlugin,\n DependencyRef,\n Empty,\n OptionsOf,\n Plugin,\n PluginDefinition,\n PluginEntry,\n Preset,\n PresetDefinition,\n PresetEntry,\n PresetPlugins,\n RequiredOptions,\n ServiceFor,\n StandardSchemaV1,\n} from './types'\nimport { mergeOptions } from './util'\n\n// Registry symbols, so plugins and presets from another copy of the package are recognized too.\nconst PLUGIN = Symbol.for('diorama.plugin')\nconst PRESET = Symbol.for('diorama.preset')\n\n/** A plugin definition with its type parameters erased, as the kernel sees it. */\nexport interface Definition {\n readonly name: string\n readonly version?: string\n readonly core?: string\n readonly dependencies?: readonly DependencyRef[]\n readonly optionalDependencies?: readonly DependencyRef[]\n readonly defaults?: object\n readonly schema?: StandardSchemaV1\n readonly critical?: boolean\n setup(app: unknown, options: unknown): unknown\n}\n\n/** Name of a dependency given as a string or as a plugin. */\nexport const refName = (ref: unknown): string | undefined => {\n if (typeof ref === 'string') return ref\n const name = (ref as { name?: unknown } | null)?.name\n return typeof name === 'string' ? name : undefined\n}\n\n/** The definition behind a plugin made by `definePlugin`, or `undefined` for anything else. */\nexport const definitionOf = (value: unknown): Definition | undefined =>\n typeof value === 'function' ? (value as { [PLUGIN]?: Definition })[PLUGIN] : undefined\n\nexport const isPreset = (value: unknown): value is Preset =>\n typeof value === 'object' && value !== null && PRESET in value\n\n/** Problems reported as PLUGIN_INVALID at start. `definePlugin` itself never throws. */\nexport function validateDefinition(def: Definition): string[] {\n const problems: string[] = []\n if (typeof def.name !== 'string' || !/^[a-z][A-Za-z0-9]*$/.test(def.name)) {\n problems.push(`name \"${String(def.name)}\" must be a lowerCamelCase identifier`)\n }\n if (typeof def.setup !== 'function') problems.push('setup must be a function')\n const dependencyLists = [def.dependencies ?? [], def.optionalDependencies ?? []]\n if (!dependencyLists.every(Array.isArray)) problems.push('dependencies must be arrays')\n else if (dependencyLists.flat().some((ref) => refName(ref) === undefined)) {\n problems.push('dependencies must be names or plugins')\n }\n if (def.core !== undefined && typeof def.core !== 'string') {\n problems.push('core must be a semver range')\n }\n if (def.defaults !== undefined && (typeof def.defaults !== 'object' || def.defaults === null)) {\n problems.push('defaults must be an object')\n }\n if (def.schema !== undefined && typeof def.schema?.['~standard']?.validate !== 'function') {\n problems.push('schema must implement Standard Schema')\n }\n return problems\n}\n\n/** A frozen plugin function carrying `options`. Calling it merges more options into a copy. */\nfunction makePlugin(def: Definition, options: Readonly<Record<string, unknown>>): AnyPlugin {\n const plugin = (next?: object): AnyPlugin => makePlugin(def, mergeOptions(options, next))\n const names = (list?: readonly DependencyRef[]) =>\n Object.freeze(Array.isArray(list) ? list.map((ref) => refName(ref) ?? '') : [])\n Object.defineProperties(plugin, {\n name: { value: def.name },\n version: { value: def.version, enumerable: true },\n options: { value: Object.freeze({ ...options }), enumerable: true },\n defaults: { value: Object.freeze({ ...def.defaults }), enumerable: true },\n schema: { value: def.schema, enumerable: true },\n dependencies: { value: names(def.dependencies), enumerable: true },\n optionalDependencies: { value: names(def.optionalDependencies), enumerable: true },\n [PLUGIN]: { value: def },\n })\n return Object.freeze(plugin) as unknown as AnyPlugin\n}\n\n/**\n * Defines a plugin. The result is a frozen function: call it with options for a configured copy.\n */\nexport function definePlugin<\n const N extends string,\n O extends object = Empty,\n DO extends Partial<OptionsOf<O, DO, SO>> = Empty,\n S = void,\n const D extends readonly DependencyRef[] = [],\n const OD extends readonly DependencyRef[] = [],\n SI = unknown,\n SO extends object = Empty,\n>(\n definition: PluginDefinition<N, O, DO, S, D, OD, SI, SO>,\n): Plugin<\n N,\n OptionsOf<O, DO, SO>,\n ServiceFor<N, S>,\n RequiredOptions<OptionsOf<O, DO, SO>, DO, SI>\n> {\n return makePlugin(definition as unknown as Definition, {}) as never\n}\n\n/** Groups plugins and other presets under one name for `createApp({ presets })`. */\nexport function definePreset<\n const E extends readonly PluginEntry[] = [],\n const PS extends readonly PresetEntry[] = [],\n>(\n definition: PresetDefinition<E, PS>,\n): Preset<Extract<E[number], AnyPlugin> | PresetPlugins<PS[number]>> {\n return Object.freeze({\n name: definition.name,\n plugins: frozenCopy(definition.plugins),\n presets: frozenCopy(definition.presets),\n [PRESET]: true,\n }) as never\n}\n\n// Non-arrays pass through untouched so createApp reports them instead of definePreset throwing.\nconst frozenCopy = <T>(list: readonly T[] | undefined): readonly T[] =>\n Array.isArray(list) ? Object.freeze([...list]) : (list ?? [])\n","/**\n * A semver subset: `^`, `~`, x-ranges, comparators and `||` groups. Unparsable input never\n * satisfies a range.\n * @module\n */\n\ntype Triple = [major: number, minor: number, patch: number]\n\ninterface Version {\n readonly triple: Triple\n /** Prerelease identifiers: `1.0.0-beta.2` has `['beta', '2']`. */\n readonly pre: readonly string[]\n}\n\ninterface Comparator {\n readonly op: '<' | '<=' | '>' | '>=' | '='\n readonly version: Version\n}\n\nconst VERSION_RE = /^v?(\\d+)\\.(\\d+)\\.(\\d+)(?:-([0-9A-Za-z.-]+))?(?:\\+[0-9A-Za-z.-]+)?$/\nconst PART = '(\\\\*|x|X|\\\\d+)'\nconst COMPARATOR_RE = new RegExp(\n `^(\\\\^|~|>=|<=|>|<|=)?v?${PART}(?:\\\\.${PART})?(?:\\\\.${PART})?(?:-([0-9A-Za-z.-]+))?(?:\\\\+[0-9A-Za-z.-]+)?$`,\n)\n\n/** Whether `version` is within a semver `range` such as `^1.2.0 || >=2`. */\nexport function satisfies(version: string, range: string): boolean {\n const parsed = parseVersion(version)\n if (!parsed) return false\n return range.split('||').some((group) => satisfiesGroup(parsed, group))\n}\n\n/** Whether `version` passes every comparator of one `||` group. */\nfunction satisfiesGroup(version: Version, group: string): boolean {\n const tokens = group\n .trim()\n .replace(/(\\^|~|>=|<=|>|<|=)\\s+/g, '$1')\n .split(/\\s+/)\n .filter(Boolean)\n const comparators: Comparator[] = []\n for (const token of tokens) {\n const expanded = parseComparator(token)\n if (!expanded) return false\n comparators.push(...expanded)\n }\n if (!comparators.every((comparator) => matches(version, comparator))) return false\n if (!version.pre.length) return true\n // A prerelease matches only a comparator with a prerelease on the same major.minor.patch.\n const plain = makeVersion(...version.triple)\n return comparators.some(\n (comparator) =>\n comparator.version.pre.length > 0 &&\n compare(makeVersion(...comparator.version.triple), plain) === 0,\n )\n}\n\nfunction parseVersion(text: string): Version | undefined {\n const match = VERSION_RE.exec(text.trim())\n if (!match) return undefined\n const triple: Triple = [Number(match[1]), Number(match[2]), Number(match[3])]\n return { triple, pre: match[4] ? match[4].split('.') : [] }\n}\n\n/** Expands one comparator (`^1.2`, `~1`, `>=2.0.0`) into plain comparisons. */\nfunction parseComparator(token: string): Comparator[] | undefined {\n const match = COMPARATOR_RE.exec(token)\n if (!match) return undefined\n const op = match[1] ?? ''\n const [majorPart, minorPart, patchPart] = [match[2], match[3], match[4]]\n const pre = match[5] ? match[5].split('.') : []\n if (isWild(majorPart)) {\n return op === '' || op === '=' || op === '>=' || op === '<=' ? [] : undefined\n }\n const major = Number(majorPart)\n const minor = isWild(minorPart) ? undefined : Number(minorPart)\n const patch = isWild(patchPart) ? undefined : Number(patchPart)\n\n if (op === '^') {\n const low = makeVersion(major, minor ?? 0, patch ?? 0, pre)\n return between(low, caretLimit(major, minor, patch))\n }\n const partial = minor === undefined || patch === undefined\n if (op === '~' || ((op === '' || op === '=') && partial)) {\n const low = makeVersion(major, minor ?? 0, patch ?? 0, pre)\n const high =\n minor === undefined ? makeVersion(major + 1, 0, 0) : makeVersion(major, minor + 1, 0)\n return between(low, high)\n }\n if (partial) {\n const next =\n minor === undefined ? makeVersion(major + 1, 0, 0) : makeVersion(major, minor + 1, 0)\n const base = makeVersion(major, minor ?? 0, 0)\n if (op === '>') return [{ op: '>=', version: next }]\n if (op === '<=') return [{ op: '<', version: next }]\n return [{ op: op as '<' | '>=', version: base }]\n }\n return [\n {\n op: op === '' ? '=' : (op as Comparator['op']),\n version: makeVersion(major, minor, patch, pre),\n },\n ]\n}\n\n/** Exclusive upper bound of `^major.minor.patch`: the next bump of the leftmost non-zero part. */\nfunction caretLimit(major: number, minor?: number, patch?: number): Version {\n if (major > 0 || minor === undefined) return makeVersion(major + 1, 0, 0)\n if (minor > 0 || patch === undefined) return makeVersion(0, minor + 1, 0)\n return makeVersion(0, 0, patch + 1)\n}\n\nconst between = (low: Version, high: Version): Comparator[] => [\n { op: '>=', version: low },\n { op: '<', version: high },\n]\n\nfunction matches(version: Version, comparator: Comparator): boolean {\n const order = compare(version, comparator.version)\n switch (comparator.op) {\n case '<':\n return order < 0\n case '<=':\n return order <= 0\n case '>':\n return order > 0\n case '>=':\n return order >= 0\n default:\n return order === 0\n }\n}\n\n/** Semver precedence: negative when `a` comes first. A release follows its prereleases. */\nfunction compare(a: Version, b: Version): number {\n for (let i = 0; i < 3; i++) {\n const difference = (a.triple[i] ?? 0) - (b.triple[i] ?? 0)\n if (difference !== 0) return difference\n }\n if (!a.pre.length || !b.pre.length) return b.pre.length - a.pre.length\n for (let i = 0; i < Math.max(a.pre.length, b.pre.length); i++) {\n const left = a.pre[i]\n const right = b.pre[i]\n if (left === undefined) return -1\n if (right === undefined) return 1\n const difference = compareIdentifiers(left, right)\n if (difference !== 0) return difference\n }\n return 0\n}\n\n/** Numeric identifiers compare as numbers and sort before alphanumeric ones. */\nfunction compareIdentifiers(a: string, b: string): number {\n const aNumeric = /^\\d+$/.test(a)\n const bNumeric = /^\\d+$/.test(b)\n if (aNumeric && bNumeric) return Number(a) - Number(b)\n if (aNumeric) return -1\n if (bNumeric) return 1\n if (a < b) return -1\n return a > b ? 1 : 0\n}\n\nconst makeVersion = (\n major: number,\n minor: number,\n patch: number,\n pre: readonly string[] = [],\n): Version => ({ triple: [major, minor, patch], pre })\n\nconst isWild = (part: string | undefined): boolean =>\n part === undefined || part === '*' || part === 'x' || part === 'X'\n","import { VERSION } from '../version'\nimport { DioramaError, messageOf } from './errors'\nimport { findCycle, topologicalSort } from './order'\nimport { type Definition, definitionOf, isPreset, refName, validateDefinition } from './plugin'\nimport type { Owner } from './scope'\nimport { satisfies } from './semver'\nimport type {\n AnyPlugin,\n AppOptions,\n DependencyRef,\n PluginStatus,\n StandardSchemaIssue,\n} from './types'\nimport { mergeOptions } from './util'\n\n/** Names a plugin may not take beyond the App API's own members. */\nexport const RESERVED = ['then', 'toJSON', 'spawn', 'query', 'tick'] as const\n\n// Layers of plugin entries. Of two entries with one name, the higher layer wins.\nconst LAYER_DEFAULTS = 0\nconst LAYER_PRESETS = 1\nconst LAYER_PLUGINS = 2\n/** Plugins installed with `use()` after start. */\nexport const LAYER_RUNTIME = 3\n\n/** Everything the kernel knows about one installed plugin. */\nexport interface PluginRecord {\n readonly name: string\n readonly def: Definition\n /** Names of the required dependencies. */\n readonly deps: readonly string[]\n /** Names of the optional dependencies. */\n readonly optional: readonly string[]\n readonly critical: boolean\n /** Options before the schema ran. `use` compares these to detect a re-install. */\n readonly raw: Record<string, unknown>\n options: Readonly<Record<string, unknown>>\n status: PluginStatus\n /** Start order. Systems and hooks of earlier plugins run first. */\n ordinal: number\n service: unknown\n hasService: boolean\n scope: Owner | undefined\n error: DioramaError | undefined\n /** Undoes the link to the owner that installed it at runtime. */\n release: (() => void) | undefined\n}\n\n/** A plugin as listed in the options, before names are resolved. */\nexport interface Entry {\n readonly plugin: AnyPlugin\n readonly def: Definition\n readonly layer: number\n /** Position in the flattened list, for a stable merge order. */\n readonly index: number\n}\n\nexport interface Resolved {\n /** One record per plugin name. */\n readonly list: PluginRecord[]\n readonly failures: Map<PluginRecord, DioramaError>\n}\n\nexport interface Config {\n readonly options: AppOptions\n /** The built-in plugins, before `defaults: false` and `disable` apply. */\n readonly defaults: readonly AnyPlugin[]\n readonly disabled: ReadonlySet<string>\n readonly reserved: (name: string) => boolean\n}\n\n/** An optional dependency: `to` depends on `from`. Dropped first to break a cycle. */\ninterface OptionalEdge {\n readonly from: number\n readonly to: number\n /** Index in the dependent's `optionalDependencies`. */\n readonly position: number\n}\n\n/** Flattens layers (defaults < presets < plugins) and applies `disable`. */\nexport function collectEntries(config: Config, problems: DioramaError[]): Entry[] {\n const entries: Entry[] = []\n const push = (value: unknown, layer: number): void => {\n if (!value) return\n const def = definitionOf(value)\n if (def) entries.push({ plugin: value as AnyPlugin, def, layer, index: entries.length })\n else problems.push(new DioramaError('PLUGIN_INVALID', `not a plugin: ${String(value)}`))\n }\n const walkPreset = (value: unknown, seen: Set<unknown>): void => {\n if (!value || seen.has(value)) return\n if (!isPreset(value)) {\n problems.push(new DioramaError('PLUGIN_INVALID', `not a preset: ${String(value)}`))\n return\n }\n seen.add(value)\n if (!Array.isArray(value.presets) || !Array.isArray(value.plugins)) {\n problems.push(new DioramaError('PLUGIN_INVALID', `preset \"${value.name}\" needs arrays`))\n return\n }\n for (const nested of value.presets) walkPreset(nested, seen)\n for (const plugin of value.plugins) push(plugin, LAYER_PRESETS)\n }\n const listOption = (key: 'presets' | 'plugins'): readonly unknown[] => {\n const value = config.options[key]\n if (value === undefined || Array.isArray(value)) return value ?? []\n problems.push(new DioramaError('CONFIG_INVALID', `${key} must be an array`))\n return []\n }\n if (config.options.defaults !== false) {\n for (const plugin of config.defaults) push(plugin, LAYER_DEFAULTS)\n }\n for (const preset of listOption('presets')) walkPreset(preset, new Set())\n for (const plugin of listOption('plugins')) push(plugin, LAYER_PLUGINS)\n // `disable` drops built-ins and preset plugins, never a plugin listed in `plugins`.\n return entries.filter(\n (entry) => entry.layer === LAYER_PLUGINS || !config.disabled.has(String(entry.def.name)),\n )\n}\n\n/** Why a missing plugin is missing, as a suffix for messages. */\nexport function missingHint(config: Config, name: string): string {\n if (config.disabled.has(name)) return ' (removed via disable)'\n if (config.options.defaults === false && config.defaults.some((p) => p.name === name)) {\n return ' (defaults are off)'\n }\n return ''\n}\n\n/** Resolves names (the strongest layer wins) and validates. Returns per-plugin failures. */\nexport async function resolveEntries(\n config: Config,\n entries: readonly Entry[],\n available?: (name: string) => boolean,\n): Promise<Resolved> {\n const groups = new Map<string, Entry[]>()\n for (const entry of entries) {\n const name = String(entry.def.name)\n groups.set(name, [...(groups.get(name) ?? []), entry])\n }\n const list: PluginRecord[] = []\n const failures = new Map<PluginRecord, DioramaError>()\n for (const [name, group] of groups) {\n const topLayer = Math.max(...group.map((entry) => entry.layer))\n const winner = group.find((entry) => entry.layer === topLayer) as Entry\n const record = createRecord(winner.def, mergeGroupOptions(group, winner))\n list.push(record)\n if (group.some((entry) => entry.layer === topLayer && entry.def !== winner.def)) {\n failures.set(\n record,\n new DioramaError('PLUGIN_DUPLICATE', `two different plugins named \"${name}\"`, {\n plugin: name,\n }),\n )\n }\n }\n for (const record of list) {\n const problem = failures.get(record) ?? (await validate(record, config.reserved))\n if (problem) failures.set(record, problem)\n }\n const present = new Set(list.map((record) => record.name))\n for (const record of list) {\n const missing = record.deps.find((name) => !present.has(name) && !available?.(name))\n if (missing === undefined || failures.has(record)) continue\n failures.set(\n record,\n new DioramaError(\n 'PLUGIN_MISSING_DEPENDENCY',\n `requires \"${missing}\"${missingHint(config, missing)}`,\n { plugin: record.name },\n ),\n )\n }\n return { list, failures }\n}\n\n/**\n * Start order by list position, or a cycle of required dependencies. Optional edges inside a\n * stuck set are dropped one at a time, starting with the dependent placed latest.\n */\nexport function orderPlugins(\n list: readonly PluginRecord[],\n): PluginRecord[] | { cycle: PluginRecord[] } {\n const recordAt = (i: number): PluginRecord => list[i] as PluginRecord\n const indexByName = new Map(list.map((record, i) => [record.name, i]))\n const required: number[][] = list.map(() => [])\n const optional: OptionalEdge[] = []\n list.forEach((record, to) => {\n for (const name of record.deps) {\n const from = indexByName.get(name)\n if (from !== undefined) required[from]?.push(to)\n }\n record.optional.forEach((name, position) => {\n const from = indexByName.get(name)\n if (from !== undefined) optional.push({ from, to, position })\n })\n })\n const requiredOnly = topologicalSort(list.length, required, byIndex)\n if (!Array.isArray(requiredOnly)) {\n return { cycle: findCycle(required, requiredOnly.stuck).map(recordAt) }\n }\n for (;;) {\n const edges = required.map((targets) => [...targets])\n for (const edge of optional) edges[edge.from]?.push(edge.to)\n const result = topologicalSort(list.length, edges, byIndex)\n if (Array.isArray(result)) return result.map(recordAt)\n const drop = edgeToDrop(optional, edges, new Set(result.stuck))\n // Not reached: required edges alone sort, so every stuck set closes through an optional one.\n if (!drop) return { cycle: result.stuck.map(recordAt) }\n optional.splice(optional.indexOf(drop), 1)\n }\n}\n\nexport const cycleError = (cycle: readonly PluginRecord[]): DioramaError =>\n new DioramaError(\n 'PLUGIN_CYCLE',\n `required dependencies form a cycle: ${cycle.map((record) => record.name).join(' → ')}`,\n )\n\n/** Entries sharing the winner's definition merge their options by layer, then position. */\nfunction mergeGroupOptions(group: readonly Entry[], winner: Entry): Record<string, unknown> {\n const same = group\n .filter((entry) => entry.def === winner.def)\n .sort((a, b) => a.layer - b.layer || a.index - b.index)\n let options: Record<string, unknown> = { ...winner.def.defaults }\n for (const entry of same) options = mergeOptions(options, entry.plugin.options)\n return options\n}\n\n/** Validates the definition, core range and options, then freezes the final options. */\nasync function validate(\n record: PluginRecord,\n reserved: (name: string) => boolean,\n): Promise<DioramaError | undefined> {\n const plugin = record.name\n const problems = validateDefinition(record.def)\n if (!problems.length && reserved(record.name)) {\n problems.push(`name \"${record.name}\" is reserved by the App API`)\n }\n if (problems.length) return new DioramaError('PLUGIN_INVALID', problems.join('; '), { plugin })\n const { core, schema } = record.def\n if (core !== undefined && !satisfies(VERSION, core)) {\n return new DioramaError('PLUGIN_INCOMPATIBLE', `requires core ${core}, running ${VERSION}`, {\n plugin,\n })\n }\n let value: unknown = record.raw\n if (schema) {\n try {\n const result = await schema['~standard'].validate(record.raw)\n if (result.issues) {\n return new DioramaError('PLUGIN_OPTIONS', describeIssues(result.issues), { plugin })\n }\n value = result.value\n } catch (error) {\n return new DioramaError('PLUGIN_OPTIONS', messageOf(error), { plugin, cause: error })\n }\n }\n record.options = Object.freeze({ ...(value as object) })\n return undefined\n}\n\n/** Schema issues as `path: message` parts joined by `; `. */\nfunction describeIssues(issues: readonly StandardSchemaIssue[]): string {\n const parts = issues.map((issue) => {\n const path = issue.path\n ?.map((segment) => String(typeof segment === 'object' ? segment.key : segment))\n .join('.')\n return path ? `${path}: ${issue.message}` : issue.message\n })\n return parts.join('; ')\n}\n\nfunction createRecord(def: Definition, raw: Record<string, unknown>): PluginRecord {\n // A non-array list is left to `validate`, which reports it as PLUGIN_INVALID.\n const names = (list?: readonly DependencyRef[]): string[] =>\n Array.isArray(list) ? list.map((ref) => refName(ref) ?? '') : []\n return {\n name: String(def.name),\n def,\n deps: names(def.dependencies),\n optional: names(def.optionalDependencies),\n critical: def.critical === true,\n raw,\n options: raw,\n status: 'pending',\n ordinal: -1,\n service: undefined,\n hasService: false,\n scope: undefined,\n error: undefined,\n release: undefined,\n }\n}\n\n/** Ties between ready plugins go to the one listed first. */\nconst byIndex = (a: number, b: number): boolean => a < b\n\n/** The optional edge on a cycle whose dependent is placed latest (then its latest entry). */\nfunction edgeToDrop(\n optional: readonly OptionalEdge[],\n edges: readonly (readonly number[])[],\n stuck: ReadonlySet<number>,\n): OptionalEdge | undefined {\n // An edge lies on a cycle only if its target can reach its source again.\n const reaches = (from: number, to: number): boolean => {\n const seen = new Set<number>()\n const walk = (node: number): boolean => {\n if (node === to) return true\n if (seen.has(node)) return false\n seen.add(node)\n return (edges[node] ?? []).some((next) => stuck.has(next) && walk(next))\n }\n return walk(from)\n }\n let drop: OptionalEdge | undefined\n for (const edge of optional) {\n if (!stuck.has(edge.from) || !stuck.has(edge.to)) continue\n const notLater =\n drop && (edge.to < drop.to || (edge.to === drop.to && edge.position <= drop.position))\n if (notLater) continue\n if (reaches(edge.to, edge.from)) drop = edge\n }\n return drop\n}\n","import { DioramaError } from './errors'\nimport type { Owner, Report } from './scope'\nimport type { Off } from './types'\nimport { isThenable, noop } from './util'\n\n/** Nesting counter shared by events and hooks. */\nexport interface Depth {\n value: number\n}\n\n/** Emits and hook calls nested deeper than this are reported as RECURSION and skipped. */\nexport const MAX_DEPTH = 64\n\ninterface Listener {\n readonly fn: (payload: unknown) => unknown\n readonly owner: Owner\n readonly once: boolean\n active: boolean\n off: Off\n}\n\n/** Event listeners by name. Errors in listeners are reported and never reach the emitter. */\nexport class EventBus {\n // Lists are copied on write, so a running emit keeps iterating its own snapshot.\n readonly #channels = new Map<string, Listener[]>()\n readonly #report: Report\n readonly #depth: Depth\n\n constructor(report: Report, depth: Depth) {\n this.#report = report\n this.#depth = depth\n }\n\n on(name: string, fn: (payload: unknown) => unknown, owner: Owner, once: boolean): Off {\n if (!owner.open()) return noop\n const listener: Listener = { fn, owner, once, active: true, off: noop }\n this.#channels.set(name, [...(this.#channels.get(name) ?? []), listener])\n listener.off = owner.add(() => {\n if (!listener.active) return\n listener.active = false\n const rest = (this.#channels.get(name) ?? []).filter((other) => other !== listener)\n if (rest.length) this.#channels.set(name, rest)\n else this.#channels.delete(name)\n })\n return listener.off\n }\n\n emit(name: string, payload: unknown): void {\n const list = this.#channels.get(name)\n if (!list) return\n if (this.#depth.value >= MAX_DEPTH) {\n this.#report(\n new DioramaError('RECURSION', `\"${name}\" nested too deep`),\n 'listener',\n undefined,\n name,\n )\n return\n }\n this.#depth.value++\n try {\n for (const listener of list) {\n // `active` skips listeners removed earlier in this same delivery.\n if (!listener.active || listener.owner.disposed) continue\n if (listener.once) listener.off()\n try {\n const result = listener.fn(payload)\n if (isThenable(result)) {\n result.then(undefined, (error) => this.#report(error, 'listener', listener.owner, name))\n }\n } catch (error) {\n this.#report(error, 'listener', listener.owner, name)\n }\n }\n } finally {\n this.#depth.value--\n }\n }\n}\n","import { DioramaError } from './errors'\nimport { type Depth, MAX_DEPTH } from './events'\nimport { type Orderable, orderRefs, sortOrderables } from './order'\nimport type { Owner, Report } from './scope'\nimport type { Cancel, Off, OrderOptions } from './types'\nimport { isThenable, noop } from './util'\n\nconst CANCEL: Cancel = Object.freeze({ '~cancel': true, reason: undefined })\n\n/** Returned from a hook handler to stop the chain. `callHook` then returns it. */\nexport function cancel(reason?: string): Cancel {\n return reason === undefined ? CANCEL : Object.freeze({ '~cancel': true, reason })\n}\n\n/** Whether a hook result is a `cancel()`. */\nexport function isCancel(value: unknown): value is Cancel {\n return (\n typeof value === 'object' && value !== null && (value as Partial<Cancel>)['~cancel'] === true\n )\n}\n\n/** Labels of an ordered entry: `before`/`after` can target its own name or its plugin. */\nexport function labelsOf(owner: Owner, name: string | undefined): string[] {\n const own = name ?? owner.label\n return owner.plugin && owner.plugin !== own ? [own, owner.plugin] : [own]\n}\n\ninterface Handler extends Orderable {\n readonly fn: (value: unknown, context: unknown) => unknown\n readonly owner: Owner\n active: boolean\n}\n\n/** Hook handlers by name, sorted by their order options. */\nexport class HookBus {\n readonly #chains = new Map<string, Handler[]>()\n /** Bumped whenever a chain changes, so callers can cache hook results. */\n readonly #versions = new Map<string, number>()\n #nextSeq = 0\n readonly #report: Report\n readonly #depth: Depth\n\n constructor(report: Report, depth: Depth) {\n this.#report = report\n this.#depth = depth\n }\n\n add(name: string, fn: Handler['fn'], owner: Owner, options?: OrderOptions): Off {\n if (!owner.open()) return noop\n const handler: Handler = {\n fn,\n owner,\n active: true,\n labels: labelsOf(owner, options?.name),\n before: orderRefs(options?.before),\n after: orderRefs(options?.after),\n rank: owner.rank,\n seq: this.#nextSeq++,\n }\n const sorted = sortOrderables([...(this.#chains.get(name) ?? []), handler])\n if (!Array.isArray(sorted)) {\n const path = sorted.cycle.map((entry) => entry.labels[0]).join(' → ')\n throw new DioramaError('ORDER_CYCLE', `hook \"${name}\": ${path}`, { plugin: owner.plugin })\n }\n this.#setChain(name, sorted)\n return owner.add(() => {\n if (!handler.active) return\n handler.active = false\n const rest = (this.#chains.get(name) ?? []).filter((other) => other !== handler)\n this.#setChain(name, rest)\n })\n }\n\n /**\n * Runs a sync chain. Each handler gets the value the previous one returned. A `cancel()`\n * stops the chain and is returned as the result. An async handler is reported and ignored.\n */\n call(name: string, value: unknown, context: unknown): unknown {\n const chain = this.#chains.get(name)\n if (!chain) return value\n if (this.#depth.value >= MAX_DEPTH) {\n this.#report(\n new DioramaError('RECURSION', `hook \"${name}\" nested too deep`),\n 'hook',\n undefined,\n name,\n )\n return value\n }\n this.#depth.value++\n try {\n for (const handler of chain) {\n if (!handler.active || handler.owner.disposed) continue\n let result: unknown\n try {\n result = handler.fn(value, context)\n } catch (error) {\n this.#report(error, 'hook', handler.owner, name)\n continue\n }\n if (result === undefined) continue\n if (isThenable(result)) {\n result.then(undefined, noop)\n const error = new Error(`async handler in sync hook \"${name}\"`)\n this.#report(error, 'hook', handler.owner, name)\n } else if (isCancel(result)) {\n return result\n } else {\n value = result\n }\n }\n return value\n } finally {\n this.#depth.value--\n }\n }\n\n /** Runs a chain like `call`, awaiting each handler in turn. */\n async callAsync(name: string, value: unknown, context: unknown): Promise<unknown> {\n for (const handler of this.#chains.get(name) ?? []) {\n if (!handler.active || handler.owner.disposed) continue\n let result: unknown\n try {\n result = await handler.fn(value, context)\n } catch (error) {\n this.#report(error, 'hook', handler.owner, name)\n continue\n }\n // An owner disposed while we awaited must not affect the value.\n if (result === undefined || handler.owner.disposed) continue\n if (isCancel(result)) return result\n value = result\n }\n return value\n }\n\n version(name: string): number {\n return this.#versions.get(name) ?? 0\n }\n\n #setChain(name: string, chain: Handler[]): void {\n if (chain.length) this.#chains.set(name, chain)\n else this.#chains.delete(name)\n this.#versions.set(name, this.version(name) + 1)\n }\n}\n","import type {\n DriverLink,\n FrameDriver,\n FrameTick,\n ManualDriver,\n ManualDriverOptions,\n Off,\n OfflineDriver,\n OfflineDriverOptions,\n TickerDriverOptions,\n} from './types'\nimport { noop, perfNow } from './util'\n\n/** One loop's connection. A driver can serve several apps, each through its own link. */\ninterface Link extends DriverLink {\n requested: boolean\n readonly tick: FrameTick\n}\n\n/** The links of one driver and their frame requests. */\ninterface Links {\n readonly all: ReadonlySet<Link>\n attach(tick: FrameTick): DriverLink\n anyRequested(): boolean\n /** Ticks every requested link once. True if any drew a frame. */\n tickRequested(now: number): boolean\n}\n\n/** `onRequest` fires on every request, `onIdle` when none remain. */\nfunction createLinks(onRequest: () => void, onIdle: () => void): Links {\n const all = new Set<Link>()\n const anyRequested = (): boolean => {\n for (const link of all) if (link.requested) return true\n return false\n }\n const attach = (tick: FrameTick): DriverLink => {\n const link: Link = {\n tick,\n requested: false,\n request() {\n if (!all.has(link)) return\n link.requested = true\n onRequest()\n },\n cancel() {\n link.requested = false\n if (!anyRequested()) onIdle()\n },\n detach() {\n all.delete(link)\n link.cancel()\n },\n }\n all.add(link)\n return link\n }\n const tickRequested = (now: number): boolean => {\n let ticked = false\n for (const link of all) {\n if (!link.requested) continue\n link.requested = false\n if (link.tick(now)) ticked = true\n }\n return ticked\n }\n return { all, attach, anyRequested, tickRequested }\n}\n\n/** Frames on `requestAnimationFrame`. The default driver in the browser. */\nexport function rafDriver(): FrameDriver {\n let handle: number | undefined\n const frame = (now: number): void => {\n handle = undefined\n links.tickRequested(now)\n }\n const links = createLinks(\n () => {\n if (handle === undefined && typeof requestAnimationFrame === 'function') {\n handle = requestAnimationFrame(frame)\n }\n },\n () => {\n if (handle !== undefined && typeof cancelAnimationFrame === 'function') {\n cancelAnimationFrame(handle)\n handle = undefined\n }\n },\n )\n return { name: 'raf', now: perfNow, attach: links.attach }\n}\n\n/** A driver that frames only on `tick()` or `flush()`, for tests. */\nexport function manualDriver(options: ManualDriverOptions = {}): ManualDriver {\n let time = options.start ?? 0\n const step = options.step ?? 1 / 60\n const links = createLinks(noop, noop)\n const driver: ManualDriver = {\n name: 'manual',\n now: () => time,\n attach: links.attach,\n get pending() {\n return links.anyRequested()\n },\n tick(seconds = step) {\n time += seconds * 1000\n return links.tickRequested(time)\n },\n advance(seconds) {\n time += seconds * 1000\n },\n flush(limit = 1000) {\n let frames = 0\n for (let i = 0; i < limit && links.anyRequested(); i++) {\n if (driver.tick()) frames++\n }\n return frames\n },\n }\n return driver\n}\n\n/** A fixed-step driver that frames on `step()`, for video capture. */\nexport function offlineDriver(options: OfflineDriverOptions): OfflineDriver {\n const start = options.start ?? 0\n const fps = options.fps\n let frame = 0\n const links = createLinks(noop, noop)\n return {\n name: 'offline',\n fps,\n get frame() {\n return frame\n },\n now: () => start + (frame * 1000) / fps,\n attach: links.attach,\n // Ticks every link, requested or not: a capture frame is forced.\n step(count = 1) {\n for (let i = 0; i < count; i++) {\n frame++\n const now = start + (frame * 1000) / fps\n for (const link of links.all) link.tick(now, 1 / fps)\n }\n },\n }\n}\n\n/** A driver on an external ticker, such as `gsap.ticker`. `subscribe` returns its own Off. */\nexport function tickerDriver(\n subscribe: (tick: (now?: number) => void) => Off,\n options: TickerDriverOptions = {},\n): FrameDriver {\n const now = options.now ?? perfNow\n let unsubscribe: Off | undefined\n const stop = (): void => {\n unsubscribe?.()\n unsubscribe = undefined\n }\n const onTick = (time?: number): void => {\n links.tickRequested(time ?? now())\n if (!links.anyRequested()) stop()\n }\n let subscribing = false\n const links = createLinks(() => {\n // A ticker may tick synchronously inside subscribe. Don't subscribe twice from there.\n if (unsubscribe || subscribing) return\n subscribing = true\n try {\n unsubscribe = subscribe(onTick)\n } finally {\n subscribing = false\n }\n if (!links.anyRequested()) stop()\n }, stop)\n return { name: options.name ?? 'ticker', now, attach: links.attach }\n}\n","import { rafDriver } from './drivers'\nimport { DioramaError } from './errors'\nimport { labelsOf } from './hooks'\nimport { type Orderable, orderRefs, sortOrderables } from './order'\nimport type { Owner, Report } from './scope'\nimport type {\n DriverLink,\n FrameDriver,\n FrameMode,\n FrameProfiler,\n FrameReason,\n FrameStats,\n FrameTime,\n Loop,\n LoopOptions,\n LoopSettings,\n Off,\n OrderOptions,\n StageName,\n StagePosition,\n System,\n SystemHandle,\n SystemInfo,\n} from './types'\nimport { isThenable, noop } from './util'\n\nconst DEFAULT_STAGES = ['input', 'layout', 'update', 'render', 'afterRender']\n/** A system that throws this many frames in a row is disabled. */\nconst MAX_FAILURES = 10\n/** Assumed frame interval, seconds, until frames measure the display. */\nconst DEFAULT_INTERVAL = 1 / 60\n/** A gap of this many frame intervals or more is a pause, not a frame. */\nconst GAP_FRAMES = 3\n/** How far each frame moves the measured interval toward the latest one. */\nconst INTERVAL_EASING = 0.1\n// The measured frame rate stays within these bounds.\nconst MAX_MEASURED_FPS = 240\nconst MIN_MEASURED_FPS = 30\n/** `maxFps` lets a frame through this many ms early, so a 60 fps cap keeps every 60 Hz frame. */\nconst FPS_SLACK_MS = 1\n\ninterface SystemRecord extends Orderable, SystemInfo {\n readonly run: System\n readonly scope: Owner\n active: boolean\n /** Its stage is gone. Kept for re-adoption, skipped by frames. */\n parked: boolean\n enabled: boolean\n /** Failures in a row. */\n failures: number\n error: unknown\n}\n\ninterface Stage {\n readonly name: string\n /** Anchor of an `after` placement: later stages with the same anchor go behind it. */\n readonly afterOf: string | undefined\n systems: SystemRecord[]\n}\n\n/** Settings or a driver set by `overrideLoop` or `setDriver`. */\ninterface Override {\n readonly settings?: LoopSettings\n readonly driver?: FrameDriver\n}\n\n/**\n * The frame loop. In `demand` mode it sleeps until something asks for a frame, so an idle page\n * holds no timers or frame requests. Frames run the systems of every stage in order.\n */\nexport class LoopImpl implements Loop {\n readonly time: FrameTime\n readonly stats: FrameStats\n // Writable backing objects of `time` and `stats`, updated in place every frame.\n readonly #time = { delta: 0, rawDelta: 0, elapsed: 0, now: 0, frame: 0, resumed: true }\n readonly #stats = {\n frames: 0,\n wakes: 0,\n reason: 'none' as FrameReason | 'none',\n invalidatedBy: '',\n interval: DEFAULT_INTERVAL,\n }\n readonly #baseSettings: Required<LoopSettings>\n readonly #baseDriver: FrameDriver\n readonly #overrides: Override[] = []\n readonly #stages: Stage[] = DEFAULT_STAGES.map((name) => ({\n name,\n afterOf: undefined,\n systems: [],\n }))\n /** Systems whose stage does not exist (yet). */\n readonly #parked: SystemRecord[] = []\n readonly #warnedStages = new Set<string>()\n readonly #holds = new Set<object>()\n readonly #pauses = new Set<object>()\n // Copy-on-write and captured per frame, so changes mid-frame apply from the next one.\n #profilers: FrameProfiler[] = []\n #frameProfilers: FrameProfiler[] = []\n /** Systems of all stages in run order, rebuilt when `#runOrderStale`. */\n #runOrder: SystemRecord[] = []\n #runOrderStale = true\n #link: DriverLink | undefined\n #attached = false\n #requested = false\n #inFrame = false\n /** Something called `invalidate` since the last frame. */\n #invalidated = false\n /** The previous frame asked for the next one. */\n #continuous = false\n /** Forces a wake frame next, after a driver switch or a pause. */\n #forceWake = true\n /** Driver time until which `keepAwake` keeps frames coming. */\n #awakeUntil = 0\n /** Driver time of the last frame. */\n #lastNow: number | undefined\n /** Measured display frame interval, seconds. */\n #interval = DEFAULT_INTERVAL\n #nextSeq = 0\n readonly #report: Report\n\n constructor(options: LoopOptions | undefined, report: Report, warn: (message: string) => void) {\n this.#report = report\n this.time = this.#time\n this.stats = this.#stats\n this.#baseSettings = {\n mode: 'demand',\n maxDelta: 0.1,\n maxFps: 0,\n timeScale: 1,\n ...validSettings(options ?? {}, warn),\n }\n this.#baseDriver = options?.driver ?? rafDriver()\n }\n\n // The newest override that sets a field wins.\n #setting<K extends keyof LoopSettings>(key: K): Required<LoopSettings>[K] {\n for (let i = this.#overrides.length; i--; ) {\n const value = this.#overrides[i]?.settings?.[key]\n if (value !== undefined) return value as Required<LoopSettings>[K]\n }\n return this.#baseSettings[key]\n }\n\n get mode(): FrameMode {\n return this.#setting('mode')\n }\n get maxDelta(): number {\n return this.#setting('maxDelta')\n }\n get maxFps(): number {\n return this.#setting('maxFps')\n }\n get timeScale(): number {\n return this.#setting('timeScale')\n }\n get driver(): FrameDriver {\n for (let i = this.#overrides.length; i--; ) {\n const driver = this.#overrides[i]?.driver\n if (driver) return driver\n }\n return this.#baseDriver\n }\n get awake(): boolean {\n return this.#requested || this.#inFrame\n }\n get paused(): boolean {\n return this.#pauses.size > 0\n }\n\n overrideLoop(owner: Owner, settings: LoopSettings): Off {\n return this.#override(owner, { settings: validSettings(settings, (m) => owner.log.warn(m)) })\n }\n\n setDriver(owner: Owner, driver: FrameDriver): Off {\n return this.#override(owner, { driver })\n }\n\n #override(owner: Owner, override: Override): Off {\n if (!owner.open()) return noop\n const apply = (change: () => void): void => {\n const driver = this.driver\n const remaining = this.#awakeUntil - driver.now()\n change()\n if (this.driver !== driver) {\n // Drivers have different clocks, so carry over the remaining keepAwake time.\n this.#awakeUntil = remaining > 0 ? this.driver.now() + remaining : 0\n if (this.#attached) {\n this.#unlink()\n this.#relink()\n }\n }\n this.#schedule()\n }\n apply(() => this.#overrides.push(override))\n return owner.add(() => apply(() => removeItem(this.#overrides, override)))\n }\n\n profile(owner: Owner, profiler: FrameProfiler): Off {\n if (!owner.open()) return noop\n this.#profilers = [...this.#profilers, profiler]\n return owner.add(() => {\n this.#profilers = this.#profilers.filter((other) => other !== profiler)\n })\n }\n\n addStage(name: string, position: StagePosition, owner: Owner): Off {\n if (!owner.open()) return noop\n const plugin = owner.plugin\n if (this.#stages.some((stage) => stage.name === name)) {\n throw new DioramaError('STAGE_DUPLICATE', `stage \"${name}\" exists`, { plugin })\n }\n const anchor = position.before ?? position.after\n let index = this.#stages.findIndex((stage) => stage.name === anchor)\n if (index < 0) throw new DioramaError('STAGE_UNKNOWN', `no stage \"${anchor}\"`, { plugin })\n if (position.after !== undefined) {\n // Go past the anchor and the stages placed after it earlier.\n index++\n while (this.#stages[index]?.afterOf === anchor) index++\n }\n // Parked systems were cycle-checked when parked, so this sort always succeeds.\n const parked = this.#parked.filter((record) => record.stage === name)\n const stage: Stage = {\n name,\n afterOf: position.after,\n systems: sortOrderables(parked) as SystemRecord[],\n }\n for (const record of stage.systems) {\n removeItem(this.#parked, record)\n record.parked = false\n }\n this.#stages.splice(index, 0, stage)\n this.#runOrderStale = true\n return owner.add(() => {\n if (!removeItem(this.#stages, stage)) return\n for (const record of stage.systems) record.parked = true\n this.#parked.push(...stage.systems)\n this.#runOrderStale = true\n })\n }\n\n system(\n stage: string,\n run: System,\n options: OrderOptions | undefined,\n owner: Owner,\n ): SystemHandle {\n const record: SystemRecord = {\n name: options?.name ?? owner.label,\n stage: stage as StageName,\n owner: owner.label,\n scope: owner,\n run,\n labels: labelsOf(owner, options?.name),\n before: orderRefs(options?.before),\n after: orderRefs(options?.after),\n rank: owner.rank,\n seq: this.#nextSeq++,\n active: false,\n parked: false,\n enabled: true,\n failures: 0,\n error: undefined,\n }\n let off: Off = noop\n const handle = systemHandle(record, () => off())\n if (!owner.open()) return handle\n\n const target = this.#stages.find((s) => s.name === stage)\n const peers = target ? target.systems : this.#parked.filter((other) => other.stage === stage)\n const sorted = sortOrderables([...peers, record])\n if (!Array.isArray(sorted)) {\n const path = sorted.cycle.map((other) => other.name).join(' → ')\n throw new DioramaError('ORDER_CYCLE', `stage \"${stage}\": ${path}`, { plugin: owner.plugin })\n }\n if (target) target.systems = sorted\n else {\n // Systems may arrive before the plugin that adds their stage.\n record.parked = true\n this.#parked.push(record)\n if (!this.#warnedStages.has(stage)) {\n this.#warnedStages.add(stage)\n owner.log.warn(`stage \"${stage}\" does not exist yet; system parked`)\n }\n }\n record.active = true\n this.#runOrderStale = true\n off = owner.add(() => {\n record.active = false\n for (const s of this.#stages) s.systems = s.systems.filter((other) => other !== record)\n removeItem(this.#parked, record)\n this.#runOrderStale = true\n })\n return handle\n }\n\n invalidate(owner: Owner): void {\n this.#invalidated = true\n this.#stats.invalidatedBy = owner.label\n this.#schedule()\n }\n\n keepAwake(owner: Owner, seconds: number): void {\n if (seconds > 0) {\n this.#awakeUntil = Math.max(this.#awakeUntil, this.driver.now() + seconds * 1000)\n }\n this.invalidate(owner)\n }\n\n hold(owner: Owner): Off {\n if (!owner.open()) return noop\n const token = {}\n this.#holds.add(token)\n this.#schedule()\n // Releasing a hold draws one closing frame with the final state.\n return owner.add(() => this.#holds.delete(token) && this.invalidate(owner))\n }\n\n pause(owner: Owner): Off {\n if (!owner.open()) return noop\n const token = {}\n this.#pauses.add(token)\n if (this.#requested) {\n this.#link?.cancel()\n this.#requested = false\n }\n return owner.add(() => {\n if (this.#pauses.delete(token) && !this.#pauses.size) {\n this.#forceWake = true\n this.#schedule()\n }\n })\n }\n\n attach(): void {\n this.#attached = true\n this.#relink()\n this.#invalidated = true\n this.#schedule()\n }\n\n stop(): void {\n this.#attached = false\n this.#unlink()\n }\n\n /** Whether anything wants a frame now. */\n #wanted(): boolean {\n return (\n this.#invalidated ||\n this.#holds.size > 0 ||\n this.mode === 'always' ||\n (this.#awakeUntil > 0 && this.driver.now() < this.#awakeUntil)\n )\n }\n\n /** Requests at most one frame. An idle loop holds no timers or requests. */\n #schedule(): void {\n if (!this.#attached || this.#pauses.size || this.#requested || this.#inFrame) return\n if (this.#wanted()) this.#requestFrame()\n }\n\n #requestFrame(): void {\n this.#requested = true\n this.#link?.request()\n }\n\n #relink(): void {\n this.#link = this.driver.attach((now, step) => this.#tick(now, step))\n this.#forceWake = true\n this.#lastNow = undefined\n this.#requested = false\n }\n\n #unlink(): void {\n this.#link?.cancel()\n this.#link?.detach()\n this.#link = undefined\n this.#requested = false\n }\n\n /** Driver callback. A forced `step` (offline capture) bypasses pauses and demand checks. */\n #tick(now: number, step?: number): boolean {\n if (this.#inFrame || !this.#attached) return false\n // A non-finite timestamp counts as no time passed, so a broken clock can't poison time.\n if (!Number.isFinite(now)) now = this.#lastNow ?? 0\n this.#requested = false\n if (step === undefined) {\n if (this.#pauses.size || !this.#wanted()) {\n this.#continuous = false\n return false\n }\n // `maxFps` throttles event-driven frames too. A clock going backwards never throttles.\n const fps = this.maxFps\n const since = this.#lastNow === undefined ? Number.POSITIVE_INFINITY : now - this.#lastNow\n if (fps > 0 && !this.#forceWake && since >= 0 && since < 1000 / fps - FPS_SLACK_MS) {\n this.#requestFrame()\n return false\n }\n }\n this.#runFrame(now, step)\n return true\n }\n\n #runFrame(now: number, step: number | undefined): void {\n this.#stats.reason = this.#reason(step)\n this.#advanceTime(now, step)\n this.#invalidated = false\n\n if (this.#runOrderStale) {\n this.#runOrder.length = 0\n for (const stage of this.#stages) this.#runOrder.push(...stage.systems)\n this.#runOrderStale = false\n }\n this.#runSystems()\n\n this.#continuous = this.#attached && !this.#pauses.size && this.#wanted()\n if (this.#continuous) this.#requestFrame()\n }\n\n #advanceTime(now: number, step: number | undefined): void {\n const time = this.#time\n const stats = this.#stats\n const interval = this.#interval\n const rawDelta =\n this.#lastNow === undefined ? interval : Math.max(0, (now - this.#lastNow) / 1000)\n // A frame continues the previous one if that one requested it, or if it follows closely\n // (event-driven invalidation). Anything else is a wake frame after idle, a pause or a\n // driver switch.\n const wake =\n this.#forceWake ||\n this.#lastNow === undefined ||\n (!this.#continuous && rawDelta >= GAP_FRAMES * interval)\n this.#forceWake = false\n // Continuing frames clamp to maxDelta and track the display interval. A wake frame gets at\n // most one frame interval.\n time.delta = (step ?? Math.min(rawDelta, wake ? interval : this.maxDelta)) * this.timeScale\n if (step === undefined && !wake) this.#interval = measureInterval(interval, rawDelta)\n time.rawDelta = rawDelta\n time.elapsed += time.delta\n time.now = now\n time.frame++\n time.resumed = wake && step === undefined\n this.#lastNow = now\n stats.frames++\n if (time.resumed) stats.wakes++\n stats.interval = this.#interval\n }\n\n #runSystems(): void {\n this.#frameProfilers = this.#profilers\n this.#inFrame = true\n try {\n this.#profiled('frameStart', this.#time)\n // Removals during a frame apply at once through `active`, additions wait a frame.\n for (const record of this.#runOrder) {\n if (!this.#attached) break\n if (record.active && !record.parked && record.enabled && record.scope.ready) {\n this.#runSystem(record)\n }\n }\n this.#profiled('frameEnd', this.#time)\n } finally {\n this.#inFrame = false\n }\n }\n\n #reason(step: number | undefined): FrameReason {\n if (step !== undefined) return 'step'\n if (this.#invalidated) return 'invalidate'\n if (this.#holds.size) return 'hold'\n return this.mode === 'always' ? 'always' : 'timed'\n }\n\n #runSystem(record: SystemRecord): void {\n this.#profiled('systemStart', record)\n try {\n const result: unknown = record.run(this.#time)\n if (isThenable(result)) {\n result.then(undefined, noop)\n throw new Error(`system \"${record.name}\" returned a promise`)\n }\n record.failures = 0\n } catch (error) {\n // Report the first failure of a streak, disable after MAX_FAILURES in a row.\n if (++record.failures === 1) this.#report(error, 'system', record.scope, record.name)\n if (record.failures >= MAX_FAILURES) {\n record.enabled = false\n record.error = error\n const disabled = new DioramaError(\n 'SYSTEM_DISABLED',\n `\"${record.name}\" failed ${MAX_FAILURES} frames in a row`,\n { plugin: record.scope.plugin, cause: error },\n )\n this.#report(disabled, 'system', record.scope, record.name)\n }\n }\n this.#profiled('systemEnd', record)\n }\n\n /** Calls one method of every profiler. A profiler that throws is removed and reported. */\n #profiled(method: keyof FrameProfiler, arg: FrameTime | SystemInfo): void {\n for (const profiler of this.#frameProfilers) {\n if (!this.#profilers.includes(profiler)) continue\n try {\n profiler[method](arg as never)\n } catch (error) {\n this.#profilers = this.#profilers.filter((other) => other !== profiler)\n this.#report(error, 'loop', undefined, 'profiler')\n }\n }\n }\n}\n\n/** The function handle that `app.system` returns. Calling it removes the system. */\nfunction systemHandle(record: SystemRecord, remove: () => void): SystemHandle {\n const handle = (() => remove()) as SystemHandle\n Object.defineProperties(handle, {\n name: { value: record.name },\n enabled: {\n get: () => record.enabled,\n set: (value: boolean) => {\n record.enabled = value\n if (!value) return\n record.failures = 0\n record.error = undefined\n },\n },\n error: { get: () => record.error },\n })\n return handle\n}\n\n/** Eases the frame interval toward a measured one. */\nfunction measureInterval(interval: number, measured: number): number {\n const plausible = measured > 0 && measured < GAP_FRAMES * interval\n const next = plausible ? interval + (measured - interval) * INTERVAL_EASING : interval\n return Math.min(Math.max(next, 1 / MAX_MEASURED_FPS), 1 / MIN_MEASURED_FPS)\n}\n\n/** Settings without invalid values. Each dropped value is warned about. */\nfunction validSettings(settings: LoopSettings, warn: (message: string) => void): LoopSettings {\n const result: { -readonly [K in keyof LoopSettings]: LoopSettings[K] } = {}\n const { mode } = settings\n if (mode === 'demand' || mode === 'always') result.mode = mode\n else if (mode !== undefined) warn(`loop: invalid mode \"${String(mode)}\" ignored`)\n for (const key of ['maxDelta', 'maxFps', 'timeScale'] as const) {\n const value = settings[key]\n if (isNonNegativeNumber(value)) result[key] = value\n else if (value !== undefined) warn(`loop: invalid ${key} ignored`)\n }\n return result\n}\n\nconst isNonNegativeNumber = (value: unknown): value is number =>\n typeof value === 'number' && Number.isFinite(value) && value >= 0\n\nfunction removeItem<T>(list: T[], item: T): boolean {\n const index = list.indexOf(item)\n if (index >= 0) list.splice(index, 1)\n return index >= 0\n}\n","import { DioramaError } from './errors'\nimport type { ErrorSource, Logger, Off } from './types'\nimport { isThenable, noop, resolved } from './util'\n\n/** Reports an error to the app: logs it, emits `app:error`, calls `onError`. */\nexport type Report = (\n error: unknown,\n source: ErrorSource,\n owner: Owner | undefined,\n target?: string,\n) => void\n\n/** What every owner of one app shares. */\nexport interface OwnerEnv {\n readonly report: Report\n logFor(owner: Owner): Logger\n}\n\nexport interface OwnerOptions {\n readonly env: OwnerEnv\n readonly label: string\n readonly rank: number\n readonly plugin?: string | undefined\n /** Services this owner may read. `undefined` means unrestricted. */\n readonly allowed?: ReadonlySet<string> | undefined\n}\n\n/** Tracks everything registered through it and undoes it, newest first, on dispose. */\nexport class Owner {\n readonly env: OwnerEnv\n readonly label: string\n readonly rank: number\n readonly plugin: string | undefined\n readonly allowed: ReadonlySet<string> | undefined\n disposed = false\n /** Set when a running setup is cut short, so its later registrations throw ABORTED. */\n abortOnAdd = false\n /** `undefined` inherits readiness from the parent. */\n #ownReady: boolean | undefined\n #parent: Owner | undefined\n /** Drops this owner from its parent's cleanups once it disposes on its own. */\n #unlink: (() => void) | undefined\n readonly #cleanups = new Set<() => unknown>()\n #controller: AbortController | undefined\n #disposal: Promise<void> | undefined\n #logger: Logger | undefined\n\n constructor(options: OwnerOptions) {\n this.env = options.env\n this.label = options.label\n this.rank = options.rank\n this.plugin = options.plugin\n this.allowed = options.allowed\n }\n\n /** Systems run only while their owner is ready. Children inherit it. */\n get ready(): boolean {\n return this.#ownReady ?? this.#parent?.ready ?? true\n }\n\n set ready(value: boolean) {\n this.#ownReady = value\n }\n\n /** Aborts when the owner disposes. Created on first read. */\n get signal(): AbortSignal {\n if (!this.#controller) {\n this.#controller = new AbortController()\n if (this.disposed) this.#controller.abort()\n }\n return this.#controller.signal\n }\n\n get log(): Logger {\n this.#logger ??= this.env.logFor(this)\n return this.#logger\n }\n\n /**\n * Registration guard. `false` once disposed, after a warning (or ABORTED for an orphaned\n * setup). Call it before touching shared state.\n */\n open(): boolean {\n if (!this.disposed) return true\n if (this.abortOnAdd)\n throw new DioramaError('ABORTED', 'setup was aborted', { plugin: this.plugin })\n this.log.warn('registration on a closed scope ignored')\n return false\n }\n\n /** Registers an undo. The returned Off runs it now, once. */\n add(undo: () => unknown): Off {\n if (this.disposed) {\n // Undo first. The orphaned setup gets ABORTED, but its resource must not leak.\n this.#runUndo(undo)\n this.open()\n return noop\n }\n this.#cleanups.add(undo)\n return () => {\n if (this.#cleanups.delete(undo)) this.#runUndo(undo)\n }\n }\n\n /** A nested owner, disposed with this one. Options not given are inherited. */\n child(options?: Partial<OwnerOptions>): Owner {\n const child = new Owner({\n env: this.env,\n label: options?.label ?? this.label,\n rank: options?.rank ?? this.rank,\n plugin: options && 'plugin' in options ? options.plugin : this.plugin,\n allowed: options && 'allowed' in options ? options.allowed : this.allowed,\n })\n child.#parent = this\n if (this.disposed) child.disposed = true\n else {\n const undo = (): Promise<void> => child.dispose()\n this.#cleanups.add(undo)\n child.#unlink = () => this.#cleanups.delete(undo)\n }\n return child\n }\n\n /** Aborts, then runs undos synchronously. The promise covers async undos only. */\n dispose(): Promise<void> {\n if (this.#disposal) return this.#disposal\n // Claim `#disposal` and empty the list before running anything, since undos may re-enter.\n let finish: (value: Promise<void>) => void = noop\n this.#disposal = new Promise<void>((resolve) => {\n finish = resolve\n })\n this.disposed = true\n this.#unlink?.()\n const undos = [...this.#cleanups].reverse()\n this.#cleanups.clear()\n this.#controller?.abort()\n const pending = undos.map((undo) => this.#runUndo(undo)).filter(isThenable)\n finish(pending.length ? Promise.all(pending).then(noop) : resolved)\n return this.#disposal\n }\n\n /** Runs one undo and reports its failure. Returns a promise only for an async undo. */\n #runUndo(undo: () => unknown): unknown {\n try {\n const result = undo()\n return isThenable(result)\n ? Promise.resolve(result).then(undefined, (error) =>\n this.env.report(error, 'dispose', this),\n )\n : undefined\n } catch (error) {\n this.env.report(error, 'dispose', this)\n }\n }\n}\n","/**\n * Push-pull signals. A write marks dependents as maybe stale and reads pull fresh values\n * lazily. Every source has a version, so staleness is checked, never guessed.\n * @module\n */\nimport { DioramaError } from './errors'\nimport type { EffectFn, Off, ReadonlySignal, Signal, SignalOptions } from './types'\nimport { isThenable } from './util'\n\n/** A computed or an effect: something that reads sources. */\ninterface Observer {\n /** Sources read by the last run, with the version each had then. */\n deps: Map<Source, number>\n notify(): void\n}\n\n/** A signal or a computed: something that can be read. */\ninterface Source {\n version: number\n /** Brings the value up to date. Only computeds do work here. */\n refresh(): void\n watch(observer: Observer): void\n unwatch(observer: Observer): void\n}\n\n/** Effects that write signals they read can loop. Give up after this many flush passes. */\nconst MAX_PASSES = 100\n\n// Module state is empty between synchronous calls.\n/** Dependencies of the observer running now, filled by reads. */\nlet collecting: Map<Source, number> | undefined\nlet batchDepth = 0\nlet flushing = false\nconst queue: EffectNode[] = []\n\n/** Reports errors that must not propagate to the code that wrote the signal. */\nfunction reportGlobal(error: unknown): void {\n const report = (globalThis as { reportError?: (e: unknown) => void }).reportError\n if (typeof report === 'function') report(error)\n else console.error(error)\n}\n\nfunction track(source: Source): void {\n if (collecting && !collecting.has(source)) collecting.set(source, source.version)\n}\n\n/** Runs queued effects until none are left, outside batches and nested flushes. */\nfunction flush(): void {\n if (flushing || batchDepth > 0) return\n flushing = true\n try {\n let passes = 0\n while (queue.length) {\n if (++passes > MAX_PASSES) {\n for (const node of queue) node.queued = false\n queue.length = 0\n const message = `effects did not settle after ${MAX_PASSES} passes`\n reportGlobal(new DioramaError('SIGNAL_CYCLE', message))\n break\n }\n const pass = queue.splice(0)\n for (const node of pass) {\n node.queued = false\n if (node.stale()) node.run()\n }\n }\n } finally {\n flushing = false\n }\n}\n\n// Only observed nodes hold subscriptions. Unobserved computeds keep none, so they can be\n// garbage-collected, and verify their sources by version on each read instead.\nfunction relink(observer: Observer, next: Map<Source, number>, watched: boolean): void {\n if (watched) {\n for (const source of observer.deps.keys()) if (!next.has(source)) source.unwatch(observer)\n for (const source of next.keys()) if (!observer.deps.has(source)) source.watch(observer)\n }\n observer.deps = next\n}\n\n/** A writable source. */\nclass SignalNode<T> implements Signal<T>, Source {\n version = 0\n #targets = new Set<Observer>()\n #value: T\n readonly #equals: (a: T, b: T) => boolean\n\n constructor(value: T, options?: SignalOptions<T>) {\n this.#value = value\n this.#equals = options?.equals ?? Object.is\n }\n\n get value(): T {\n track(this)\n return this.#value\n }\n\n set value(next: T) {\n if (this.#equals(this.#value, next)) return\n this.#value = next\n this.version++\n for (const target of this.#targets) target.notify()\n flush()\n }\n\n peek(): T {\n return this.#value\n }\n\n subscribe(listener: (value: T) => void): Off {\n return subscribe(this, listener)\n }\n\n refresh(): void {}\n\n watch(observer: Observer): void {\n this.#targets.add(observer)\n }\n\n unwatch(observer: Observer): void {\n this.#targets.delete(observer)\n }\n}\n\n/** A derived value: a source for its readers and an observer of what it reads. */\nclass ComputedNode<T> implements ReadonlySignal<T>, Source, Observer {\n version = 0\n deps: Map<Source, number> = new Map()\n #targets = new Set<Observer>()\n #value: T | undefined\n #error: unknown\n #failed = false\n #initialized = false\n #dirty = true\n #running = false\n readonly #fn: () => T\n readonly #equals: (a: T, b: T) => boolean\n\n constructor(fn: () => T, options?: SignalOptions<T>) {\n this.#fn = fn\n this.#equals = options?.equals ?? Object.is\n }\n\n get value(): T {\n this.refresh()\n track(this)\n if (this.#failed) throw this.#error\n return this.#value as T\n }\n\n peek(): T {\n this.refresh()\n if (this.#failed) throw this.#error\n return this.#value as T\n }\n\n subscribe(listener: (value: T) => void): Off {\n return subscribe(this, listener)\n }\n\n notify(): void {\n if (this.#dirty) return\n this.#dirty = true\n for (const target of this.#targets) target.notify()\n }\n\n refresh(): void {\n if (this.#running) throw new DioramaError('SIGNAL_CYCLE', 'computed depends on itself')\n if (this.#initialized && !this.#dirty && this.#targets.size > 0) return\n if (this.#initialized) {\n let changed = false\n for (const [source, seen] of this.deps) {\n source.refresh()\n if (source.version !== seen) {\n changed = true\n break\n }\n }\n if (!changed) {\n this.#dirty = false\n return\n }\n }\n this.#recompute()\n }\n\n #recompute(): void {\n const outer = collecting\n const next = new Map<Source, number>()\n collecting = next\n this.#running = true\n let value: T | undefined\n let error: unknown\n let failed = false\n try {\n value = this.#fn()\n } catch (thrown) {\n error = thrown\n failed = true\n } finally {\n collecting = outer\n this.#running = false\n }\n relink(this, next, this.#targets.size > 0)\n const changed =\n !this.#initialized ||\n failed !== this.#failed ||\n (failed ? error !== this.#error : !this.#equals(this.#value as T, value as T))\n this.#initialized = true\n this.#dirty = false\n if (changed) {\n this.#value = value\n this.#error = error\n this.#failed = failed\n this.version++\n }\n }\n\n watch(observer: Observer): void {\n if (this.#targets.size === 0) {\n // Sources may have changed while nobody watched. Catch up first so the new observer\n // sees a fresh version and `#dirty` keeps meaning \"observers notified\".\n try {\n this.refresh()\n } catch {}\n for (const source of this.deps.keys()) source.watch(this)\n }\n this.#targets.add(observer)\n }\n\n unwatch(observer: Observer): void {\n this.#targets.delete(observer)\n if (this.#targets.size === 0) for (const source of this.deps.keys()) source.unwatch(this)\n }\n}\n\n/** Reruns its function when a source it read changes. */\nclass EffectNode implements Observer {\n deps: Map<Source, number> = new Map()\n queued = false\n #disposed = false\n #cleanup: (() => unknown) | undefined\n readonly #fn: EffectFn\n readonly #onError: (error: unknown) => void\n\n constructor(fn: EffectFn, onError: (error: unknown) => void) {\n this.#fn = fn\n this.#onError = onError\n }\n\n notify(): void {\n if (this.queued || this.#disposed) return\n this.queued = true\n queue.push(this)\n }\n\n // Rerun only if a source really changed. A computed that recomputed to an equal value\n // stops propagation here, which also keeps diamonds glitch-free.\n stale(): boolean {\n if (this.#disposed) return false\n for (const [source, seen] of this.deps) {\n try {\n source.refresh()\n } catch {\n return true\n }\n if (source.version !== seen) return true\n }\n return false\n }\n\n run(): void {\n if (this.#disposed) return\n this.#runCleanup()\n const outer = collecting\n const next = new Map<Source, number>()\n collecting = next\n try {\n const result = this.#fn()\n if (typeof result === 'function') this.#cleanup = result as () => unknown\n else if (isThenable(result)) result.then(undefined, this.#onError)\n } catch (error) {\n this.#onError(error)\n } finally {\n collecting = outer\n if (this.#disposed) this.#runCleanup()\n else this.#settle(next)\n }\n }\n\n // Subscriptions start only after the run, so a write made during the run reached no\n // one. Compare versions now and rerun if a dependency moved under us.\n #settle(next: Map<Source, number>): void {\n relink(this, next, true)\n for (const [source, seen] of next) {\n if (source.version !== seen) {\n this.notify()\n flush()\n return\n }\n }\n }\n\n dispose(): void {\n if (this.#disposed) return\n this.#disposed = true\n for (const source of this.deps.keys()) source.unwatch(this)\n this.deps.clear()\n this.#runCleanup()\n }\n\n #runCleanup(): void {\n const cleanup = this.#cleanup\n this.#cleanup = undefined\n if (!cleanup) return\n const outer = collecting\n collecting = undefined\n try {\n cleanup()\n } catch (error) {\n this.#onError(error)\n } finally {\n collecting = outer\n }\n }\n}\n\n/** Svelte store contract: calls `listener` now and after every change. The first call may throw. */\nfunction subscribe<T>(node: ReadonlySignal<T>, listener: (value: T) => void): Off {\n let first = true\n const watcher = new EffectNode(\n () => {\n const value = node.value\n untracked(() => listener(value))\n },\n (error) => {\n if (first) throw error\n reportGlobal(error)\n },\n )\n try {\n watcher.run()\n } catch (error) {\n watcher.dispose()\n throw error\n } finally {\n first = false\n }\n return () => watcher.dispose()\n}\n\n/** A writable reactive value. Reading `value` inside `effect` or `computed` tracks it. */\nexport function signal<T>(value: T, options?: SignalOptions<T>): Signal<T> {\n return new SignalNode(value, options)\n}\n\n/**\n * A read-only value derived from signals, recomputed lazily when they change.\n * @throws {DioramaError} `SIGNAL_CYCLE` on read when the value depends on itself.\n */\nexport function computed<T>(compute: () => T, options?: SignalOptions<T>): ReadonlySignal<T> {\n return new ComputedNode(compute, options)\n}\n\n/** `effect` with a custom error sink. `app.effect` reports through the app. */\nexport function ownedEffect(fn: EffectFn, onError: (error: unknown) => void): Off {\n const node = new EffectNode(fn, onError)\n node.run()\n return () => node.dispose()\n}\n\n/** Runs `fn` now and again whenever a signal it read changes. Returns Off. */\nexport function effect(fn: EffectFn): Off {\n return ownedEffect(fn, reportGlobal)\n}\n\n/** Runs `fn` and notifies effects once at the end, not after each write. */\nexport function batch<T>(fn: () => T): T {\n batchDepth++\n try {\n return fn()\n } finally {\n batchDepth--\n flush()\n }\n}\n\n/** Runs `fn` without tracking the signals it reads. */\nexport function untracked<T>(fn: () => T): T {\n const outer = collecting\n collecting = undefined\n try {\n return fn()\n } finally {\n collecting = outer\n }\n}\n","/**\n * Views are what plugins, scopes and the app itself see as `app`. All views of one app share a\n * prototype and reach their kernel and owner through two symbols, so a scope per entity stays\n * cheap and a call allocates nothing.\n * @module\n */\nimport type { Kernel } from './app'\nimport { RESERVED } from './config'\nimport type { LoopImpl } from './loop'\nimport type { Owner } from './scope'\nimport { ownedEffect } from './signals'\nimport type {\n AppState,\n Cleanup,\n DependencyRef,\n FrameDriver,\n FrameProfiler,\n Logger,\n LoopSettings,\n Off,\n OrderOptions,\n ReadonlySignal,\n RemoveOptions,\n StagePosition,\n System,\n SystemHandle,\n} from './types'\nimport { noop } from './util'\n\nexport const OWNER: unique symbol = Symbol('diorama.owner') as never\nexport const KERNEL: unique symbol = Symbol('diorama.kernel') as never\n\nexport interface View {\n readonly [OWNER]: Owner\n readonly [KERNEL]: Kernel\n}\n\nconst kernelOf = (view: unknown): Kernel => (view as View)[KERNEL]\nconst ownerOf = (view: unknown): Owner => (view as View)[OWNER]\n\n/** The App API every view has. Registrations belong to the view's owner. */\nconst VIEW_METHODS = {\n use(entry: unknown): Promise<unknown> {\n return kernelOf(this).use(entry, ownerOf(this))\n },\n remove(ref: DependencyRef, options?: RemoveOptions): Promise<boolean> {\n return kernelOf(this).remove(ref, options, ownerOf(this))\n },\n has(ref: DependencyRef): boolean {\n return kernelOf(this).has(ref)\n },\n get(ref: DependencyRef): unknown {\n return kernelOf(this).service(ownerOf(this), ref, true)\n },\n find(ref: DependencyRef): unknown {\n return kernelOf(this).service(ownerOf(this), ref, false)\n },\n on(name: string, listener: (payload: unknown) => unknown): Off {\n return kernelOf(this).events.on(name, listener, ownerOf(this), false)\n },\n once(name: string, listener: (payload: unknown) => unknown): Off {\n return kernelOf(this).events.on(name, listener, ownerOf(this), true)\n },\n emit(name: string, payload?: unknown): void {\n if (!ownerOf(this).disposed) kernelOf(this).events.emit(name, payload)\n },\n hook(\n name: string,\n handler: (value: unknown, context: unknown) => unknown,\n options?: OrderOptions,\n ): Off {\n return kernelOf(this).hooks.add(name, handler, ownerOf(this), options)\n },\n callHook(name: string, value: unknown, context?: unknown): unknown {\n return ownerOf(this).disposed ? value : kernelOf(this).hooks.call(name, value, context)\n },\n callHookAsync(name: string, value: unknown, context?: unknown): Promise<unknown> {\n return ownerOf(this).disposed\n ? Promise.resolve(value)\n : kernelOf(this).hooks.callAsync(name, value, context)\n },\n hookVersion(name: string): number {\n return kernelOf(this).hooks.version(name)\n },\n get loop(): LoopImpl {\n return kernelOf(this).loop\n },\n system(stage: string, run: System, options?: OrderOptions): SystemHandle {\n return kernelOf(this).loop.system(stage, run, options, ownerOf(this))\n },\n addStage(name: string, position: StagePosition): Off {\n return kernelOf(this).loop.addStage(name, position, ownerOf(this))\n },\n invalidate(): void {\n const owner = ownerOf(this)\n if (!owner.disposed) kernelOf(this).loop.invalidate(owner)\n },\n keepAwake(seconds: number): void {\n const owner = ownerOf(this)\n if (!owner.disposed) kernelOf(this).loop.keepAwake(owner, seconds)\n },\n hold(): Off {\n return kernelOf(this).loop.hold(ownerOf(this))\n },\n pause(): Off {\n return kernelOf(this).loop.pause(ownerOf(this))\n },\n overrideLoop(settings: LoopSettings): Off {\n return kernelOf(this).loop.overrideLoop(ownerOf(this), settings)\n },\n setDriver(driver: FrameDriver): Off {\n return kernelOf(this).loop.setDriver(ownerOf(this), driver)\n },\n profile(profiler: FrameProfiler): Off {\n return kernelOf(this).loop.profile(ownerOf(this), profiler)\n },\n effect(fn: () => unknown): Off {\n const kernel = kernelOf(this)\n const owner = ownerOf(this)\n if (!owner.open()) return noop\n return owner.add(ownedEffect(fn, (error) => kernel.report(error, 'effect', owner)))\n },\n scope(): unknown {\n return kernelOf(this).view(ownerOf(this).child(), true)\n },\n onDispose(cleanup: Cleanup): Off {\n return ownerOf(this).add(typeof cleanup === 'function' ? cleanup : () => cleanup.dispose())\n },\n get abortSignal(): AbortSignal {\n return ownerOf(this).signal\n },\n get log(): Logger {\n return ownerOf(this).log\n },\n report(error: unknown, target?: string): void {\n const owner = ownerOf(this)\n // An AbortError after this view's own abort is the expected outcome, not a failure.\n if ((error as { name?: unknown } | null)?.name === 'AbortError' && owner.signal.aborted) return\n kernelOf(this).report(error, 'report', owner, target)\n },\n}\n\n/** Lifecycle members of the view `createApp` returns. */\nexport const ROOT_METHODS = {\n get name(): string {\n return kernelOf(this).name\n },\n get state(): ReadonlySignal<AppState> {\n return kernelOf(this).state\n },\n start(): Promise<unknown> {\n return kernelOf(this).start()\n },\n destroy(): Promise<void> {\n return kernelOf(this).destroy()\n },\n}\n\n/** Members of a view made by `app.scope()`. */\nexport const SCOPE_METHODS = {\n dispose(): Promise<void> {\n return ownerOf(this).dispose()\n },\n get disposed(): boolean {\n return ownerOf(this).disposed\n },\n}\n\nexport const describe = (methods: object): PropertyDescriptorMap =>\n Object.getOwnPropertyDescriptors(methods)\n\nexport const VIEW_PROTO: object = Object.defineProperties({}, describe(VIEW_METHODS))\n\n/** Whether a plugin name would shadow a member of the App API. */\nexport const isReserved = (name: string): boolean =>\n // Check the method objects, not a live view, which also carries service getters.\n name in VIEW_PROTO ||\n name in ROOT_METHODS ||\n name in SCOPE_METHODS ||\n (RESERVED as readonly string[]).includes(name)\n","import {\n type Config,\n collectEntries,\n cycleError,\n type Entry,\n LAYER_RUNTIME,\n missingHint,\n orderPlugins,\n type PluginRecord,\n resolveEntries,\n} from './config'\nimport { DioramaError, isDioramaError, messageOf, toDioramaError } from './errors'\nimport { type Depth, EventBus } from './events'\nimport { HookBus } from './hooks'\nimport { LoopImpl } from './loop'\nimport { definitionOf, isPreset, refName } from './plugin'\nimport { Owner } from './scope'\nimport { signal } from './signals'\nimport type {\n AnyPlugin,\n AppOptions,\n AppState,\n DependencyRef,\n ErrorReport,\n ErrorSource,\n Logger,\n PluginStatus,\n RemoveOptions,\n Signal,\n} from './types'\nimport { createLogger, isThenable, noop, resolved, shallowEqual } from './util'\nimport {\n describe,\n isReserved,\n KERNEL,\n OWNER,\n ROOT_METHODS,\n SCOPE_METHODS,\n VIEW_PROTO,\n type View,\n} from './view'\n\n/** `setTimeout` fires at once for longer delays, so such timeouts are not set at all. */\nconst MAX_TIMER_MS = 2 ** 31 - 1\n/** Seconds a setup may take unless `setupTimeout` says otherwise. */\nconst DEFAULT_SETUP_TIMEOUT = 30\n\nconst aborted = (plugin?: string): DioramaError =>\n new DioramaError('ABORTED', 'start was aborted', { plugin })\nconst destroyed = (): DioramaError => new DioramaError('APP_DESTROYED', 'the app is destroyed')\n\n/**\n * One app: its plugins, lifecycle, events, hooks and frame loop. Plugins start in dependency\n * order, each under its own owner, and stop in reverse order.\n */\nexport class Kernel {\n readonly name: string\n readonly state: Signal<AppState> = signal<AppState>('idle')\n readonly events: EventBus\n readonly hooks: HookBus\n readonly loop: LoopImpl\n readonly root: Owner\n readonly rootView: View\n readonly #options: AppOptions\n readonly #config: Config\n readonly #errorLog: Logger\n /** Seconds. */\n readonly #setupTimeout: number\n /** Prototype of every view: the App API plus a getter per running service. */\n readonly #viewProto: object\n readonly #scopeProto: object\n readonly #records = new Map<string, PluginRecord>()\n /** Setups that lost their race and still run. `destroy` waits for them. */\n readonly #orphanSetups = new Set<Promise<unknown>>()\n /** Cleanups of a failed start, awaited by `destroy`. */\n readonly #rollbacks: Promise<unknown>[] = []\n #starting: Promise<unknown> | undefined\n #stopping: Promise<void> | undefined\n /** Tail of the `use`/`remove` queue. */\n #operations: Promise<unknown> = resolved\n /** Aborts on `destroy`. */\n #abortController = new AbortController()\n /** A setup function is running synchronously right now. */\n #inSyncSetup = false\n #reporting = false\n #nextOrdinal = 0\n\n constructor(options: AppOptions, defaults: readonly AnyPlugin[]) {\n this.#options = options\n this.#config = {\n options,\n defaults,\n disabled: new Set(Array.isArray(options.disable) ? options.disable : []),\n reserved: isReserved,\n }\n this.name = options.name ?? 'app'\n const sink = options.logger ?? console\n const level = options.logLevel ?? 'warn'\n this.#errorLog = createLogger(sink, level, '')\n const timeout = options.setupTimeout\n this.#setupTimeout =\n typeof timeout === 'number' && timeout > 0 ? timeout : DEFAULT_SETUP_TIMEOUT\n const depth: Depth = { value: 0 }\n const report = this.report.bind(this)\n this.events = new EventBus(report, depth)\n this.hooks = new HookBus(report, depth)\n // One lazily built logger per owner. The root's is the app-wide one.\n const logFor = (owner: Owner): Logger => {\n const parts = ['diorama', options.name, owner.plugin].filter(Boolean)\n return createLogger(sink, level, `[${parts.join(':')}]`)\n }\n this.root = new Owner({ env: { report, logFor }, label: 'app', rank: Number.POSITIVE_INFINITY })\n this.loop = new LoopImpl(options.loop, report, (message) => this.root.log.warn(message))\n this.#viewProto = Object.create(VIEW_PROTO, { [KERNEL]: { value: this } })\n this.#scopeProto = Object.create(this.#viewProto, describe(SCOPE_METHODS))\n this.rootView = Object.create(Object.create(this.#viewProto, describe(ROOT_METHODS)), {\n [OWNER]: { value: this.root },\n })\n }\n\n view(owner: Owner, scope: boolean): View {\n return Object.create(scope ? this.#scopeProto : this.#viewProto, { [OWNER]: { value: owner } })\n }\n\n report(error: unknown, source: ErrorSource, owner: Owner | undefined, target?: string): void {\n const wrapped = toDioramaError(error, source, owner?.plugin)\n // A failure inside an app:error listener or onError must not recurse.\n if (this.#reporting) {\n console.error(wrapped)\n return\n }\n this.#reporting = true\n try {\n this.#errorLog.error(wrapped)\n const report: ErrorReport = {\n error: wrapped,\n source,\n plugin: owner?.plugin ?? wrapped.plugin,\n target,\n }\n this.events.emit('app:error', report)\n this.#options.onError?.(report)\n } catch (failure) {\n console.error(failure)\n } finally {\n this.#reporting = false\n }\n }\n\n has(ref: DependencyRef): boolean {\n return this.#records.get(refName(ref) ?? '')?.status === 'running'\n }\n\n service(owner: Owner, ref: DependencyRef, required: boolean): unknown {\n const name = refName(ref) ?? String(ref)\n // Plugin views see only their declared dependencies, in every build.\n if (owner.allowed && !owner.allowed.has(name)) {\n throw new DioramaError('UNDECLARED_DEPENDENCY', `\"${name}\" is not a declared dependency`, {\n plugin: owner.plugin,\n })\n }\n const record = this.#records.get(name)\n if (!owner.disposed && record?.status === 'running') return record.service\n if (!required) return undefined\n throw new DioramaError('SERVICE_UNAVAILABLE', this.#whyUnavailable(name, record, owner), {\n plugin: owner.plugin,\n })\n }\n\n #whyUnavailable(name: string, record: PluginRecord | undefined, owner: Owner): string {\n if (this.state.peek() === 'destroyed') return `\"${name}\": the app is destroyed`\n if (owner.disposed) return `\"${name}\": this view is closed`\n if (!record) return `\"${name}\" is not installed${missingHint(this.#config, name)}`\n return `\"${name}\" is ${record.status}${record.error ? `: ${record.error.message}` : ''}`\n }\n\n start(): Promise<unknown> {\n if (this.#starting) return this.#starting\n if (this.#stopping) return Promise.reject(destroyed())\n // The queue must exist before #run flips the state: effects on `state` may call use().\n let release: () => void = noop\n this.#operations = new Promise<void>((resolve) => {\n release = resolve\n })\n this.#starting = this.#run()\n void this.#starting.then(release, release)\n return this.#starting\n }\n\n async #run(): Promise<unknown> {\n this.state.value = 'starting'\n const { signal } = this.#abortController\n try {\n const problems: DioramaError[] = []\n const entries = collectEntries(this.#config, problems)\n const { list, failures } = await resolveEntries(this.#config, entries)\n if (signal.aborted) throw aborted()\n const ordered = this.#register(list, failures, problems)\n for (const record of ordered) {\n if (signal.aborted) throw aborted()\n if (record.status === 'failed') continue\n const stopped = record.deps.find((name) => !this.has(name))\n const error =\n stopped === undefined\n ? await this.#startPlugin(record, signal)\n : this.#skip(record, stopped)\n // failFast ends the start on a plugin's own failure, not on a skipped dependent.\n if (error && (record.critical || (this.#options.failFast && stopped === undefined))) {\n return this.#fail(error)\n }\n }\n if (signal.aborted) throw aborted()\n } catch (error) {\n if (signal.aborted || this.state.peek() !== 'starting') throw error\n // An unexpected throw must not leave the app stuck in `starting`.\n const wrapped = toDioramaError(error, 'config', undefined)\n this.report(wrapped, 'config', undefined)\n return this.#fail(wrapped)\n }\n\n this.state.value = 'running'\n // A `state` subscriber may have destroyed the app on this very transition.\n if (this.#stopping) throw aborted()\n this.loop.attach()\n this.events.emit('app:start', undefined)\n return this.rootView\n }\n\n /**\n * Orders the resolved plugins and registers them. Fails the start on a fatal configuration\n * problem; other problems only fail their plugin.\n */\n #register(\n list: readonly PluginRecord[],\n failures: ReadonlyMap<PluginRecord, DioramaError>,\n problems: DioramaError[],\n ): PluginRecord[] {\n const ordered = orderPlugins(list)\n if (!Array.isArray(ordered)) problems.push(cycleError(ordered.cycle))\n // Configuration errors only cost the plugin unless it is critical or failFast is set.\n for (const [record, error] of failures) {\n if (record.critical || this.#options.failFast) problems.push(error)\n }\n if (problems.length || !Array.isArray(ordered)) {\n const error =\n problems.length === 1\n ? (problems[0] as DioramaError)\n : new DioramaError('CONFIG_INVALID', `${problems.length} configuration problems`, {\n problems,\n })\n this.report(error, 'config', undefined)\n return this.#fail(error)\n }\n\n for (const record of ordered) {\n record.ordinal = this.#nextOrdinal++\n this.#records.set(record.name, record)\n }\n for (const [record, error] of failures) {\n record.error = error\n this.#setStatus(record, 'failed', error)\n this.report(error, 'config', undefined)\n }\n return ordered\n }\n\n /** Skips a plugin whose dependency is not running. The root cause is reported already. */\n #skip(record: PluginRecord, stopped: string): DioramaError {\n const error = new DioramaError(\n 'PLUGIN_DEPENDENCY_FAILED',\n `dependency \"${stopped}\" is not running`,\n { plugin: record.name },\n )\n record.error = error\n this.root.log.warn(error.message)\n this.#setStatus(record, 'skipped', error)\n return error\n }\n\n /** Rolls back a start and enters `failed`. */\n #fail(error: DioramaError): never {\n for (const record of this.#live()) this.#rollbacks.push(this.#stopPlugin(record))\n this.#rollbacks.push(this.root.dispose())\n this.loop.stop()\n this.state.value = 'failed'\n throw error\n }\n\n /** Plugins holding a scope, latest first. */\n #live(): PluginRecord[] {\n return [...this.#records.values()]\n .filter((record) => record.scope)\n .sort((a, b) => b.ordinal - a.ordinal)\n }\n\n #setStatus(record: PluginRecord, status: PluginStatus, error?: DioramaError): void {\n const previous = record.status\n record.status = status\n this.events.emit('plugin:status', { name: record.name, status, previous, error })\n }\n\n /** Runs one setup and returns its failure. ABORTED is thrown to the caller. */\n async #startPlugin(record: PluginRecord, signal: AbortSignal): Promise<DioramaError | undefined> {\n const scope = this.root.child({\n label: record.name,\n rank: record.ordinal,\n plugin: record.name,\n allowed: new Set([record.name, ...record.deps, ...record.optional]),\n })\n scope.ready = false\n record.scope = scope\n record.error = undefined\n this.#setStatus(record, 'starting')\n let service: unknown\n try {\n let result: unknown\n this.#inSyncSetup = true\n try {\n result = record.def.setup(this.view(scope, false), record.options)\n } finally {\n this.#inSyncSetup = false\n }\n service = isThenable(result) ? await this.#race(result, record.name, signal, scope) : result\n // The scope may have closed, or a required dependency stopped, while setup was awaiting.\n if (scope.disposed) throw aborted(record.name)\n const stopped = record.deps.find((name) => !this.has(name))\n if (stopped !== undefined) {\n throw new DioramaError(\n 'PLUGIN_DEPENDENCY_FAILED',\n `dependency \"${stopped}\" stopped during setup`,\n { plugin: record.name },\n )\n }\n } catch (error) {\n return this.#setupFailed(record, scope, signal, error)\n }\n // Running from here on: expose the service as `app.<name>` on every view.\n record.service = service\n record.hasService = service !== undefined\n scope.ready = true\n if (record.hasService) {\n const kernel = this\n Object.defineProperty(this.#viewProto, record.name, {\n configurable: true,\n get(this: View) {\n return kernel.service(this[OWNER], record.name, false)\n },\n })\n }\n this.#setStatus(record, 'running')\n return undefined\n }\n\n /** Undoes a failed setup and returns its error. Rethrows ABORTED of a cancelled start. */\n #setupFailed(\n record: PluginRecord,\n scope: Owner,\n signal: AbortSignal,\n error: unknown,\n ): DioramaError {\n scope.abortOnAdd = true\n void scope.dispose()\n if (record.scope === scope) record.scope = undefined\n if (isDioramaError(error, 'ABORTED') && (signal.aborted || record.status !== 'starting')) {\n throw error\n }\n const failure =\n isDioramaError(error, 'PLUGIN_TIMEOUT') || isDioramaError(error, 'PLUGIN_DEPENDENCY_FAILED')\n ? error\n : new DioramaError('PLUGIN_SETUP', messageOf(error), { plugin: record.name, cause: error })\n record.error = failure\n this.#setStatus(record, 'failed', failure)\n this.report(failure, 'setup', scope)\n return failure\n }\n\n /**\n * Races a setup against the timeout, the app's abort and the plugin scope closing. The\n * losing setup keeps running as an orphan, and `destroy` waits for it, bounded by the timeout.\n */\n #race(\n setup: PromiseLike<unknown>,\n plugin: string,\n appSignal: AbortSignal,\n scope: Owner,\n ): Promise<unknown> {\n const settled = Promise.resolve(setup)\n const orphan = settled.then(noop, noop)\n this.#orphanSetups.add(orphan)\n void orphan.then(() => this.#orphanSetups.delete(orphan))\n return new Promise((resolve, reject) => {\n const signals = [appSignal, scope.signal]\n if (signals.some((s) => s.aborted)) return reject(aborted(plugin))\n const ms = this.#setupTimeout * 1000\n const timer =\n ms <= MAX_TIMER_MS\n ? setTimeout(() => {\n const message = `setup did not finish in ${this.#setupTimeout} s (awaiting use() or remove() from setup deadlocks)`\n reject(new DioramaError('PLUGIN_TIMEOUT', message, { plugin }))\n }, ms)\n : undefined\n const onAbort = (): void => reject(aborted(plugin))\n for (const s of signals) s.addEventListener('abort', onAbort, { once: true })\n const cleanup = (): void => {\n clearTimeout(timer)\n for (const s of signals) s.removeEventListener('abort', onAbort)\n }\n settled.then(\n (value) => {\n cleanup()\n resolve(value)\n },\n (error: unknown) => {\n cleanup()\n reject(error)\n },\n )\n })\n }\n\n #stopPlugin(record: PluginRecord): Promise<void> {\n const { scope } = record\n if (!scope) return resolved\n if (record.status === 'starting') scope.abortOnAdd = true\n this.#setStatus(record, 'stopping')\n if (record.hasService) Reflect.deleteProperty(this.#viewProto, record.name)\n record.hasService = false\n record.service = undefined\n record.scope = undefined\n record.release?.()\n record.release = undefined\n const done = scope.dispose()\n this.#setStatus(record, 'stopped')\n return done\n }\n\n /** Stops required dependents first (latest first), then the plugin itself. */\n #stopTree(record: PluginRecord): Promise<unknown> {\n // A stale record (replaced by a re-install) must not stop its namesake's dependents.\n if (this.#records.get(record.name) !== record) return resolved\n const dependents = this.#dependentsOf(record.name).sort((a, b) => b.ordinal - a.ordinal)\n return Promise.all([...dependents, record].map((r) => this.#stopPlugin(r)))\n }\n\n destroy(): Promise<void> {\n if (this.#stopping) return this.#stopping\n // Claim the promise first so a listener or cleanup calling destroy() again gets this one.\n let finish: (done: Promise<void>) => void = noop\n this.#stopping = new Promise<void>((resolve) => {\n finish = resolve\n })\n const previous = this.state.peek()\n const pending: Promise<unknown>[] = [...this.#rollbacks]\n const waiting = new Set<string>()\n if (previous !== 'idle' && previous !== 'failed') {\n this.state.value = 'destroying'\n this.#abortController.abort()\n // Services are still alive for app:destroy listeners.\n if (previous === 'running') this.events.emit('app:destroy', undefined)\n this.loop.stop()\n for (const record of this.#live()) {\n waiting.add(record.name)\n pending.push(this.#stopPlugin(record).finally(() => waiting.delete(record.name)))\n }\n }\n pending.push(this.root.dispose(), ...this.#orphanSetups)\n this.state.value = 'destroyed'\n finish(this.#settle(pending, waiting))\n return this.#stopping\n }\n\n /** Waits for every cleanup, or warns and gives up after the setup timeout. */\n #settle(pending: Promise<unknown>[], waiting: ReadonlySet<string>): Promise<void> {\n const all = Promise.allSettled(pending).then(noop)\n const ms = this.#setupTimeout * 1000\n if (ms > MAX_TIMER_MS) return all\n return new Promise((resolve) => {\n const timer = setTimeout(() => {\n const message = `destroy: cleanups still pending after ${this.#setupTimeout} s`\n this.root.log.warn(message, [...waiting])\n resolve()\n }, ms)\n void all.then(() => {\n clearTimeout(timer)\n resolve()\n })\n })\n }\n\n /**\n * Runtime operations run one at a time, after start, in call order. Calling one from a\n * running setup is rejected at once: awaiting it there would deadlock the start.\n */\n #enqueue<T>(owner: Owner, operation: () => Promise<T>): Promise<T> {\n const state = this.state.peek()\n if (state === 'destroying' || state === 'destroyed') return Promise.reject(destroyed())\n if (state === 'idle' || state === 'failed') {\n return Promise.reject(new DioramaError('APP_STATE', `the app is ${state}`))\n }\n const ownerStarting = owner.plugin && this.#records.get(owner.plugin)?.status === 'starting'\n if (this.#inSyncSetup || ownerStarting) {\n return Promise.reject(\n new DioramaError('PLUGIN_REENTRANT', 'use() and remove() cannot be called from setup', {\n plugin: owner.plugin,\n }),\n )\n }\n const run = this.#operations.then(() => {\n if (this.#stopping) throw destroyed()\n if (owner.disposed) throw aborted()\n if (this.state.peek() !== 'running') {\n throw new DioramaError('APP_STATE', 'the app did not start')\n }\n return operation()\n })\n this.#operations = run.then(noop, noop)\n return run\n }\n\n use(entry: unknown, owner: Owner): Promise<unknown> {\n return this.#enqueue(owner, () => this.#install(entry, owner))\n }\n\n async #install(entry: unknown, owner: Owner): Promise<unknown> {\n const entries = flattenPlugins(entry).map((plugin, index): Entry => {\n const def = definitionOf(plugin)\n if (!def) throw new DioramaError('PLUGIN_INVALID', `not a plugin: ${String(plugin)}`)\n return { plugin: plugin as AnyPlugin, def, layer: LAYER_RUNTIME, index }\n })\n const { list, failures } = await resolveEntries(this.#config, entries, (name) => this.has(name))\n const cancelled = (): boolean => this.#abortController.signal.aborted || owner.disposed\n if (cancelled()) throw aborted()\n for (const error of failures.values()) throw error\n const ordered = orderPlugins(list.filter((record) => this.#needsInstall(record)))\n if (!Array.isArray(ordered)) throw cycleError(ordered.cycle)\n\n const started: PluginRecord[] = []\n try {\n for (const record of ordered) {\n if (cancelled()) throw aborted()\n record.ordinal = this.#nextOrdinal++\n this.#records.set(record.name, record)\n // Owned before setup, so closing the owner also interrupts a running setup.\n if (owner !== this.root) {\n record.release = owner.add(() => (record.scope ? this.#stopTree(record) : undefined))\n }\n const error = await this.#startPlugin(record, this.#abortController.signal)\n if (error) throw error\n started.push(record)\n }\n } catch (error) {\n for (const record of started.reverse()) await this.#stopPlugin(record)\n // Drop owner links of records that never ran, or a later close could hit a namesake.\n for (const record of ordered) {\n record.release?.()\n record.release = undefined\n }\n throw error\n }\n return typeof entry === 'function' ? this.#records.get(entry.name)?.service : undefined\n }\n\n /**\n * Whether `use` must start this record. Re-installing a running plugin with the same\n * definition and options is a no-op.\n * @throws {DioramaError} `PLUGIN_DUPLICATE` when it runs with other options.\n */\n #needsInstall(record: PluginRecord): boolean {\n const running = this.#records.get(record.name)\n if (running?.status !== 'running') return true\n if (running.def === record.def && shallowEqual(running.raw, record.raw)) return false\n throw new DioramaError(\n 'PLUGIN_DUPLICATE',\n `\"${record.name}\" is already running with other options`,\n { plugin: record.name },\n )\n }\n\n remove(ref: DependencyRef, options: RemoveOptions | undefined, owner: Owner): Promise<boolean> {\n return this.#enqueue(owner, async () => {\n const name = refName(ref) ?? ''\n const record = this.#records.get(name)\n if (!record) return false\n if (record.status === 'running') {\n const dependents = this.#dependentsOf(name)\n if (dependents.length && !options?.cascade) {\n const names = dependents.map((dependent) => dependent.name).join(', ')\n throw new DioramaError('PLUGIN_HAS_DEPENDENTS', `required by ${names}`, { plugin: name })\n }\n await this.#stopTree(record)\n }\n record.release?.()\n this.#records.delete(name)\n return true\n })\n }\n\n /** Running plugins that require `name`, directly or transitively. */\n #dependentsOf(name: string): PluginRecord[] {\n const found = new Set<PluginRecord>()\n const visit = (target: string): void => {\n for (const record of this.#records.values()) {\n if (record.status === 'running' && record.deps.includes(target) && !found.has(record)) {\n found.add(record)\n visit(record.name)\n }\n }\n }\n visit(name)\n return [...found]\n }\n}\n\n/** Synchronous and never throws. Plugins start on `app.start()`. */\nexport function createKernelApp(\n options: AppOptions | undefined,\n defaults: readonly AnyPlugin[],\n): unknown {\n return new Kernel(options ?? {}, defaults).rootView\n}\n\n/** Plugins of a `use()` argument: arrays and presets are opened, falsy entries skipped. */\nfunction flattenPlugins(entry: unknown): unknown[] {\n const plugins: unknown[] = []\n const visit = (value: unknown): void => {\n if (Array.isArray(value)) value.forEach(visit)\n else if (isPreset(value)) [...value.presets, ...value.plugins].forEach(visit)\n else if (value) plugins.push(value)\n }\n visit(entry)\n return plugins\n}\n","/**\n * Calls `swap` after the document's <body> element is replaced (Astro ClientRouter, Turbo).\n * Observes only the childList of <html>, which gives one record per swap and none for page\n * content changes.\n */\nexport function onBodySwap(\n app: { onDispose(cleanup: () => void): unknown },\n swap: (body: HTMLElement, previous: HTMLElement) => void,\n): void {\n if (typeof document === 'undefined' || typeof MutationObserver === 'undefined') return\n let current = document.body\n const observer = new MutationObserver(() => {\n const body = document.body\n if (!body || body === current) return\n const previous = current\n current = body\n swap(body, previous)\n })\n observer.observe(document.documentElement, { childList: true })\n app.onDispose(() => observer.disconnect())\n}\n","import { definePlugin } from '../kernel/plugin'\nimport type { Plugin } from '../kernel/types'\nimport { noop } from '../kernel/util'\nimport { onBodySwap } from './body'\n\n/** An element's box, kept in sync with the page in the `layout` stage. */\nexport interface Anchor {\n /** The tracked element. */\n readonly element: Element\n /** Viewport position and size, CSS px. */\n readonly x: number\n /** Viewport y, CSS px. */\n readonly y: number\n /** Width, CSS px. */\n readonly width: number\n /** Height, CSS px. */\n readonly height: number\n /** Overlaps the viewport. */\n readonly visible: boolean\n /**\n * 0 as the top enters at the bottom of the viewport, 1 as the bottom leaves at the top.\n * Measured along `scroll.state.axis`, so a horizontal source runs it from right to left.\n */\n readonly progress: number\n /**\n * Progress of a section pinned with CSS sticky. 0 while its top is below the viewport top,\n * 1 once it has scrolled `height - viewport height` past it. A section no taller than the\n * viewport switches from 0 to 1 as its top passes the viewport top.\n */\n readonly pin: number\n /** Counts re-measures after layout changes. Per-frame live reads don't bump it. */\n readonly version: number\n /** Stops tracking. Pass the anchor to `app.onDispose` to tie it to a scope. */\n dispose(): void\n}\n\n/** Options of `anchors.track`. */\nexport interface TrackOptions {\n /**\n * Re-read the box every frame while near the viewport, to follow transforms and inline\n * `position: fixed`. Elements inside sticky or fixed ancestors are live by themselves.\n */\n readonly live?: boolean\n}\n\n/** The `anchors` service: element boxes kept in sync with the page. */\nexport interface AnchorsApi {\n /** Starts tracking an element. The anchor updates in the `layout` stage. */\n track(element: Element, options?: TrackOptions): Anchor\n /** Re-measures every anchor after a layout change the observers cannot see. */\n refresh(): void\n}\n\n/** The anchor object itself, with the cached page geometry behind it. */\ninterface Entry {\n element: Element\n x: number\n y: number\n width: number\n height: number\n visible: boolean\n progress: number\n pin: number\n version: number\n /** Position relative to the document, measured with the DOM. */\n pageX: number\n pageY: number\n /** `track` asked for `live`. */\n manual: boolean\n /** Re-read every frame while near the viewport: manual, or inside sticky or fixed. */\n live: boolean\n /** Page band a sticky element moves within along the axis. Unbounded when fixed, else empty. */\n start: number\n end: number\n dispose(): void\n}\n\n/** How far ahead of the viewport, in viewport sizes, a live anchor is still re-read. */\nconst NEAR_AHEAD = 2\n\n/**\n * What moves an element without a layout change: the box its outermost sticky ancestor moves\n * within, `fixed` for a fixed ancestor, or `null`. `positions` caches computed styles per pass.\n */\nconst stickyContainer = (\n element: Element,\n positions: Map<Element, string>,\n): Element | 'fixed' | null => {\n let within: Element | null = null\n for (let node: Element | null = element; node; node = node.parentElement) {\n let position = positions.get(node)\n if (position === undefined) {\n position = getComputedStyle(node).position\n positions.set(node, position)\n }\n if (position === 'fixed') return 'fixed'\n if (position === 'sticky') within = node.parentElement\n }\n return within\n}\n\n/** A page band near the viewport along the scroll axis, at scroll offset `at`. Behind the\n * viewport it counts as near for one viewport size. */\nconst isNear = (start: number, end: number, at: number, size: number): boolean =>\n start - at < NEAR_AHEAD * size && end - at > -size\n\n/**\n * Layout is read only when something may have moved (resize, observed size changes,\n * fonts). Each frame just offsets the cached page boxes by the scroll position. Live anchors\n * near the viewport are re-read every frame, since sticky, fixed and transformed boxes move\n * without a layout change.\n */\nexport const anchors: Plugin<'anchors'> = /*#__PURE__*/ definePlugin({\n name: 'anchors',\n dependencies: ['stage', 'scroll'],\n setup(app): AnchorsApi {\n const { stage, scroll } = app\n const entries = new Set<Entry>()\n // Boxes must be read from the DOM before the next frame uses them.\n let stale = true\n let horizontal = false\n /** Scroll offset along the axis in the last frame. */\n let lastAlong = 0\n const refresh = (): void => {\n stale = true\n app.invalidate()\n }\n\n const observer = typeof ResizeObserver === 'undefined' ? undefined : new ResizeObserver(refresh)\n // Entries of one element share its observation. The last one to go ends it.\n const counts = new Map<Element, number>()\n const observe = (element: Element): void => {\n const count = counts.get(element) ?? 0\n counts.set(element, count + 1)\n if (!count) observer?.observe(element)\n }\n const unobserve = (element: Element): void => {\n const count = (counts.get(element) ?? 1) - 1\n if (count) counts.set(element, count)\n else if (counts.delete(element)) observer?.unobserve(element)\n }\n if (typeof document !== 'undefined') {\n observe(document.body)\n window.addEventListener('resize', refresh, { signal: app.abortSignal })\n document.fonts?.ready.then(refresh, noop)\n onBodySwap(app, (body, previous) => {\n unobserve(previous)\n observe(body)\n refresh()\n })\n }\n app.onDispose(() => {\n observer?.disconnect()\n counts.clear()\n entries.clear()\n })\n\n const readBox = (entry: Entry, scrollX: number, scrollY: number): void => {\n const box = entry.element.getBoundingClientRect()\n entry.pageX = box.left + scrollX\n entry.pageY = box.top + scrollY\n entry.width = box.width\n entry.height = box.height\n }\n\n app.system(\n 'layout',\n () => {\n const { x: scrollX, y: scrollY, axis } = scroll.state\n const width = stage.width.peek()\n const height = stage.height.peek()\n // Progress, pin and nearness run along the scroll axis, so a horizontal source measures\n // by width. Sticky bands are stored along it too, so a new axis re-measures.\n if (horizontal !== (axis === 'x')) {\n horizontal = !horizontal\n stale = true\n }\n const along = horizontal ? scrollX : scrollY\n const size = horizontal ? width : height\n // Reads only in this pass, so layout is forced at most once.\n const positions = stale ? new Map<Element, string>() : undefined\n // Cached boxes cannot be trusted to say what is near after a jump.\n const jumped = Math.abs(along - lastAlong) > size\n stale = false\n lastAlong = along\n for (const entry of entries) {\n if (positions) {\n // Full measure after a layout change: the box and what moves it.\n readBox(entry, scrollX, scrollY)\n entry.version++\n const container = stickyContainer(entry.element, positions)\n const band =\n container && container !== 'fixed' ? container.getBoundingClientRect() : undefined\n entry.live = entry.manual || container !== null\n // A fixed element is near everywhere, one that is not sticky only by its own box.\n const unbounded = container ? Infinity : -Infinity\n entry.start = band ? (horizontal ? band.left : band.top) + along : -unbounded\n entry.end = band ? (horizontal ? band.right : band.bottom) + along : unbounded\n } else if (entry.live) {\n const start = horizontal ? entry.pageX : entry.pageY\n const end = start + (horizontal ? entry.width : entry.height)\n if (\n jumped ||\n isNear(entry.start, entry.end, along, size) ||\n isNear(start, end, along, size)\n ) {\n readBox(entry, scrollX, scrollY)\n }\n }\n // Viewport box, visibility, progress and pin from the cached page box.\n entry.x = entry.pageX - scrollX\n entry.y = entry.pageY - scrollY\n entry.visible =\n entry.width > 0 &&\n entry.x < width &&\n entry.x + entry.width > 0 &&\n entry.y < height &&\n entry.y + entry.height > 0\n const at = horizontal ? entry.x : entry.y\n const length = horizontal ? entry.width : entry.height\n entry.progress = Math.min(1, Math.max(0, (size - at) / (size + length || 1)))\n const travel = length - size\n entry.pin = travel > 0 ? Math.min(1, Math.max(0, -at / travel)) : at <= 0 ? 1 : 0\n }\n },\n { name: 'anchors' },\n )\n\n return {\n refresh,\n track(element, options) {\n const manual = options?.live === true\n const entry: Entry = {\n element,\n x: 0,\n y: 0,\n width: 0,\n height: 0,\n visible: false,\n progress: 0,\n pin: 0,\n version: 0,\n pageX: 0,\n pageY: 0,\n manual,\n live: manual,\n start: Infinity,\n end: -Infinity,\n dispose() {\n if (entries.delete(entry)) unobserve(element)\n },\n }\n entries.add(entry)\n observe(element)\n refresh()\n return entry\n },\n }\n },\n})\n","import type { FrameTime } from '../kernel/types'\n\n/** Smoothing rate of velocities, per second. Frame-rate independent. */\nconst SMOOTHING = 10\n/** Below this speed (px/s) motion counts as settled. */\nconst REST_SPEED = 1\n/** Without frames for this long (ms) a velocity counts as settled. */\nconst STALE_MS = 100\n\n/** A smoothed velocity fed once per frame. */\nexport interface VelocityTracker {\n /** The smoothed velocity. Reading it before it settles asks for the next frame. */\n readonly value: number\n /** Feeds the distance moved since the previous frame. */\n update(distance: number, t: FrameTime): void\n}\n\n/**\n * Exponentially smoothed velocity. Frames keep coming while someone reads it as it decays, so\n * effects driven by it ease out instead of freezing mid-motion. Unread, it asks for none.\n */\nexport function velocityTracker(app: {\n invalidate(): void\n readonly loop: { readonly driver: { now(): number } }\n}): VelocityTracker {\n let velocity = 0\n /** Driver time of the last update. */\n let updatedAt = 0\n return {\n get value() {\n if (velocity) {\n // Nobody read it while frames were stopped, so it would have settled by now.\n if (app.loop.driver.now() - updatedAt > STALE_MS) velocity = 0\n else app.invalidate()\n }\n return velocity\n },\n update(distance, time) {\n const instant = time.delta > 0 ? distance / time.delta : 0\n velocity += (instant - velocity) * (1 - Math.exp(-time.delta * SMOOTHING))\n if (Math.abs(velocity) <= REST_SPEED) velocity = 0\n updatedAt = time.now\n },\n }\n}\n","import { definePlugin } from '../kernel/plugin'\nimport type { Plugin } from '../kernel/types'\nimport { velocityTracker } from './motion'\n\n/**\n * Live pointer state. A move asks for a frame only if someone read the position in the last\n * frame (or since), so a page whose effects ignore the pointer draws nothing on mouse moves.\n */\nexport interface PointerState {\n /** Viewport position, CSS px. */\n readonly x: number\n /** Viewport y, CSS px. */\n readonly y: number\n /** Normalized device coordinates, -1..1, y up. */\n readonly nx: number\n /** Normalized y, -1..1, up is positive. */\n readonly ny: number\n /** Smoothed velocity, px/s. Reading it while it decays keeps frames coming. */\n readonly vx: number\n /** Smoothed vertical velocity, px/s. */\n readonly vy: number\n /** The pointer is over the page. A touch leaves when the finger lifts. */\n readonly inside: boolean\n /** Device of the last pointer event. */\n readonly type: 'mouse' | 'pen' | 'touch'\n}\n\n/** The `pointer` service. */\nexport interface PointerApi {\n /** Pointer state, updated in place every frame. */\n readonly state: PointerState\n}\n\n/** Tracks the pointer over the page. Built in. */\nexport const pointer: Plugin<'pointer'> = /*#__PURE__*/ definePlugin({\n name: 'pointer',\n dependencies: ['stage'],\n setup(app): PointerApi {\n const trackX = velocityTracker(app)\n const trackY = velocityTracker(app)\n let x = 0\n let y = 0\n let inside = false\n // The frame of the last read. Moves wake the loop only for a reader.\n let readFrame = -1\n const markRead = (): void => {\n readFrame = app.loop.time.frame\n }\n const state = {\n get x() {\n markRead()\n return x\n },\n get y() {\n markRead()\n return y\n },\n get nx() {\n markRead()\n return (x / (app.stage.width.peek() || 1)) * 2 - 1\n },\n get ny() {\n markRead()\n return 1 - (y / (app.stage.height.peek() || 1)) * 2\n },\n get vx() {\n markRead()\n return trackX.value\n },\n get vy() {\n markRead()\n return trackY.value\n },\n get inside() {\n markRead()\n return inside\n },\n type: 'mouse' as PointerState['type'],\n }\n if (typeof window === 'undefined') return { state }\n\n const wake = (): void => {\n if (readFrame >= app.loop.time.frame) app.invalidate()\n }\n const listen = { signal: app.abortSignal, passive: true }\n const move = (event: PointerEvent): void => {\n x = event.clientX\n y = event.clientY\n const { pointerType } = event\n state.type = pointerType === 'touch' || pointerType === 'pen' ? pointerType : 'mouse'\n inside = true\n wake()\n }\n const leave = (): void => {\n inside = false\n wake()\n }\n // A lifted finger hovers nothing. Without this, hover sticks after a tap.\n const lift = (event: PointerEvent): void => {\n if (event.pointerType === 'touch') leave()\n }\n window.addEventListener('pointermove', move, listen)\n window.addEventListener('pointerdown', move, listen)\n window.addEventListener('pointerup', lift, listen)\n window.addEventListener('pointercancel', lift, listen)\n document.documentElement.addEventListener('pointerleave', leave, listen)\n\n // Velocity is fed per frame. Entering (first move, back over the page, a new touch)\n // re-bases without a spike.\n let lastX = 0\n let lastY = 0\n let wasInside = false\n app.system(\n 'input',\n (time) => {\n const entered = inside && !wasInside\n wasInside = inside\n trackX.update(entered ? 0 : x - lastX, time)\n trackY.update(entered ? 0 : y - lastY, time)\n lastX = x\n lastY = y\n },\n { name: 'pointer' },\n )\n return { state }\n },\n})\n","import { definePlugin } from '../kernel/plugin'\nimport type { Off, Plugin } from '../kernel/types'\nimport { noop } from '../kernel/util'\nimport { onBodySwap } from './body'\nimport { velocityTracker } from './motion'\n\n/** Scroll axis: `x` for horizontal, `y` for vertical. */\nexport type ScrollAxis = 'x' | 'y'\n\n/** Live scroll state, updated in place in the `input` stage. */\nexport interface ScrollState {\n /** Document scroll offset, CSS px. */\n readonly x: number\n /** Vertical document scroll offset, CSS px. */\n readonly y: number\n /**\n * Smoothed velocity along `axis`, px/s, positive while scrolling down (or right). Reading it\n * while it decays keeps frames coming.\n */\n readonly velocity: number\n /** 1 down, -1 up, 0 at rest. */\n readonly direction: -1 | 0 | 1\n /** 0..1 through the scrollable range along `axis`. */\n readonly progress: number\n /** Axis of `progress`, `velocity` and `direction`. The active source's, or 'y' without one. */\n readonly axis: ScrollAxis\n}\n\n/** One frame's reading of a scroll source, filled in place. */\nexport interface ScrollSample {\n /** Document scroll offset this frame, CSS px, as the page shows it. */\n x: number\n /** Vertical offset this frame, CSS px. */\n y: number\n /** Continuous position along the axis for velocity. An infinite scroller doesn't wrap it. */\n travel: number\n}\n\n/** Where `scroll` takes the offset from. Without one, window scroll events are cached. */\nexport interface ScrollSource {\n /** Label for logs. */\n readonly name: string\n /** Axis of `progress`, `velocity`, `direction`. Default 'y'. */\n readonly axis?: ScrollAxis\n /** Called once per frame at the start of the `scroll` system. Reads only, never writes the DOM. */\n read(out: ScrollSample): void\n /** Scrollable range along the axis, CSS px. Default: the measured document range. */\n limit?(): number\n}\n\n/** The `scroll` service. */\nexport interface ScrollApi {\n /** Scroll state, updated in place every frame. */\n readonly state: ScrollState\n /** Re-reads the scrollable range after a layout change the observers cannot see. */\n measure(): void\n /**\n * Reads offsets from `source` from the next frame on. The newest source wins and Off restores\n * the previous one. The switch frame keeps the previous velocity, so there is no spike.\n */\n source(source: ScrollSource): Off\n}\n\nconst finite = (value: number, fallback: number): number =>\n Number.isFinite(value) ? value : fallback\n\n/** Tracks page scroll, its velocity and progress. Built in. */\nexport const scroll: Plugin<'scroll'> = /*#__PURE__*/ definePlugin({\n name: 'scroll',\n setup(app): ScrollApi {\n const track = velocityTracker(app)\n const state = {\n x: 0,\n y: 0,\n get velocity() {\n return track.value\n },\n get direction() {\n return Math.sign(track.value) as -1 | 0 | 1\n },\n progress: 0,\n axis: 'y' as ScrollAxis,\n }\n if (typeof window === 'undefined') return { state, measure: noop, source: () => noop }\n\n const root = document.documentElement\n let x = window.scrollX\n let y = window.scrollY\n let rangeX = 0\n let rangeY = 0\n state.x = x\n state.y = y\n // Scroll events only record the offset. The frame turns it into state.\n const listen = { signal: app.abortSignal, passive: true }\n window.addEventListener(\n 'scroll',\n () => {\n x = window.scrollX\n y = window.scrollY\n app.invalidate()\n },\n listen,\n )\n const measure = (): void => {\n rangeX = Math.max(0, root.scrollWidth - root.clientWidth)\n rangeY = Math.max(0, root.scrollHeight - root.clientHeight)\n app.invalidate()\n }\n measure()\n window.addEventListener('resize', measure, listen)\n const observer = typeof ResizeObserver === 'undefined' ? undefined : new ResizeObserver(measure)\n observer?.observe(document.body)\n if (observer) app.onDispose(() => observer.disconnect())\n onBodySwap(app, (body, previous) => {\n observer?.unobserve(previous)\n observer?.observe(body)\n measure()\n })\n\n const sources: ScrollSource[] = []\n const sample = { x: 0, y: 0, travel: 0 }\n let lastTravel = y\n // The first frame, and the one after a resync, re-base travel without feeding velocity.\n let resync = true\n // The active source threw last frame. Errors are reported once per streak.\n let failing = false\n const switched = (): void => {\n resync = true\n failing = false\n app.invalidate()\n }\n const source = (added: ScrollSource): Off => {\n sources.push(added)\n switched()\n return () => {\n const index = sources.indexOf(added)\n if (index < 0) return\n sources.splice(index, 1)\n switched()\n }\n }\n\n /** Fills `sample` from the active source, or from native offsets if it throws. */\n const readSource = (active: ScrollSource): number | undefined => {\n sample.x = x\n sample.y = y\n sample.travel = lastTravel\n try {\n active.read(sample)\n const limit = active.limit?.()\n sample.x = finite(sample.x, x)\n sample.y = finite(sample.y, y)\n sample.travel = finite(sample.travel, lastTravel)\n // A recovering source may be in another domain than the native fallback.\n if (failing) resync = true\n failing = false\n return limit\n } catch (error) {\n if (!failing) app.report(error, `scroll:${active.name}`)\n failing = true\n sample.x = x\n sample.y = y\n sample.travel = lastTravel\n return undefined\n }\n }\n\n app.system(\n 'input',\n (time) => {\n const active = sources.at(-1)\n let limit: number | undefined\n if (active) {\n limit = readSource(active)\n } else {\n sample.x = x\n sample.y = y\n sample.travel = y\n }\n const axis = active?.axis ?? 'y'\n const moved = sample.travel - lastTravel\n // A jump (restore, #hash, scrollTo immediate) or a wake after idle is no motion.\n if (resync || time.resumed) resync = false\n else if (Math.abs(moved) > (axis === 'x' ? innerWidth : innerHeight)) resync = false\n else track.update(moved, time)\n lastTravel = sample.travel\n let range = axis === 'x' ? rangeX : rangeY\n if (Number.isFinite(limit) && (limit as number) > 0) range = limit as number\n const offset = axis === 'x' ? sample.x : sample.y\n state.axis = axis\n state.x = sample.x\n state.y = sample.y\n state.progress = range > 0 ? Math.min(1, Math.max(0, offset / range)) : 0\n },\n { name: 'scroll' },\n )\n return { state, measure, source }\n },\n})\n","import type { AppCore, Off } from '../kernel/types'\n\nconst KEYFRAMES = 'dio-stage-scroll'\n/** Scroll covered by the follow animation, px. Past it the canvas stays put. */\nconst RANGE = 1_000_000\nlet sheet: CSSStyleSheet | undefined\n\n/** Starts following a canvas; `hold` keeps it still while a predicate is true. */\nexport interface Follow {\n (canvas: HTMLCanvasElement): void\n hold(held: () => boolean): Off\n}\n\n/**\n * Lets a fixed canvas follow page scroll on the compositor. A scroll timeline applies\n * `translateY(-scroll)` in every compositor frame, and each Diorama frame adds back, through\n * `translate`, the scroll it drew at. Between frames the canvas moves with the page by the\n * scroll the frame has not seen yet.\n *\n * Content that stands still on screen (a pinned sticky stage) would ride that scroll and jump\n * back when the frame lands, so while any `hold` predicate is true the canvas drops the\n * animation and stays fixed to the viewport, and frames draw at scroll 0. Predicates run in\n * `afterRender`, after the frame's layout reads, and the animation and the offset switch in\n * that same frame. Needs a DOM.\n */\nexport function followScroll(app: Pick<AppCore, 'system'>): Follow {\n const root = document.documentElement\n const holds = new Set<() => boolean>()\n let followed: { canvas: HTMLCanvasElement; computed: CSSStyleDeclaration } | undefined\n /** The site's styles keep the animation. */\n let animated = false\n /** The page scroll this frame draws at. */\n let drawnAt = 0\n /** A hold has dropped the animation. */\n let held = false\n /** The offset last written to `translate`. */\n let written = 0\n app.system(\n 'layout',\n () => {\n if (!followed) return\n adoptKeyframes()\n // A stylesheet that drops the animation (`animation: none !important`) turns following\n // off. While held the computed name is the hold's own `none`, so the last reading stays.\n if (!held) {\n const { animationName, animationTimeline } = followed.computed\n animated = animationName === KEYFRAMES && animationTimeline?.startsWith('scroll(') !== false\n }\n // The timeline is clamped to the scroll range, rubber-band overscroll is not.\n const max = root.scrollHeight - root.clientHeight\n drawnAt = animated ? Math.max(0, Math.min(window.scrollY, max, RANGE)) : 0\n },\n { name: 'stage' },\n )\n app.system(\n 'afterRender',\n () => {\n if (!followed) return\n let hold = false\n if (animated) {\n for (const predicate of holds) if (predicate()) hold = true\n }\n if (hold !== held) {\n held = hold\n followed.canvas.style.animationName = hold ? 'none' : KEYFRAMES\n }\n const offset = hold ? 0 : drawnAt\n if (offset === written) return\n written = offset\n followed.canvas.style.translate = offset ? `0px ${offset}px` : ''\n },\n { name: 'stage' },\n )\n const follow = ((canvas) => {\n const computed = startAnimation(canvas)\n if (computed) followed = { canvas, computed }\n }) as Follow\n follow.hold = (predicate) => {\n // Its own entry, so one predicate held twice needs both offs.\n const entry = (): boolean => predicate()\n holds.add(entry)\n return () => void holds.delete(entry)\n }\n return follow\n}\n\n/** Adopts the keyframes, again if a site reassigns `document.adoptedStyleSheets`. */\nfunction adoptKeyframes(): void {\n if (!sheet) {\n sheet = new CSSStyleSheet()\n sheet.replaceSync(`@keyframes ${KEYFRAMES} { to { transform: translateY(-${RANGE}px) } }`)\n }\n const sheets = document.adoptedStyleSheets\n if (!sheets.includes(sheet)) document.adoptedStyleSheets = [...sheets, sheet]\n}\n\n/** Starts the scroll-timeline animation on `canvas`. `undefined` if the engine lacks it. */\nfunction startAnimation(canvas: HTMLCanvasElement): CSSStyleDeclaration | undefined {\n // Engines with scroll timelines (Chrome 115, Safari 26) all have constructable stylesheets.\n if (typeof CSS === 'undefined' || !CSS.supports?.('animation-timeline: scroll(root y)')) return\n adoptKeyframes()\n canvas.style.cssText +=\n `animation:${KEYFRAMES} linear both;` +\n `animation-timeline:scroll(root y);animation-range:0px ${RANGE}px`\n return getComputedStyle(canvas)\n}\n","import { DioramaError } from '../kernel/errors'\nimport { definePlugin } from '../kernel/plugin'\nimport { batch, signal } from '../kernel/signals'\nimport type { Off, Plugin, ReadonlySignal } from '../kernel/types'\nimport { noop } from '../kernel/util'\nimport { onBodySwap } from './body'\nimport { followScroll } from './follow'\n\n/** Options of the `stage` plugin. */\nexport interface StageOptions {\n /**\n * Canvas or selector to draw into. By default a fixed full-viewport canvas is created. A\n * selector that matches no canvas fails the plugin with `PLUGIN_OPTIONS`.\n */\n readonly canvas: HTMLCanvasElement | string | undefined\n /** z-index of the created canvas. It sits above content, which stays interactive. Default 1. */\n readonly zIndex: number\n /** Upper bound for the device pixel ratio. Default 2. */\n readonly maxPixelRatio: number\n /**\n * Keeps GL copies on their elements while the browser scrolls the page ahead of the next frame\n * (keyboard, scrollbar, native wheel, touch). The created canvas moves with the page on the\n * compositor until the frame lands, and GL content fixed to the viewport moves with it for that\n * time. While a `stage.hold` predicate is true (effects: a pinned sticky stage of a scroll\n * section) the canvas stays fixed to the viewport instead. Vertical page scroll only. Needs CSS\n * scroll-driven animations. Default true.\n */\n readonly followScroll: boolean\n}\n\n/** The `stage` service: the canvas and the viewport. */\nexport interface StageApi {\n /** The page-wide canvas, created on first access. `undefined` without a DOM. */\n readonly canvas: HTMLCanvasElement | undefined\n /** Viewport size in CSS px, excluding scrollbars. */\n readonly width: ReadonlySignal<number>\n /** Viewport height in CSS px, excluding scrollbars. */\n readonly height: ReadonlySignal<number>\n /** Device pixel ratio, capped by `maxPixelRatio`. */\n readonly pixelRatio: ReadonlySignal<number>\n /** Whether the user prefers reduced motion. */\n readonly reducedMotion: ReadonlySignal<boolean>\n /**\n * Keeps the created canvas from following scroll (`followScroll`) while `held()` is true:\n * for content that stands still on screen as the page scrolls, such as a pinned sticky stage.\n * Read once per frame after the frame is drawn; the switch lands with that frame. Returns a\n * function that removes the predicate. Without following it does nothing.\n */\n hold(held: () => boolean): Off\n}\n\nconst defaults: StageOptions = {\n canvas: undefined,\n zIndex: 1,\n maxPixelRatio: 2,\n followScroll: true,\n}\n\n/** Canvases created by live apps. Any other `canvas[data-dio-canvas]` is a stale clone. */\nconst liveCanvases = new WeakSet<Element>()\n\n/** One canvas for the whole site. It outlives page transitions. */\nexport const stage: Plugin<'stage', StageOptions> = /*#__PURE__*/ definePlugin({\n name: 'stage',\n defaults,\n setup(app, options): StageApi {\n const width = signal(0)\n const height = signal(0)\n const pixelRatio = signal(1)\n const reducedMotion = signal(false)\n const api: StageApi = {\n canvas: undefined,\n width,\n height,\n pixelRatio,\n reducedMotion,\n hold: () => noop,\n }\n if (typeof document === 'undefined') return api\n\n const root = document.documentElement\n const measure = (): void => {\n batch(() => {\n width.value = root.clientWidth\n height.value = root.clientHeight\n pixelRatio.value = Math.min(window.devicePixelRatio || 1, options.maxPixelRatio)\n })\n app.invalidate()\n }\n measure()\n const listen = { signal: app.abortSignal }\n window.addEventListener('resize', measure, listen)\n\n const reduceQuery = window.matchMedia?.('(prefers-reduced-motion: reduce)')\n if (reduceQuery) {\n const update = (): void => {\n reducedMotion.value = reduceQuery.matches\n }\n update()\n reduceQuery.addEventListener('change', update, listen)\n }\n\n const follow = followScroll(app)\n\n let canvas: HTMLCanvasElement | undefined\n // Runs once for a canvas the plugin created: it follows scroll and lives as long as the app.\n const adopt = (created: HTMLCanvasElement): void => {\n if (options.followScroll) follow(created)\n liveCanvases.add(created)\n app.onDispose(() => {\n liveCanvases.delete(created)\n created.remove()\n })\n // A replaced <body> takes the canvas with it, so move it into the new one.\n onBodySwap(app, (body) => {\n // Clones from a cached snapshot are dead full-screen canvases.\n for (const clone of body.querySelectorAll('canvas[data-dio-canvas]')) {\n if (!liveCanvases.has(clone)) clone.remove()\n }\n if (!created.isConnected) body.append(created)\n app.invalidate()\n })\n }\n return {\n ...api,\n hold: follow.hold,\n get canvas() {\n canvas ??= resolveCanvas(options, adopt)\n return canvas\n },\n }\n },\n})\n\n/** The canvas of `options.canvas`, or a new full-viewport one passed to `adopt`. */\nfunction resolveCanvas(\n options: StageOptions,\n adopt: (created: HTMLCanvasElement) => void,\n): HTMLCanvasElement {\n const { canvas } = options\n if (canvas instanceof HTMLCanvasElement) return canvas\n if (typeof canvas === 'string') {\n const found = document.querySelector(canvas)\n if (found instanceof HTMLCanvasElement) return found\n throw new DioramaError('PLUGIN_OPTIONS', `no canvas matches \"${canvas}\"`, { plugin: 'stage' })\n }\n const created = document.createElement('canvas')\n created.setAttribute('aria-hidden', 'true')\n // Turbo drops temporary elements from its snapshots. The marker finds clones made otherwise.\n created.setAttribute('data-dio-canvas', '')\n created.setAttribute('data-turbo-temporary', '')\n Object.assign(created.style, {\n position: 'fixed',\n inset: '0',\n width: '100%',\n height: '100%',\n pointerEvents: 'none',\n zIndex: String(options.zIndex),\n })\n document.body.append(created)\n adopt(created)\n return created\n}\n","import { definePlugin } from '../kernel/plugin'\nimport { signal } from '../kernel/signals'\nimport type { Off, Plugin, ReadonlySignal } from '../kernel/types'\n\n/** The `visibility` service. */\nexport interface VisibilityApi {\n /** Whether the tab is visible. */\n readonly visible: ReadonlySignal<boolean>\n}\n\n/** Options of the `visibility` plugin. */\nexport interface VisibilityOptions {\n /** Pause the frame loop while the tab is hidden. Default true. */\n readonly pause: boolean\n}\n\nconst defaults: VisibilityOptions = { pause: true }\n\n/** Tracks tab visibility and pauses frames while the tab is hidden. Built in. */\nexport const visibility: Plugin<'visibility', VisibilityOptions> = /*#__PURE__*/ definePlugin({\n name: 'visibility',\n defaults,\n setup(app, options): VisibilityApi {\n const visible = signal(true)\n if (typeof document === 'undefined') return { visible }\n // Releases the pause taken while the tab is hidden.\n let resume: Off | undefined\n const update = (): void => {\n visible.value = document.visibilityState !== 'hidden'\n if (!visible.peek() && options.pause) resume ??= app.pause('hidden')\n else if (resume) {\n resume()\n resume = undefined\n }\n }\n update()\n document.addEventListener('visibilitychange', update, { signal: app.abortSignal })\n return { visible }\n },\n})\n","import { createKernelApp } from './kernel/app'\nimport type {\n AnyPlugin,\n App,\n AppOptions,\n PluginEntry,\n PresetEntry,\n PresetPlugins,\n ServicesOf,\n} from './kernel/types'\nimport { anchors } from './web/anchors'\nimport { pointer } from './web/pointer'\nimport { scroll } from './web/scroll'\nimport { stage } from './web/stage'\nimport { visibility } from './web/visibility'\n\nexport { manualDriver, offlineDriver, rafDriver, tickerDriver } from './kernel/drivers'\nexport { DioramaError, isDioramaError } from './kernel/errors'\nexport { cancel, isCancel } from './kernel/hooks'\nexport { definePlugin, definePreset } from './kernel/plugin'\nexport { satisfies } from './kernel/semver'\nexport { batch, computed, effect, signal, untracked } from './kernel/signals'\nexport * from './kernel/types'\nexport { VERSION } from './version'\nexport { type Anchor, type AnchorsApi, anchors, type TrackOptions } from './web/anchors'\nexport { type PointerApi, type PointerState, pointer } from './web/pointer'\nexport {\n type ScrollApi,\n type ScrollAxis,\n type ScrollSample,\n type ScrollSource,\n type ScrollState,\n scroll,\n} from './web/scroll'\nexport { type StageApi, type StageOptions, stage } from './web/stage'\nexport { type VisibilityApi, type VisibilityOptions, visibility } from './web/visibility'\n\n/** Built-in web layer, in start order. Disable one with `disable`, or all with `defaults: false`. */\nconst WEB_DEFAULTS = [\n visibility,\n stage,\n scroll,\n pointer,\n anchors,\n] as unknown as readonly AnyPlugin[]\n\n/**\n * Creates an app with the built-in web layer and the given presets and plugins. Call `start()` to\n * run it.\n */\nexport function createApp<\n const P extends readonly PresetEntry[] = [],\n const E extends readonly PluginEntry[] = [],\n>(\n options?: AppOptions<P, E>,\n): App<ServicesOf<PresetPlugins<P[number]> | Extract<E[number], AnyPlugin>>> {\n return createKernelApp(options as AppOptions | undefined, WEB_DEFAULTS) as App<\n ServicesOf<PresetPlugins<P[number]> | Extract<E[number], AnyPlugin>>\n >\n}\n"],"mappings":";;;ACGA,MAAa,UAAkB;;ACA/B,MAAM,iBAAiD;CACrD,QAAQ;CACR,OAAO;CACP,UAAU;CACV,MAAM;CACN,QAAQ;CACR,QAAQ;CACR,SAAS;CACT,MAAM;CACN,QAAQ;AACV;;AAGA,IAAa,eAAb,cAAkC,MAAM;;CAEtC;;CAEA;;CAEA;CAEA,YAAY,MAAiB,SAAiB,UAA+B,CAAC,GAAG;EAC/E,MAAM,SAAS,QAAQ,SAAS,YAAY,QAAQ,OAAO,KAAK;EAChE,MACE,SAAS,GAAG,OAAO,GAAG,KAAK,IAAI,WAAW,IAAI,GAC9C,QAAQ,UAAU,KAAA,IAAY,KAAA,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A,MAAa,aAAoE,2BAAa;CAC5F,MAAM;CACN,YALoC,OAAO,KAK3C;CACA,MAAM,KAAK,SAAwB;EACjC,MAAM,UAAU,OAAO,IAAI;EAC3B,IAAI,OAAO,aAAa,aAAa,OAAO,EAAE,QAAQ;EAEtD,IAAI;EACJ,MAAM,eAAqB;GACzB,QAAQ,QAAQ,SAAS,oBAAoB;GAC7C,IAAI,CAAC,QAAQ,KAAK,KAAK,QAAQ,OAAO,WAAW,IAAI,MAAM,QAAQ;QAC9D,IAAI,QAAQ;IACf,OAAO;IACP,SAAS,KAAA;GACX;EACF;EACA,OAAO;EACP,SAAS,iBAAiB,oBAAoB,QAAQ,EAAE,QAAQ,IAAI,YAAY,CAAC;EACjF,OAAO,EAAE,QAAQ;CACnB;AACF,CAAC;;;ACDD,MAAM,eAAe;CACnB;CACA;CACA;CACA;CACA;AACF;;;;;AAMA,SAAgB,UAId,SAC2E;CAC3E,OAAO,gBAAgB,SAAmC,YAAY;AAGxE"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["defaults"],"sources":["../package.json","../src/version.ts","../src/kernel/errors.ts","../src/kernel/order.ts","../src/kernel/util.ts","../src/kernel/plugin.ts","../src/kernel/semver.ts","../src/kernel/config.ts","../src/kernel/events.ts","../src/kernel/hooks.ts","../src/kernel/drivers.ts","../src/kernel/loop.ts","../src/kernel/scope.ts","../src/kernel/signals.ts","../src/kernel/view.ts","../src/kernel/app.ts","../src/web/body.ts","../src/web/anchors.ts","../src/web/motion.ts","../src/web/pointer.ts","../src/web/scroll.ts","../src/web/follow.ts","../src/web/stage.ts","../src/web/visibility.ts","../src/index.ts"],"sourcesContent":["","import { version } from '../package.json'\n\n/** Version of @dioramajs/core. */\nexport const VERSION: string = version\n","import { withDocs } from '../dev'\nimport type { DioramaErrorOptions, ErrorCode, ErrorSource } from './types'\n\nconst CODE_BY_SOURCE: Record<ErrorSource, ErrorCode> = {\n config: 'CONFIG_INVALID',\n setup: 'PLUGIN_SETUP',\n listener: 'LISTENER',\n hook: 'HOOK',\n system: 'SYSTEM',\n effect: 'EFFECT',\n dispose: 'DISPOSE',\n loop: 'LOOP',\n report: 'REPORTED',\n}\n\n/** An error of the kernel or a plugin. Its message reads `[diorama] CODE: message`. */\nexport class DioramaError extends Error {\n /** Error code, the key of its page in the docs. */\n readonly code: ErrorCode\n /** Plugin the error comes from, if any. */\n readonly plugin: string | undefined\n /** Every problem found, when the error collects several. */\n readonly problems: readonly DioramaError[]\n\n constructor(code: ErrorCode, message: string, options: DioramaErrorOptions = {}) {\n const prefix = options.plugin ? `[diorama:${options.plugin}]` : '[diorama]'\n super(\n withDocs(`${prefix} ${code}: ${message}`, code),\n options.cause === undefined ? undefined : { cause: options.cause },\n )\n this.name = 'DioramaError'\n this.code = code\n this.plugin = options.plugin\n this.problems = options.problems ?? []\n }\n}\n\n/** Whether `value` is a `DioramaError`, with `code` if one is given. */\nexport function isDioramaError(value: unknown, code?: ErrorCode): value is DioramaError {\n if (typeof value !== 'object' || value === null) return false\n // Checks the shape, not the class, so errors from another copy of the package match too.\n const candidate = value as { name?: unknown; code?: unknown }\n return (\n candidate.name === 'DioramaError' &&\n typeof candidate.code === 'string' &&\n (!code || candidate.code === code)\n )\n}\n\nexport function messageOf(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n\n/** Wraps anything thrown as a `DioramaError` whose code says where it was caught. */\nexport function toDioramaError(\n error: unknown,\n source: ErrorSource,\n plugin: string | undefined,\n): DioramaError {\n if (isDioramaError(error)) return error\n return new DioramaError(CODE_BY_SOURCE[source], messageOf(error), { plugin, cause: error })\n}\n","/** An entry ordered by `before`/`after` labels: a hook handler or a system. */\nexport interface Orderable {\n /** Names that `before` and `after` of other entries can refer to. */\n readonly labels: readonly string[]\n readonly before: readonly string[]\n readonly after: readonly string[]\n /** Owning plugin's ordinal. App code uses Infinity and runs after plugins. */\n readonly rank: number\n /** Registration order, the last tie-breaker. */\n readonly seq: number\n}\n\nexport const orderRefs = (ref: string | readonly string[] | undefined): readonly string[] => {\n if (ref === undefined) return []\n return typeof ref === 'string' ? [ref] : ref\n}\n\n/**\n * Topological sort (Kahn's algorithm) over nodes `0..count-1`, where `edges[a]` lists the nodes\n * that must come after `a`. Among the nodes ready at each step it takes the `less`-smallest, so\n * the result is deterministic. Returns the order, or the nodes left inside cycles.\n */\nexport function topologicalSort(\n count: number,\n edges: readonly (readonly number[])[],\n less: (a: number, b: number) => boolean,\n): number[] | { stuck: number[] } {\n const indegree = new Array<number>(count).fill(0)\n for (const targets of edges) {\n for (const target of targets) indegree[target] = (indegree[target] ?? 0) + 1\n }\n const done = new Array<boolean>(count).fill(false)\n const order: number[] = []\n for (;;) {\n let next = -1\n for (let i = 0; i < count; i++) {\n if (!done[i] && indegree[i] === 0 && (next < 0 || less(i, next))) next = i\n }\n if (next < 0) break\n done[next] = true\n order.push(next)\n for (const target of edges[next] ?? []) indegree[target] = (indegree[target] ?? 0) - 1\n }\n if (order.length === count) return order\n return { stuck: [...done.keys()].filter((i) => !done[i]) }\n}\n\n/** One concrete cycle among `stuck` nodes, for error messages. */\nexport function findCycle(\n edges: readonly (readonly number[])[],\n stuck: readonly number[],\n): number[] {\n const inStuck = new Set(stuck)\n const visiting = new Set<number>()\n const visited = new Set<number>()\n const path: number[] = []\n // Depth-first search. Reaching a node still on the path closes a cycle.\n const visit = (node: number): number[] | undefined => {\n visiting.add(node)\n path.push(node)\n for (const next of edges[node] ?? []) {\n if (!inStuck.has(next) || visited.has(next)) continue\n if (visiting.has(next)) return [...path.slice(path.indexOf(next)), next]\n const found = visit(next)\n if (found) return found\n }\n path.pop()\n visiting.delete(node)\n visited.add(node)\n return undefined\n }\n for (const node of stuck) {\n const found = visited.has(node) ? undefined : visit(node)\n if (found) return found\n }\n return [...stuck]\n}\n\n/** Orders entries by before/after, then by (rank, seq). Returns the cycle if there is one. */\nexport function sortOrderables<T extends Orderable>(items: readonly T[]): T[] | { cycle: T[] } {\n const edges: number[][] = items.map(() => [])\n items.forEach((a, i) => {\n items.forEach((b, j) => {\n if (i === j) return\n if (a.before.some((label) => b.labels.includes(label))) edges[i]?.push(j)\n if (a.after.some((label) => b.labels.includes(label))) edges[j]?.push(i)\n })\n })\n const less = (a: number, b: number): boolean => {\n const first = items[a] as T\n const second = items[b] as T\n return first.rank !== second.rank ? first.rank < second.rank : first.seq < second.seq\n }\n const result = topologicalSort(items.length, edges, less)\n if (Array.isArray(result)) return result.map((i) => items[i] as T)\n return { cycle: findCycle(edges, result.stuck).map((i) => items[i] as T) }\n}\n","import type { Logger, LogLevel } from './types'\n\nconst LEVELS: Record<LogLevel, number> = { debug: 0, info: 1, warn: 2, error: 3, silent: 4 }\n\nexport const noop = (): void => {}\n\nexport const resolved: Promise<void> = Promise.resolve()\n\nexport function isThenable(value: unknown): value is PromiseLike<unknown> {\n return (\n (typeof value === 'object' || typeof value === 'function') &&\n value !== null &&\n typeof (value as { then?: unknown }).then === 'function'\n )\n}\n\n/** Copies `base` and overwrites it with the keys of `next` that are not `undefined`. */\nexport function mergeOptions(base: object, next: object | undefined): Record<string, unknown> {\n const result: Record<string, unknown> = { ...base }\n if (!next) return result\n for (const [key, value] of Object.entries(next)) {\n if (value !== undefined) result[key] = value\n }\n return result\n}\n\nexport function shallowEqual(a: object, b: object): boolean {\n const keys = Object.keys(a)\n if (keys.length !== Object.keys(b).length) return false\n const first = a as Record<string, unknown>\n const second = b as Record<string, unknown>\n return keys.every((key) => Object.is(first[key], second[key]))\n}\n\nexport function perfNow(): number {\n return typeof performance === 'undefined' ? Date.now() : performance.now()\n}\n\n/** Forwards to `sink` the calls at `level` or above, after `prefix` if one is given. */\nexport function createLogger(sink: Logger, level: LogLevel, prefix: string): Logger {\n const threshold = LEVELS[level]\n const forward =\n (method: keyof Logger) =>\n (...data: unknown[]): void => {\n if (LEVELS[method] < threshold) return\n if (prefix) sink[method](prefix, ...data)\n else sink[method](...data)\n }\n return {\n debug: forward('debug'),\n info: forward('info'),\n warn: forward('warn'),\n error: forward('error'),\n }\n}\n","import type {\n AnyPlugin,\n DependencyRef,\n Empty,\n OptionsOf,\n Plugin,\n PluginDefinition,\n PluginEntry,\n Preset,\n PresetDefinition,\n PresetEntry,\n PresetPlugins,\n RequiredOptions,\n ServiceFor,\n StandardSchemaV1,\n} from './types'\nimport { mergeOptions } from './util'\n\n// Registry symbols, so plugins and presets from another copy of the package are recognized too.\nconst PLUGIN = Symbol.for('diorama.plugin')\nconst PRESET = Symbol.for('diorama.preset')\n\n/** A plugin definition with its type parameters erased, as the kernel sees it. */\nexport interface Definition {\n readonly name: string\n readonly version?: string\n readonly core?: string\n readonly dependencies?: readonly DependencyRef[]\n readonly optionalDependencies?: readonly DependencyRef[]\n readonly defaults?: object\n readonly schema?: StandardSchemaV1\n readonly critical?: boolean\n setup(app: unknown, options: unknown): unknown\n}\n\n/** Name of a dependency given as a string or as a plugin. */\nexport const refName = (ref: unknown): string | undefined => {\n if (typeof ref === 'string') return ref\n const name = (ref as { name?: unknown } | null)?.name\n return typeof name === 'string' ? name : undefined\n}\n\n/** The definition behind a plugin made by `definePlugin`, or `undefined` for anything else. */\nexport const definitionOf = (value: unknown): Definition | undefined =>\n typeof value === 'function' ? (value as { [PLUGIN]?: Definition })[PLUGIN] : undefined\n\nexport const isPreset = (value: unknown): value is Preset =>\n typeof value === 'object' && value !== null && PRESET in value\n\n/** Problems reported as PLUGIN_INVALID at start. `definePlugin` itself never throws. */\nexport function validateDefinition(def: Definition): string[] {\n const problems: string[] = []\n if (typeof def.name !== 'string' || !/^[a-z][A-Za-z0-9]*$/.test(def.name)) {\n problems.push(`name \"${String(def.name)}\" must be a lowerCamelCase identifier`)\n }\n if (typeof def.setup !== 'function') problems.push('setup must be a function')\n const dependencyLists = [def.dependencies ?? [], def.optionalDependencies ?? []]\n if (!dependencyLists.every(Array.isArray)) problems.push('dependencies must be arrays')\n else if (dependencyLists.flat().some((ref) => refName(ref) === undefined)) {\n problems.push('dependencies must be names or plugins')\n }\n if (def.core !== undefined && typeof def.core !== 'string') {\n problems.push('core must be a semver range')\n }\n if (def.defaults !== undefined && (typeof def.defaults !== 'object' || def.defaults === null)) {\n problems.push('defaults must be an object')\n }\n if (def.schema !== undefined && typeof def.schema?.['~standard']?.validate !== 'function') {\n problems.push('schema must implement Standard Schema')\n }\n return problems\n}\n\n/** A frozen plugin function carrying `options`. Calling it merges more options into a copy. */\nfunction makePlugin(def: Definition, options: Readonly<Record<string, unknown>>): AnyPlugin {\n const plugin = (next?: object): AnyPlugin => makePlugin(def, mergeOptions(options, next))\n const names = (list?: readonly DependencyRef[]) =>\n Object.freeze(Array.isArray(list) ? list.map((ref) => refName(ref) ?? '') : [])\n Object.defineProperties(plugin, {\n name: { value: def.name },\n version: { value: def.version, enumerable: true },\n options: { value: Object.freeze({ ...options }), enumerable: true },\n defaults: { value: Object.freeze({ ...def.defaults }), enumerable: true },\n schema: { value: def.schema, enumerable: true },\n dependencies: { value: names(def.dependencies), enumerable: true },\n optionalDependencies: { value: names(def.optionalDependencies), enumerable: true },\n [PLUGIN]: { value: def },\n })\n return Object.freeze(plugin) as unknown as AnyPlugin\n}\n\n/**\n * Defines a plugin. The result is a frozen function: call it with options for a configured copy.\n */\nexport function definePlugin<\n const N extends string,\n O extends object = Empty,\n DO extends Partial<OptionsOf<O, DO, SO>> = Empty,\n S = void,\n const D extends readonly DependencyRef[] = [],\n const OD extends readonly DependencyRef[] = [],\n SI = unknown,\n SO extends object = Empty,\n>(\n definition: PluginDefinition<N, O, DO, S, D, OD, SI, SO>,\n): Plugin<\n N,\n OptionsOf<O, DO, SO>,\n ServiceFor<N, S>,\n RequiredOptions<OptionsOf<O, DO, SO>, DO, SI>\n> {\n return makePlugin(definition as unknown as Definition, {}) as never\n}\n\n/** Groups plugins and other presets under one name for `createApp({ presets })`. */\nexport function definePreset<\n const E extends readonly PluginEntry[] = [],\n const PS extends readonly PresetEntry[] = [],\n>(\n definition: PresetDefinition<E, PS>,\n): Preset<Extract<E[number], AnyPlugin> | PresetPlugins<PS[number]>> {\n return Object.freeze({\n name: definition.name,\n plugins: frozenCopy(definition.plugins),\n presets: frozenCopy(definition.presets),\n [PRESET]: true,\n }) as never\n}\n\n// Non-arrays pass through untouched so createApp reports them instead of definePreset throwing.\nconst frozenCopy = <T>(list: readonly T[] | undefined): readonly T[] =>\n Array.isArray(list) ? Object.freeze([...list]) : (list ?? [])\n","/**\n * A semver subset: `^`, `~`, x-ranges, comparators and `||` groups. Unparsable input never\n * satisfies a range.\n * @module\n */\n\ntype Triple = [major: number, minor: number, patch: number]\n\ninterface Version {\n readonly triple: Triple\n /** Prerelease identifiers: `1.0.0-beta.2` has `['beta', '2']`. */\n readonly pre: readonly string[]\n}\n\ninterface Comparator {\n readonly op: '<' | '<=' | '>' | '>=' | '='\n readonly version: Version\n}\n\nconst VERSION_RE = /^v?(\\d+)\\.(\\d+)\\.(\\d+)(?:-([0-9A-Za-z.-]+))?(?:\\+[0-9A-Za-z.-]+)?$/\nconst PART = '(\\\\*|x|X|\\\\d+)'\nconst COMPARATOR_RE = new RegExp(\n `^(\\\\^|~|>=|<=|>|<|=)?v?${PART}(?:\\\\.${PART})?(?:\\\\.${PART})?(?:-([0-9A-Za-z.-]+))?(?:\\\\+[0-9A-Za-z.-]+)?$`,\n)\n\n/** Whether `version` is within a semver `range` such as `^1.2.0 || >=2`. */\nexport function satisfies(version: string, range: string): boolean {\n const parsed = parseVersion(version)\n if (!parsed) return false\n return range.split('||').some((group) => satisfiesGroup(parsed, group))\n}\n\n/** Whether `version` passes every comparator of one `||` group. */\nfunction satisfiesGroup(version: Version, group: string): boolean {\n const tokens = group\n .trim()\n .replace(/(\\^|~|>=|<=|>|<|=)\\s+/g, '$1')\n .split(/\\s+/)\n .filter(Boolean)\n const comparators: Comparator[] = []\n for (const token of tokens) {\n const expanded = parseComparator(token)\n if (!expanded) return false\n comparators.push(...expanded)\n }\n if (!comparators.every((comparator) => matches(version, comparator))) return false\n if (!version.pre.length) return true\n // A prerelease matches only a comparator with a prerelease on the same major.minor.patch.\n const plain = makeVersion(...version.triple)\n return comparators.some(\n (comparator) =>\n comparator.version.pre.length > 0 &&\n compare(makeVersion(...comparator.version.triple), plain) === 0,\n )\n}\n\nfunction parseVersion(text: string): Version | undefined {\n const match = VERSION_RE.exec(text.trim())\n if (!match) return undefined\n const triple: Triple = [Number(match[1]), Number(match[2]), Number(match[3])]\n return { triple, pre: match[4] ? match[4].split('.') : [] }\n}\n\n/** Expands one comparator (`^1.2`, `~1`, `>=2.0.0`) into plain comparisons. */\nfunction parseComparator(token: string): Comparator[] | undefined {\n const match = COMPARATOR_RE.exec(token)\n if (!match) return undefined\n const op = match[1] ?? ''\n const [majorPart, minorPart, patchPart] = [match[2], match[3], match[4]]\n const pre = match[5] ? match[5].split('.') : []\n if (isWild(majorPart)) {\n return op === '' || op === '=' || op === '>=' || op === '<=' ? [] : undefined\n }\n const major = Number(majorPart)\n const minor = isWild(minorPart) ? undefined : Number(minorPart)\n const patch = isWild(patchPart) ? undefined : Number(patchPart)\n\n if (op === '^') {\n const low = makeVersion(major, minor ?? 0, patch ?? 0, pre)\n return between(low, caretLimit(major, minor, patch))\n }\n const partial = minor === undefined || patch === undefined\n if (op === '~' || ((op === '' || op === '=') && partial)) {\n const low = makeVersion(major, minor ?? 0, patch ?? 0, pre)\n const high =\n minor === undefined ? makeVersion(major + 1, 0, 0) : makeVersion(major, minor + 1, 0)\n return between(low, high)\n }\n if (partial) {\n const next =\n minor === undefined ? makeVersion(major + 1, 0, 0) : makeVersion(major, minor + 1, 0)\n const base = makeVersion(major, minor ?? 0, 0)\n if (op === '>') return [{ op: '>=', version: next }]\n if (op === '<=') return [{ op: '<', version: next }]\n return [{ op: op as '<' | '>=', version: base }]\n }\n return [\n {\n op: op === '' ? '=' : (op as Comparator['op']),\n version: makeVersion(major, minor, patch, pre),\n },\n ]\n}\n\n/** Exclusive upper bound of `^major.minor.patch`: the next bump of the leftmost non-zero part. */\nfunction caretLimit(major: number, minor?: number, patch?: number): Version {\n if (major > 0 || minor === undefined) return makeVersion(major + 1, 0, 0)\n if (minor > 0 || patch === undefined) return makeVersion(0, minor + 1, 0)\n return makeVersion(0, 0, patch + 1)\n}\n\nconst between = (low: Version, high: Version): Comparator[] => [\n { op: '>=', version: low },\n { op: '<', version: high },\n]\n\nfunction matches(version: Version, comparator: Comparator): boolean {\n const order = compare(version, comparator.version)\n switch (comparator.op) {\n case '<':\n return order < 0\n case '<=':\n return order <= 0\n case '>':\n return order > 0\n case '>=':\n return order >= 0\n default:\n return order === 0\n }\n}\n\n/** Semver precedence: negative when `a` comes first. A release follows its prereleases. */\nfunction compare(a: Version, b: Version): number {\n for (let i = 0; i < 3; i++) {\n const difference = (a.triple[i] ?? 0) - (b.triple[i] ?? 0)\n if (difference !== 0) return difference\n }\n if (!a.pre.length || !b.pre.length) return b.pre.length - a.pre.length\n for (let i = 0; i < Math.max(a.pre.length, b.pre.length); i++) {\n const left = a.pre[i]\n const right = b.pre[i]\n if (left === undefined) return -1\n if (right === undefined) return 1\n const difference = compareIdentifiers(left, right)\n if (difference !== 0) return difference\n }\n return 0\n}\n\n/** Numeric identifiers compare as numbers and sort before alphanumeric ones. */\nfunction compareIdentifiers(a: string, b: string): number {\n const aNumeric = /^\\d+$/.test(a)\n const bNumeric = /^\\d+$/.test(b)\n if (aNumeric && bNumeric) return Number(a) - Number(b)\n if (aNumeric) return -1\n if (bNumeric) return 1\n if (a < b) return -1\n return a > b ? 1 : 0\n}\n\nconst makeVersion = (\n major: number,\n minor: number,\n patch: number,\n pre: readonly string[] = [],\n): Version => ({ triple: [major, minor, patch], pre })\n\nconst isWild = (part: string | undefined): boolean =>\n part === undefined || part === '*' || part === 'x' || part === 'X'\n","import { VERSION } from '../version'\nimport { DioramaError, messageOf } from './errors'\nimport { findCycle, topologicalSort } from './order'\nimport { type Definition, definitionOf, isPreset, refName, validateDefinition } from './plugin'\nimport type { Owner } from './scope'\nimport { satisfies } from './semver'\nimport type {\n AnyPlugin,\n AppOptions,\n DependencyRef,\n PluginStatus,\n StandardSchemaIssue,\n} from './types'\nimport { mergeOptions } from './util'\n\n/** Names a plugin may not take beyond the App API's own members. */\nexport const RESERVED = ['then', 'toJSON', 'spawn', 'query', 'tick'] as const\n\n// Layers of plugin entries. Of two entries with one name, the higher layer wins.\nconst LAYER_DEFAULTS = 0\nconst LAYER_PRESETS = 1\nconst LAYER_PLUGINS = 2\n/** Plugins installed with `use()` after start. */\nexport const LAYER_RUNTIME = 3\n\n/** Everything the kernel knows about one installed plugin. */\nexport interface PluginRecord {\n readonly name: string\n readonly def: Definition\n /** Names of the required dependencies. */\n readonly deps: readonly string[]\n /** Names of the optional dependencies. */\n readonly optional: readonly string[]\n readonly critical: boolean\n /** Options before the schema ran. `use` compares these to detect a re-install. */\n readonly raw: Record<string, unknown>\n options: Readonly<Record<string, unknown>>\n status: PluginStatus\n /** Start order. Systems and hooks of earlier plugins run first. */\n ordinal: number\n service: unknown\n hasService: boolean\n scope: Owner | undefined\n error: DioramaError | undefined\n /** Undoes the link to the owner that installed it at runtime. */\n release: (() => void) | undefined\n}\n\n/** A plugin as listed in the options, before names are resolved. */\nexport interface Entry {\n readonly plugin: AnyPlugin\n readonly def: Definition\n readonly layer: number\n /** Position in the flattened list, for a stable merge order. */\n readonly index: number\n}\n\nexport interface Resolved {\n /** One record per plugin name. */\n readonly list: PluginRecord[]\n readonly failures: Map<PluginRecord, DioramaError>\n}\n\nexport interface Config {\n readonly options: AppOptions\n /** The built-in plugins, before `defaults: false` and `disable` apply. */\n readonly defaults: readonly AnyPlugin[]\n readonly disabled: ReadonlySet<string>\n readonly reserved: (name: string) => boolean\n}\n\n/** An optional dependency: `to` depends on `from`. Dropped first to break a cycle. */\ninterface OptionalEdge {\n readonly from: number\n readonly to: number\n /** Index in the dependent's `optionalDependencies`. */\n readonly position: number\n}\n\n/** Flattens layers (defaults < presets < plugins) and applies `disable`. */\nexport function collectEntries(config: Config, problems: DioramaError[]): Entry[] {\n const entries: Entry[] = []\n const push = (value: unknown, layer: number): void => {\n if (!value) return\n const def = definitionOf(value)\n if (def) entries.push({ plugin: value as AnyPlugin, def, layer, index: entries.length })\n else problems.push(new DioramaError('PLUGIN_INVALID', `not a plugin: ${String(value)}`))\n }\n const walkPreset = (value: unknown, seen: Set<unknown>): void => {\n if (!value || seen.has(value)) return\n if (!isPreset(value)) {\n problems.push(new DioramaError('PLUGIN_INVALID', `not a preset: ${String(value)}`))\n return\n }\n seen.add(value)\n if (!Array.isArray(value.presets) || !Array.isArray(value.plugins)) {\n problems.push(new DioramaError('PLUGIN_INVALID', `preset \"${value.name}\" needs arrays`))\n return\n }\n for (const nested of value.presets) walkPreset(nested, seen)\n for (const plugin of value.plugins) push(plugin, LAYER_PRESETS)\n }\n const listOption = (key: 'presets' | 'plugins'): readonly unknown[] => {\n const value = config.options[key]\n if (value === undefined || Array.isArray(value)) return value ?? []\n problems.push(new DioramaError('CONFIG_INVALID', `${key} must be an array`))\n return []\n }\n if (config.options.defaults !== false) {\n for (const plugin of config.defaults) push(plugin, LAYER_DEFAULTS)\n }\n for (const preset of listOption('presets')) walkPreset(preset, new Set())\n for (const plugin of listOption('plugins')) push(plugin, LAYER_PLUGINS)\n // `disable` drops built-ins and preset plugins, never a plugin listed in `plugins`.\n return entries.filter(\n (entry) => entry.layer === LAYER_PLUGINS || !config.disabled.has(String(entry.def.name)),\n )\n}\n\n/** Why a missing plugin is missing, as a suffix for messages. */\nexport function missingHint(config: Config, name: string): string {\n if (config.disabled.has(name)) return ' (removed via disable)'\n if (config.options.defaults === false && config.defaults.some((p) => p.name === name)) {\n return ' (defaults are off)'\n }\n return ''\n}\n\n/** Resolves names (the strongest layer wins) and validates. Returns per-plugin failures. */\nexport async function resolveEntries(\n config: Config,\n entries: readonly Entry[],\n available?: (name: string) => boolean,\n): Promise<Resolved> {\n const groups = new Map<string, Entry[]>()\n for (const entry of entries) {\n const name = String(entry.def.name)\n groups.set(name, [...(groups.get(name) ?? []), entry])\n }\n const list: PluginRecord[] = []\n const failures = new Map<PluginRecord, DioramaError>()\n for (const [name, group] of groups) {\n const topLayer = Math.max(...group.map((entry) => entry.layer))\n const winner = group.find((entry) => entry.layer === topLayer) as Entry\n const record = createRecord(winner.def, mergeGroupOptions(group, winner))\n list.push(record)\n if (group.some((entry) => entry.layer === topLayer && entry.def !== winner.def)) {\n failures.set(\n record,\n new DioramaError('PLUGIN_DUPLICATE', `two different plugins named \"${name}\"`, {\n plugin: name,\n }),\n )\n }\n }\n for (const record of list) {\n const problem = failures.get(record) ?? (await validate(record, config.reserved))\n if (problem) failures.set(record, problem)\n }\n const present = new Set(list.map((record) => record.name))\n for (const record of list) {\n const missing = record.deps.find((name) => !present.has(name) && !available?.(name))\n if (missing === undefined || failures.has(record)) continue\n failures.set(\n record,\n new DioramaError(\n 'PLUGIN_MISSING_DEPENDENCY',\n `requires \"${missing}\"${missingHint(config, missing)}`,\n { plugin: record.name },\n ),\n )\n }\n return { list, failures }\n}\n\n/**\n * Start order by list position, or a cycle of required dependencies. Optional edges inside a\n * stuck set are dropped one at a time, starting with the dependent placed latest.\n */\nexport function orderPlugins(\n list: readonly PluginRecord[],\n): PluginRecord[] | { cycle: PluginRecord[] } {\n const recordAt = (i: number): PluginRecord => list[i] as PluginRecord\n const indexByName = new Map(list.map((record, i) => [record.name, i]))\n const required: number[][] = list.map(() => [])\n const optional: OptionalEdge[] = []\n list.forEach((record, to) => {\n for (const name of record.deps) {\n const from = indexByName.get(name)\n if (from !== undefined) required[from]?.push(to)\n }\n record.optional.forEach((name, position) => {\n const from = indexByName.get(name)\n if (from !== undefined) optional.push({ from, to, position })\n })\n })\n const requiredOnly = topologicalSort(list.length, required, byIndex)\n if (!Array.isArray(requiredOnly)) {\n return { cycle: findCycle(required, requiredOnly.stuck).map(recordAt) }\n }\n for (;;) {\n const edges = required.map((targets) => [...targets])\n for (const edge of optional) edges[edge.from]?.push(edge.to)\n const result = topologicalSort(list.length, edges, byIndex)\n if (Array.isArray(result)) return result.map(recordAt)\n const drop = edgeToDrop(optional, edges, new Set(result.stuck))\n // Not reached: required edges alone sort, so every stuck set closes through an optional one.\n if (!drop) return { cycle: result.stuck.map(recordAt) }\n optional.splice(optional.indexOf(drop), 1)\n }\n}\n\nexport const cycleError = (cycle: readonly PluginRecord[]): DioramaError =>\n new DioramaError(\n 'PLUGIN_CYCLE',\n `required dependencies form a cycle: ${cycle.map((record) => record.name).join(' → ')}`,\n )\n\n/** Entries sharing the winner's definition merge their options by layer, then position. */\nfunction mergeGroupOptions(group: readonly Entry[], winner: Entry): Record<string, unknown> {\n const same = group\n .filter((entry) => entry.def === winner.def)\n .sort((a, b) => a.layer - b.layer || a.index - b.index)\n let options: Record<string, unknown> = { ...winner.def.defaults }\n for (const entry of same) options = mergeOptions(options, entry.plugin.options)\n return options\n}\n\n/** Validates the definition, core range and options, then freezes the final options. */\nasync function validate(\n record: PluginRecord,\n reserved: (name: string) => boolean,\n): Promise<DioramaError | undefined> {\n const plugin = record.name\n const problems = validateDefinition(record.def)\n if (!problems.length && reserved(record.name)) {\n problems.push(`name \"${record.name}\" is reserved by the App API`)\n }\n if (problems.length) return new DioramaError('PLUGIN_INVALID', problems.join('; '), { plugin })\n const { core, schema } = record.def\n if (core !== undefined && !satisfies(VERSION, core)) {\n return new DioramaError('PLUGIN_INCOMPATIBLE', `requires core ${core}, running ${VERSION}`, {\n plugin,\n })\n }\n let value: unknown = record.raw\n if (schema) {\n try {\n const result = await schema['~standard'].validate(record.raw)\n if (result.issues) {\n return new DioramaError('PLUGIN_OPTIONS', describeIssues(result.issues), { plugin })\n }\n value = result.value\n } catch (error) {\n return new DioramaError('PLUGIN_OPTIONS', messageOf(error), { plugin, cause: error })\n }\n }\n record.options = Object.freeze({ ...(value as object) })\n return undefined\n}\n\n/** Schema issues as `path: message` parts joined by `; `. */\nfunction describeIssues(issues: readonly StandardSchemaIssue[]): string {\n const parts = issues.map((issue) => {\n const path = issue.path\n ?.map((segment) => String(typeof segment === 'object' ? segment.key : segment))\n .join('.')\n return path ? `${path}: ${issue.message}` : issue.message\n })\n return parts.join('; ')\n}\n\nfunction createRecord(def: Definition, raw: Record<string, unknown>): PluginRecord {\n // A non-array list is left to `validate`, which reports it as PLUGIN_INVALID.\n const names = (list?: readonly DependencyRef[]): string[] =>\n Array.isArray(list) ? list.map((ref) => refName(ref) ?? '') : []\n return {\n name: String(def.name),\n def,\n deps: names(def.dependencies),\n optional: names(def.optionalDependencies),\n critical: def.critical === true,\n raw,\n options: raw,\n status: 'pending',\n ordinal: -1,\n service: undefined,\n hasService: false,\n scope: undefined,\n error: undefined,\n release: undefined,\n }\n}\n\n/** Ties between ready plugins go to the one listed first. */\nconst byIndex = (a: number, b: number): boolean => a < b\n\n/** The optional edge on a cycle whose dependent is placed latest (then its latest entry). */\nfunction edgeToDrop(\n optional: readonly OptionalEdge[],\n edges: readonly (readonly number[])[],\n stuck: ReadonlySet<number>,\n): OptionalEdge | undefined {\n // An edge lies on a cycle only if its target can reach its source again.\n const reaches = (from: number, to: number): boolean => {\n const seen = new Set<number>()\n const walk = (node: number): boolean => {\n if (node === to) return true\n if (seen.has(node)) return false\n seen.add(node)\n return (edges[node] ?? []).some((next) => stuck.has(next) && walk(next))\n }\n return walk(from)\n }\n let drop: OptionalEdge | undefined\n for (const edge of optional) {\n if (!stuck.has(edge.from) || !stuck.has(edge.to)) continue\n const notLater =\n drop && (edge.to < drop.to || (edge.to === drop.to && edge.position <= drop.position))\n if (notLater) continue\n if (reaches(edge.to, edge.from)) drop = edge\n }\n return drop\n}\n","import { DioramaError } from './errors'\nimport type { Owner, Report } from './scope'\nimport type { Off } from './types'\nimport { isThenable, noop } from './util'\n\n/** Nesting counter shared by events and hooks. */\nexport interface Depth {\n value: number\n}\n\n/** Emits and hook calls nested deeper than this are reported as RECURSION and skipped. */\nexport const MAX_DEPTH = 64\n\ninterface Listener {\n readonly fn: (payload: unknown) => unknown\n readonly owner: Owner\n readonly once: boolean\n active: boolean\n off: Off\n}\n\n/** Event listeners by name. Errors in listeners are reported and never reach the emitter. */\nexport class EventBus {\n // Lists are copied on write, so a running emit keeps iterating its own snapshot.\n readonly #channels = new Map<string, Listener[]>()\n readonly #report: Report\n readonly #depth: Depth\n\n constructor(report: Report, depth: Depth) {\n this.#report = report\n this.#depth = depth\n }\n\n on(name: string, fn: (payload: unknown) => unknown, owner: Owner, once: boolean): Off {\n if (!owner.open()) return noop\n const listener: Listener = { fn, owner, once, active: true, off: noop }\n this.#channels.set(name, [...(this.#channels.get(name) ?? []), listener])\n listener.off = owner.add(() => {\n if (!listener.active) return\n listener.active = false\n const rest = (this.#channels.get(name) ?? []).filter((other) => other !== listener)\n if (rest.length) this.#channels.set(name, rest)\n else this.#channels.delete(name)\n })\n return listener.off\n }\n\n emit(name: string, payload: unknown): void {\n const list = this.#channels.get(name)\n if (!list) return\n if (this.#depth.value >= MAX_DEPTH) {\n this.#report(\n new DioramaError('RECURSION', `\"${name}\" nested too deep`),\n 'listener',\n undefined,\n name,\n )\n return\n }\n this.#depth.value++\n try {\n for (const listener of list) {\n // `active` skips listeners removed earlier in this same delivery.\n if (!listener.active || listener.owner.disposed) continue\n if (listener.once) listener.off()\n try {\n const result = listener.fn(payload)\n if (isThenable(result)) {\n result.then(undefined, (error) => this.#report(error, 'listener', listener.owner, name))\n }\n } catch (error) {\n this.#report(error, 'listener', listener.owner, name)\n }\n }\n } finally {\n this.#depth.value--\n }\n }\n}\n","import { DioramaError } from './errors'\nimport { type Depth, MAX_DEPTH } from './events'\nimport { type Orderable, orderRefs, sortOrderables } from './order'\nimport type { Owner, Report } from './scope'\nimport type { Cancel, Off, OrderOptions } from './types'\nimport { isThenable, noop } from './util'\n\nconst CANCEL: Cancel = Object.freeze({ '~cancel': true, reason: undefined })\n\n/** Returned from a hook handler to stop the chain. `callHook` then returns it. */\nexport function cancel(reason?: string): Cancel {\n return reason === undefined ? CANCEL : Object.freeze({ '~cancel': true, reason })\n}\n\n/** Whether a hook result is a `cancel()`. */\nexport function isCancel(value: unknown): value is Cancel {\n return (\n typeof value === 'object' && value !== null && (value as Partial<Cancel>)['~cancel'] === true\n )\n}\n\n/** Labels of an ordered entry: `before`/`after` can target its own name or its plugin. */\nexport function labelsOf(owner: Owner, name: string | undefined): string[] {\n const own = name ?? owner.label\n return owner.plugin && owner.plugin !== own ? [own, owner.plugin] : [own]\n}\n\ninterface Handler extends Orderable {\n readonly fn: (value: unknown, context: unknown) => unknown\n readonly owner: Owner\n active: boolean\n}\n\n/** Hook handlers by name, sorted by their order options. */\nexport class HookBus {\n readonly #chains = new Map<string, Handler[]>()\n /** Bumped whenever a chain changes, so callers can cache hook results. */\n readonly #versions = new Map<string, number>()\n #nextSeq = 0\n readonly #report: Report\n readonly #depth: Depth\n\n constructor(report: Report, depth: Depth) {\n this.#report = report\n this.#depth = depth\n }\n\n add(name: string, fn: Handler['fn'], owner: Owner, options?: OrderOptions): Off {\n if (!owner.open()) return noop\n const handler: Handler = {\n fn,\n owner,\n active: true,\n labels: labelsOf(owner, options?.name),\n before: orderRefs(options?.before),\n after: orderRefs(options?.after),\n rank: owner.rank,\n seq: this.#nextSeq++,\n }\n const sorted = sortOrderables([...(this.#chains.get(name) ?? []), handler])\n if (!Array.isArray(sorted)) {\n const path = sorted.cycle.map((entry) => entry.labels[0]).join(' → ')\n throw new DioramaError('ORDER_CYCLE', `hook \"${name}\": ${path}`, { plugin: owner.plugin })\n }\n this.#setChain(name, sorted)\n return owner.add(() => {\n if (!handler.active) return\n handler.active = false\n const rest = (this.#chains.get(name) ?? []).filter((other) => other !== handler)\n this.#setChain(name, rest)\n })\n }\n\n /**\n * Runs a sync chain. Each handler gets the value the previous one returned. A `cancel()`\n * stops the chain and is returned as the result. An async handler is reported and ignored.\n */\n call(name: string, value: unknown, context: unknown): unknown {\n const chain = this.#chains.get(name)\n if (!chain) return value\n if (this.#depth.value >= MAX_DEPTH) {\n this.#report(\n new DioramaError('RECURSION', `hook \"${name}\" nested too deep`),\n 'hook',\n undefined,\n name,\n )\n return value\n }\n this.#depth.value++\n try {\n for (const handler of chain) {\n if (!handler.active || handler.owner.disposed) continue\n let result: unknown\n try {\n result = handler.fn(value, context)\n } catch (error) {\n this.#report(error, 'hook', handler.owner, name)\n continue\n }\n if (result === undefined) continue\n if (isThenable(result)) {\n result.then(undefined, noop)\n const error = new Error(`async handler in sync hook \"${name}\"`)\n this.#report(error, 'hook', handler.owner, name)\n } else if (isCancel(result)) {\n return result\n } else {\n value = result\n }\n }\n return value\n } finally {\n this.#depth.value--\n }\n }\n\n /** Runs a chain like `call`, awaiting each handler in turn. */\n async callAsync(name: string, value: unknown, context: unknown): Promise<unknown> {\n for (const handler of this.#chains.get(name) ?? []) {\n if (!handler.active || handler.owner.disposed) continue\n let result: unknown\n try {\n result = await handler.fn(value, context)\n } catch (error) {\n this.#report(error, 'hook', handler.owner, name)\n continue\n }\n // An owner disposed while we awaited must not affect the value.\n if (result === undefined || handler.owner.disposed) continue\n if (isCancel(result)) return result\n value = result\n }\n return value\n }\n\n version(name: string): number {\n return this.#versions.get(name) ?? 0\n }\n\n #setChain(name: string, chain: Handler[]): void {\n if (chain.length) this.#chains.set(name, chain)\n else this.#chains.delete(name)\n this.#versions.set(name, this.version(name) + 1)\n }\n}\n","import type {\n DriverLink,\n FrameDriver,\n FrameTick,\n ManualDriver,\n ManualDriverOptions,\n Off,\n OfflineDriver,\n OfflineDriverOptions,\n TickerDriverOptions,\n} from './types'\nimport { noop, perfNow } from './util'\n\n/** One loop's connection. A driver can serve several apps, each through its own link. */\ninterface Link extends DriverLink {\n requested: boolean\n readonly tick: FrameTick\n}\n\n/** The links of one driver and their frame requests. */\ninterface Links {\n readonly all: ReadonlySet<Link>\n attach(tick: FrameTick): DriverLink\n anyRequested(): boolean\n /** Ticks every requested link once. True if any drew a frame. */\n tickRequested(now: number): boolean\n}\n\n/** `onRequest` fires on every request, `onIdle` when none remain. */\nfunction createLinks(onRequest: () => void, onIdle: () => void): Links {\n const all = new Set<Link>()\n const anyRequested = (): boolean => {\n for (const link of all) if (link.requested) return true\n return false\n }\n const attach = (tick: FrameTick): DriverLink => {\n const link: Link = {\n tick,\n requested: false,\n request() {\n if (!all.has(link)) return\n link.requested = true\n onRequest()\n },\n cancel() {\n link.requested = false\n if (!anyRequested()) onIdle()\n },\n detach() {\n all.delete(link)\n link.cancel()\n },\n }\n all.add(link)\n return link\n }\n const tickRequested = (now: number): boolean => {\n let ticked = false\n for (const link of all) {\n if (!link.requested) continue\n link.requested = false\n if (link.tick(now)) ticked = true\n }\n return ticked\n }\n return { all, attach, anyRequested, tickRequested }\n}\n\n/** Frames on `requestAnimationFrame`. The default driver in the browser. */\nexport function rafDriver(): FrameDriver {\n let handle: number | undefined\n const frame = (now: number): void => {\n handle = undefined\n links.tickRequested(now)\n }\n const links = createLinks(\n () => {\n if (handle === undefined && typeof requestAnimationFrame === 'function') {\n handle = requestAnimationFrame(frame)\n }\n },\n () => {\n if (handle !== undefined && typeof cancelAnimationFrame === 'function') {\n cancelAnimationFrame(handle)\n handle = undefined\n }\n },\n )\n return { name: 'raf', now: perfNow, attach: links.attach }\n}\n\n/** A driver that frames only on `tick()` or `flush()`, for tests. */\nexport function manualDriver(options: ManualDriverOptions = {}): ManualDriver {\n let time = options.start ?? 0\n const step = options.step ?? 1 / 60\n const links = createLinks(noop, noop)\n const driver: ManualDriver = {\n name: 'manual',\n now: () => time,\n attach: links.attach,\n get pending() {\n return links.anyRequested()\n },\n tick(seconds = step) {\n time += seconds * 1000\n return links.tickRequested(time)\n },\n advance(seconds) {\n time += seconds * 1000\n },\n flush(limit = 1000) {\n let frames = 0\n for (let i = 0; i < limit && links.anyRequested(); i++) {\n if (driver.tick()) frames++\n }\n return frames\n },\n }\n return driver\n}\n\n/** A fixed-step driver that frames on `step()`, for video capture. */\nexport function offlineDriver(options: OfflineDriverOptions): OfflineDriver {\n const start = options.start ?? 0\n const fps = options.fps\n let frame = 0\n const links = createLinks(noop, noop)\n return {\n name: 'offline',\n fps,\n get frame() {\n return frame\n },\n now: () => start + (frame * 1000) / fps,\n attach: links.attach,\n // Ticks every link, requested or not: a capture frame is forced.\n step(count = 1) {\n for (let i = 0; i < count; i++) {\n frame++\n const now = start + (frame * 1000) / fps\n for (const link of links.all) link.tick(now, 1 / fps)\n }\n },\n }\n}\n\n/** A driver on an external ticker, such as `gsap.ticker`. `subscribe` returns its own Off. */\nexport function tickerDriver(\n subscribe: (tick: (now?: number) => void) => Off,\n options: TickerDriverOptions = {},\n): FrameDriver {\n const now = options.now ?? perfNow\n let unsubscribe: Off | undefined\n const stop = (): void => {\n unsubscribe?.()\n unsubscribe = undefined\n }\n const onTick = (time?: number): void => {\n links.tickRequested(time ?? now())\n if (!links.anyRequested()) stop()\n }\n let subscribing = false\n const links = createLinks(() => {\n // A ticker may tick synchronously inside subscribe. Don't subscribe twice from there.\n if (unsubscribe || subscribing) return\n subscribing = true\n try {\n unsubscribe = subscribe(onTick)\n } finally {\n subscribing = false\n }\n if (!links.anyRequested()) stop()\n }, stop)\n return { name: options.name ?? 'ticker', now, attach: links.attach }\n}\n","import { rafDriver } from './drivers'\nimport { DioramaError } from './errors'\nimport { labelsOf } from './hooks'\nimport { type Orderable, orderRefs, sortOrderables } from './order'\nimport type { Owner, Report } from './scope'\nimport type {\n DriverLink,\n FrameDriver,\n FrameMode,\n FrameProfiler,\n FrameReason,\n FrameStats,\n FrameTime,\n Loop,\n LoopOptions,\n LoopSettings,\n Off,\n OrderOptions,\n StageName,\n StagePosition,\n System,\n SystemHandle,\n SystemInfo,\n} from './types'\nimport { isThenable, noop } from './util'\n\nconst DEFAULT_STAGES = ['input', 'layout', 'update', 'render', 'afterRender']\n/** A system that throws this many frames in a row is disabled. */\nconst MAX_FAILURES = 10\n/** Assumed frame interval, seconds, until frames measure the display. */\nconst DEFAULT_INTERVAL = 1 / 60\n/** A gap of this many frame intervals or more is a pause, not a frame. */\nconst GAP_FRAMES = 3\n/** How far each frame moves the measured interval toward the latest one. */\nconst INTERVAL_EASING = 0.1\n// The measured frame rate stays within these bounds.\nconst MAX_MEASURED_FPS = 240\nconst MIN_MEASURED_FPS = 30\n/** `maxFps` lets a frame through this many ms early, so a 60 fps cap keeps every 60 Hz frame. */\nconst FPS_SLACK_MS = 1\n\ninterface SystemRecord extends Orderable, SystemInfo {\n readonly run: System\n readonly scope: Owner\n active: boolean\n /** Its stage is gone. Kept for re-adoption, skipped by frames. */\n parked: boolean\n enabled: boolean\n /** Failures in a row. */\n failures: number\n error: unknown\n}\n\ninterface Stage {\n readonly name: string\n /** Anchor of an `after` placement: later stages with the same anchor go behind it. */\n readonly afterOf: string | undefined\n systems: SystemRecord[]\n}\n\n/** Settings or a driver set by `overrideLoop` or `setDriver`. */\ninterface Override {\n readonly settings?: LoopSettings\n readonly driver?: FrameDriver\n}\n\n/**\n * The frame loop. In `demand` mode it sleeps until something asks for a frame, so an idle page\n * holds no timers or frame requests. Frames run the systems of every stage in order.\n */\nexport class LoopImpl implements Loop {\n readonly time: FrameTime\n readonly stats: FrameStats\n // Writable backing objects of `time` and `stats`, updated in place every frame.\n readonly #time = { delta: 0, rawDelta: 0, elapsed: 0, now: 0, frame: 0, resumed: true }\n readonly #stats = {\n frames: 0,\n wakes: 0,\n reason: 'none' as FrameReason | 'none',\n invalidatedBy: '',\n interval: DEFAULT_INTERVAL,\n }\n readonly #baseSettings: Required<LoopSettings>\n readonly #baseDriver: FrameDriver\n readonly #overrides: Override[] = []\n readonly #stages: Stage[] = DEFAULT_STAGES.map((name) => ({\n name,\n afterOf: undefined,\n systems: [],\n }))\n /** Systems whose stage does not exist (yet). */\n readonly #parked: SystemRecord[] = []\n readonly #warnedStages = new Set<string>()\n readonly #holds = new Set<object>()\n readonly #pauses = new Set<object>()\n // Copy-on-write and captured per frame, so changes mid-frame apply from the next one.\n #profilers: FrameProfiler[] = []\n #frameProfilers: FrameProfiler[] = []\n /** Systems of all stages in run order, rebuilt when `#runOrderStale`. */\n #runOrder: SystemRecord[] = []\n #runOrderStale = true\n #link: DriverLink | undefined\n #attached = false\n #requested = false\n #inFrame = false\n /** Something called `invalidate` since the last frame. */\n #invalidated = false\n /** The previous frame asked for the next one. */\n #continuous = false\n /** Forces a wake frame next, after a driver switch or a pause. */\n #forceWake = true\n /** Driver time until which `keepAwake` keeps frames coming. */\n #awakeUntil = 0\n /** Driver time of the last frame. */\n #lastNow: number | undefined\n /** Measured display frame interval, seconds. */\n #interval = DEFAULT_INTERVAL\n #nextSeq = 0\n readonly #report: Report\n\n constructor(options: LoopOptions | undefined, report: Report, warn: (message: string) => void) {\n this.#report = report\n this.time = this.#time\n this.stats = this.#stats\n this.#baseSettings = {\n mode: 'demand',\n maxDelta: 0.1,\n maxFps: 0,\n timeScale: 1,\n ...validSettings(options ?? {}, warn),\n }\n this.#baseDriver = options?.driver ?? rafDriver()\n }\n\n // The newest override that sets a field wins.\n #setting<K extends keyof LoopSettings>(key: K): Required<LoopSettings>[K] {\n for (let i = this.#overrides.length; i--; ) {\n const value = this.#overrides[i]?.settings?.[key]\n if (value !== undefined) return value as Required<LoopSettings>[K]\n }\n return this.#baseSettings[key]\n }\n\n get mode(): FrameMode {\n return this.#setting('mode')\n }\n get maxDelta(): number {\n return this.#setting('maxDelta')\n }\n get maxFps(): number {\n return this.#setting('maxFps')\n }\n get timeScale(): number {\n return this.#setting('timeScale')\n }\n get driver(): FrameDriver {\n for (let i = this.#overrides.length; i--; ) {\n const driver = this.#overrides[i]?.driver\n if (driver) return driver\n }\n return this.#baseDriver\n }\n get awake(): boolean {\n return this.#requested || this.#inFrame\n }\n get paused(): boolean {\n return this.#pauses.size > 0\n }\n\n overrideLoop(owner: Owner, settings: LoopSettings): Off {\n return this.#override(owner, { settings: validSettings(settings, (m) => owner.log.warn(m)) })\n }\n\n setDriver(owner: Owner, driver: FrameDriver): Off {\n return this.#override(owner, { driver })\n }\n\n #override(owner: Owner, override: Override): Off {\n if (!owner.open()) return noop\n const apply = (change: () => void): void => {\n const driver = this.driver\n const remaining = this.#awakeUntil - driver.now()\n change()\n if (this.driver !== driver) {\n // Drivers have different clocks, so carry over the remaining keepAwake time.\n this.#awakeUntil = remaining > 0 ? this.driver.now() + remaining : 0\n if (this.#attached) {\n this.#unlink()\n this.#relink()\n }\n }\n this.#schedule()\n }\n apply(() => this.#overrides.push(override))\n return owner.add(() => apply(() => removeItem(this.#overrides, override)))\n }\n\n profile(owner: Owner, profiler: FrameProfiler): Off {\n if (!owner.open()) return noop\n this.#profilers = [...this.#profilers, profiler]\n return owner.add(() => {\n this.#profilers = this.#profilers.filter((other) => other !== profiler)\n })\n }\n\n addStage(name: string, position: StagePosition, owner: Owner): Off {\n if (!owner.open()) return noop\n const plugin = owner.plugin\n if (this.#stages.some((stage) => stage.name === name)) {\n throw new DioramaError('STAGE_DUPLICATE', `stage \"${name}\" exists`, { plugin })\n }\n const anchor = position.before ?? position.after\n let index = this.#stages.findIndex((stage) => stage.name === anchor)\n if (index < 0) throw new DioramaError('STAGE_UNKNOWN', `no stage \"${anchor}\"`, { plugin })\n if (position.after !== undefined) {\n // Go past the anchor and the stages placed after it earlier.\n index++\n while (this.#stages[index]?.afterOf === anchor) index++\n }\n // Parked systems were cycle-checked when parked, so this sort always succeeds.\n const parked = this.#parked.filter((record) => record.stage === name)\n const stage: Stage = {\n name,\n afterOf: position.after,\n systems: sortOrderables(parked) as SystemRecord[],\n }\n for (const record of stage.systems) {\n removeItem(this.#parked, record)\n record.parked = false\n }\n this.#stages.splice(index, 0, stage)\n this.#runOrderStale = true\n return owner.add(() => {\n if (!removeItem(this.#stages, stage)) return\n for (const record of stage.systems) record.parked = true\n this.#parked.push(...stage.systems)\n this.#runOrderStale = true\n })\n }\n\n system(\n stage: string,\n run: System,\n options: OrderOptions | undefined,\n owner: Owner,\n ): SystemHandle {\n const record: SystemRecord = {\n name: options?.name ?? owner.label,\n stage: stage as StageName,\n owner: owner.label,\n scope: owner,\n run,\n labels: labelsOf(owner, options?.name),\n before: orderRefs(options?.before),\n after: orderRefs(options?.after),\n rank: owner.rank,\n seq: this.#nextSeq++,\n active: false,\n parked: false,\n enabled: true,\n failures: 0,\n error: undefined,\n }\n let off: Off = noop\n const handle = systemHandle(record, () => off())\n if (!owner.open()) return handle\n\n const target = this.#stages.find((s) => s.name === stage)\n const peers = target ? target.systems : this.#parked.filter((other) => other.stage === stage)\n const sorted = sortOrderables([...peers, record])\n if (!Array.isArray(sorted)) {\n const path = sorted.cycle.map((other) => other.name).join(' → ')\n throw new DioramaError('ORDER_CYCLE', `stage \"${stage}\": ${path}`, { plugin: owner.plugin })\n }\n if (target) target.systems = sorted\n else {\n // Systems may arrive before the plugin that adds their stage.\n record.parked = true\n this.#parked.push(record)\n if (!this.#warnedStages.has(stage)) {\n this.#warnedStages.add(stage)\n owner.log.warn(`stage \"${stage}\" does not exist yet; system parked`)\n }\n }\n record.active = true\n this.#runOrderStale = true\n off = owner.add(() => {\n record.active = false\n for (const s of this.#stages) s.systems = s.systems.filter((other) => other !== record)\n removeItem(this.#parked, record)\n this.#runOrderStale = true\n })\n return handle\n }\n\n invalidate(owner: Owner): void {\n this.#invalidated = true\n this.#stats.invalidatedBy = owner.label\n this.#schedule()\n }\n\n keepAwake(owner: Owner, seconds: number): void {\n if (seconds > 0) {\n this.#awakeUntil = Math.max(this.#awakeUntil, this.driver.now() + seconds * 1000)\n }\n this.invalidate(owner)\n }\n\n hold(owner: Owner): Off {\n if (!owner.open()) return noop\n const token = {}\n this.#holds.add(token)\n this.#schedule()\n // Releasing a hold draws one closing frame with the final state.\n return owner.add(() => this.#holds.delete(token) && this.invalidate(owner))\n }\n\n pause(owner: Owner): Off {\n if (!owner.open()) return noop\n const token = {}\n this.#pauses.add(token)\n if (this.#requested) {\n this.#link?.cancel()\n this.#requested = false\n }\n return owner.add(() => {\n if (this.#pauses.delete(token) && !this.#pauses.size) {\n this.#forceWake = true\n this.#schedule()\n }\n })\n }\n\n attach(): void {\n this.#attached = true\n this.#relink()\n this.#invalidated = true\n this.#schedule()\n }\n\n stop(): void {\n this.#attached = false\n this.#unlink()\n }\n\n /** Whether anything wants a frame now. */\n #wanted(): boolean {\n return (\n this.#invalidated ||\n this.#holds.size > 0 ||\n this.mode === 'always' ||\n (this.#awakeUntil > 0 && this.driver.now() < this.#awakeUntil)\n )\n }\n\n /** Requests at most one frame. An idle loop holds no timers or requests. */\n #schedule(): void {\n if (!this.#attached || this.#pauses.size || this.#requested || this.#inFrame) return\n if (this.#wanted()) this.#requestFrame()\n }\n\n #requestFrame(): void {\n this.#requested = true\n this.#link?.request()\n }\n\n #relink(): void {\n this.#link = this.driver.attach((now, step) => this.#tick(now, step))\n this.#forceWake = true\n this.#lastNow = undefined\n this.#requested = false\n }\n\n #unlink(): void {\n this.#link?.cancel()\n this.#link?.detach()\n this.#link = undefined\n this.#requested = false\n }\n\n /** Driver callback. A forced `step` (offline capture) bypasses pauses and demand checks. */\n #tick(now: number, step?: number): boolean {\n if (this.#inFrame || !this.#attached) return false\n // A non-finite timestamp counts as no time passed, so a broken clock can't poison time.\n if (!Number.isFinite(now)) now = this.#lastNow ?? 0\n this.#requested = false\n if (step === undefined) {\n if (this.#pauses.size || !this.#wanted()) {\n this.#continuous = false\n return false\n }\n // `maxFps` throttles event-driven frames too. A clock going backwards never throttles.\n const fps = this.maxFps\n const since = this.#lastNow === undefined ? Number.POSITIVE_INFINITY : now - this.#lastNow\n if (fps > 0 && !this.#forceWake && since >= 0 && since < 1000 / fps - FPS_SLACK_MS) {\n this.#requestFrame()\n return false\n }\n }\n this.#runFrame(now, step)\n return true\n }\n\n #runFrame(now: number, step: number | undefined): void {\n this.#stats.reason = this.#reason(step)\n this.#advanceTime(now, step)\n this.#invalidated = false\n\n if (this.#runOrderStale) {\n this.#runOrder.length = 0\n for (const stage of this.#stages) this.#runOrder.push(...stage.systems)\n this.#runOrderStale = false\n }\n this.#runSystems()\n\n this.#continuous = this.#attached && !this.#pauses.size && this.#wanted()\n if (this.#continuous) this.#requestFrame()\n }\n\n #advanceTime(now: number, step: number | undefined): void {\n const time = this.#time\n const stats = this.#stats\n const interval = this.#interval\n const rawDelta =\n this.#lastNow === undefined ? interval : Math.max(0, (now - this.#lastNow) / 1000)\n // A frame continues the previous one if that one requested it, or if it follows closely\n // (event-driven invalidation). Anything else is a wake frame after idle, a pause or a\n // driver switch.\n const wake =\n this.#forceWake ||\n this.#lastNow === undefined ||\n (!this.#continuous && rawDelta >= GAP_FRAMES * interval)\n this.#forceWake = false\n // Continuing frames clamp to maxDelta and track the display interval. A wake frame gets at\n // most one frame interval.\n time.delta = (step ?? Math.min(rawDelta, wake ? interval : this.maxDelta)) * this.timeScale\n if (step === undefined && !wake) this.#interval = measureInterval(interval, rawDelta)\n time.rawDelta = rawDelta\n time.elapsed += time.delta\n time.now = now\n time.frame++\n time.resumed = wake && step === undefined\n this.#lastNow = now\n stats.frames++\n if (time.resumed) stats.wakes++\n stats.interval = this.#interval\n }\n\n #runSystems(): void {\n this.#frameProfilers = this.#profilers\n this.#inFrame = true\n try {\n this.#profiled('frameStart', this.#time)\n // Removals during a frame apply at once through `active`, additions wait a frame.\n for (const record of this.#runOrder) {\n if (!this.#attached) break\n if (record.active && !record.parked && record.enabled && record.scope.ready) {\n this.#runSystem(record)\n }\n }\n this.#profiled('frameEnd', this.#time)\n } finally {\n this.#inFrame = false\n }\n }\n\n #reason(step: number | undefined): FrameReason {\n if (step !== undefined) return 'step'\n if (this.#invalidated) return 'invalidate'\n if (this.#holds.size) return 'hold'\n return this.mode === 'always' ? 'always' : 'timed'\n }\n\n #runSystem(record: SystemRecord): void {\n this.#profiled('systemStart', record)\n try {\n const result: unknown = record.run(this.#time)\n if (isThenable(result)) {\n result.then(undefined, noop)\n throw new Error(`system \"${record.name}\" returned a promise`)\n }\n record.failures = 0\n } catch (error) {\n // Report the first failure of a streak, disable after MAX_FAILURES in a row.\n if (++record.failures === 1) this.#report(error, 'system', record.scope, record.name)\n if (record.failures >= MAX_FAILURES) {\n record.enabled = false\n record.error = error\n const disabled = new DioramaError(\n 'SYSTEM_DISABLED',\n `\"${record.name}\" failed ${MAX_FAILURES} frames in a row`,\n { plugin: record.scope.plugin, cause: error },\n )\n this.#report(disabled, 'system', record.scope, record.name)\n }\n }\n this.#profiled('systemEnd', record)\n }\n\n /** Calls one method of every profiler. A profiler that throws is removed and reported. */\n #profiled(method: keyof FrameProfiler, arg: FrameTime | SystemInfo): void {\n for (const profiler of this.#frameProfilers) {\n if (!this.#profilers.includes(profiler)) continue\n try {\n profiler[method](arg as never)\n } catch (error) {\n this.#profilers = this.#profilers.filter((other) => other !== profiler)\n this.#report(error, 'loop', undefined, 'profiler')\n }\n }\n }\n}\n\n/** The function handle that `app.system` returns. Calling it removes the system. */\nfunction systemHandle(record: SystemRecord, remove: () => void): SystemHandle {\n const handle = (() => remove()) as SystemHandle\n Object.defineProperties(handle, {\n name: { value: record.name },\n enabled: {\n get: () => record.enabled,\n set: (value: boolean) => {\n record.enabled = value\n if (!value) return\n record.failures = 0\n record.error = undefined\n },\n },\n error: { get: () => record.error },\n })\n return handle\n}\n\n/** Eases the frame interval toward a measured one. */\nfunction measureInterval(interval: number, measured: number): number {\n const plausible = measured > 0 && measured < GAP_FRAMES * interval\n const next = plausible ? interval + (measured - interval) * INTERVAL_EASING : interval\n return Math.min(Math.max(next, 1 / MAX_MEASURED_FPS), 1 / MIN_MEASURED_FPS)\n}\n\n/** Settings without invalid values. Each dropped value is warned about. */\nfunction validSettings(settings: LoopSettings, warn: (message: string) => void): LoopSettings {\n const result: { -readonly [K in keyof LoopSettings]: LoopSettings[K] } = {}\n const { mode } = settings\n if (mode === 'demand' || mode === 'always') result.mode = mode\n else if (mode !== undefined) warn(`loop: invalid mode \"${String(mode)}\" ignored`)\n for (const key of ['maxDelta', 'maxFps', 'timeScale'] as const) {\n const value = settings[key]\n if (isNonNegativeNumber(value)) result[key] = value\n else if (value !== undefined) warn(`loop: invalid ${key} ignored`)\n }\n return result\n}\n\nconst isNonNegativeNumber = (value: unknown): value is number =>\n typeof value === 'number' && Number.isFinite(value) && value >= 0\n\nfunction removeItem<T>(list: T[], item: T): boolean {\n const index = list.indexOf(item)\n if (index >= 0) list.splice(index, 1)\n return index >= 0\n}\n","import { DioramaError } from './errors'\nimport type { ErrorSource, Logger, Off } from './types'\nimport { isThenable, noop, resolved } from './util'\n\n/** Reports an error to the app: logs it, emits `app:error`, calls `onError`. */\nexport type Report = (\n error: unknown,\n source: ErrorSource,\n owner: Owner | undefined,\n target?: string,\n) => void\n\n/** What every owner of one app shares. */\nexport interface OwnerEnv {\n readonly report: Report\n logFor(owner: Owner): Logger\n}\n\nexport interface OwnerOptions {\n readonly env: OwnerEnv\n readonly label: string\n readonly rank: number\n readonly plugin?: string | undefined\n /** Services this owner may read. `undefined` means unrestricted. */\n readonly allowed?: ReadonlySet<string> | undefined\n}\n\n/** Tracks everything registered through it and undoes it, newest first, on dispose. */\nexport class Owner {\n readonly env: OwnerEnv\n readonly label: string\n readonly rank: number\n readonly plugin: string | undefined\n readonly allowed: ReadonlySet<string> | undefined\n disposed = false\n /** Set when a running setup is cut short, so its later registrations throw ABORTED. */\n abortOnAdd = false\n /** `undefined` inherits readiness from the parent. */\n #ownReady: boolean | undefined\n #parent: Owner | undefined\n /** Drops this owner from its parent's cleanups once it disposes on its own. */\n #unlink: (() => void) | undefined\n readonly #cleanups = new Set<() => unknown>()\n #controller: AbortController | undefined\n #disposal: Promise<void> | undefined\n #logger: Logger | undefined\n\n constructor(options: OwnerOptions) {\n this.env = options.env\n this.label = options.label\n this.rank = options.rank\n this.plugin = options.plugin\n this.allowed = options.allowed\n }\n\n /** Systems run only while their owner is ready. Children inherit it. */\n get ready(): boolean {\n return this.#ownReady ?? this.#parent?.ready ?? true\n }\n\n set ready(value: boolean) {\n this.#ownReady = value\n }\n\n /** Aborts when the owner disposes. Created on first read. */\n get signal(): AbortSignal {\n if (!this.#controller) {\n this.#controller = new AbortController()\n if (this.disposed) this.#controller.abort()\n }\n return this.#controller.signal\n }\n\n get log(): Logger {\n this.#logger ??= this.env.logFor(this)\n return this.#logger\n }\n\n /**\n * Registration guard. `false` once disposed, after a warning (or ABORTED for an orphaned\n * setup). Call it before touching shared state.\n */\n open(): boolean {\n if (!this.disposed) return true\n if (this.abortOnAdd)\n throw new DioramaError('ABORTED', 'setup was aborted', { plugin: this.plugin })\n this.log.warn('registration on a closed scope ignored')\n return false\n }\n\n /** Registers an undo. The returned Off runs it now, once. */\n add(undo: () => unknown): Off {\n if (this.disposed) {\n // Undo first. The orphaned setup gets ABORTED, but its resource must not leak.\n this.#runUndo(undo)\n this.open()\n return noop\n }\n this.#cleanups.add(undo)\n return () => {\n if (this.#cleanups.delete(undo)) this.#runUndo(undo)\n }\n }\n\n /** A nested owner, disposed with this one. Options not given are inherited. */\n child(options?: Partial<OwnerOptions>): Owner {\n const child = new Owner({\n env: this.env,\n label: options?.label ?? this.label,\n rank: options?.rank ?? this.rank,\n plugin: options && 'plugin' in options ? options.plugin : this.plugin,\n allowed: options && 'allowed' in options ? options.allowed : this.allowed,\n })\n child.#parent = this\n if (this.disposed) child.disposed = true\n else {\n const undo = (): Promise<void> => child.dispose()\n this.#cleanups.add(undo)\n child.#unlink = () => this.#cleanups.delete(undo)\n }\n return child\n }\n\n /** Aborts, then runs undos synchronously. The promise covers async undos only. */\n dispose(): Promise<void> {\n if (this.#disposal) return this.#disposal\n // Claim `#disposal` and empty the list before running anything, since undos may re-enter.\n let finish: (value: Promise<void>) => void = noop\n this.#disposal = new Promise<void>((resolve) => {\n finish = resolve\n })\n this.disposed = true\n this.#unlink?.()\n const undos = [...this.#cleanups].reverse()\n this.#cleanups.clear()\n this.#controller?.abort()\n const pending = undos.map((undo) => this.#runUndo(undo)).filter(isThenable)\n finish(pending.length ? Promise.all(pending).then(noop) : resolved)\n return this.#disposal\n }\n\n /** Runs one undo and reports its failure. Returns a promise only for an async undo. */\n #runUndo(undo: () => unknown): unknown {\n try {\n const result = undo()\n return isThenable(result)\n ? Promise.resolve(result).then(undefined, (error) =>\n this.env.report(error, 'dispose', this),\n )\n : undefined\n } catch (error) {\n this.env.report(error, 'dispose', this)\n }\n }\n}\n","/**\n * Push-pull signals. A write marks dependents as maybe stale and reads pull fresh values\n * lazily. Every source has a version, so staleness is checked, never guessed.\n * @module\n */\nimport { DioramaError } from './errors'\nimport type { EffectFn, Off, ReadonlySignal, Signal, SignalOptions } from './types'\nimport { isThenable } from './util'\n\n/** A computed or an effect: something that reads sources. */\ninterface Observer {\n /** Sources read by the last run, with the version each had then. */\n deps: Map<Source, number>\n notify(): void\n}\n\n/** A signal or a computed: something that can be read. */\ninterface Source {\n version: number\n /** Brings the value up to date. Only computeds do work here. */\n refresh(): void\n watch(observer: Observer): void\n unwatch(observer: Observer): void\n}\n\n/** Effects that write signals they read can loop. Give up after this many flush passes. */\nconst MAX_PASSES = 100\n\n// Module state is empty between synchronous calls.\n/** Dependencies of the observer running now, filled by reads. */\nlet collecting: Map<Source, number> | undefined\nlet batchDepth = 0\nlet flushing = false\nconst queue: EffectNode[] = []\n\n/** Reports errors that must not propagate to the code that wrote the signal. */\nfunction reportGlobal(error: unknown): void {\n const report = (globalThis as { reportError?: (e: unknown) => void }).reportError\n if (typeof report === 'function') report(error)\n else console.error(error)\n}\n\nfunction track(source: Source): void {\n if (collecting && !collecting.has(source)) collecting.set(source, source.version)\n}\n\n/** Runs queued effects until none are left, outside batches and nested flushes. */\nfunction flush(): void {\n if (flushing || batchDepth > 0) return\n flushing = true\n try {\n let passes = 0\n while (queue.length) {\n if (++passes > MAX_PASSES) {\n for (const node of queue) node.queued = false\n queue.length = 0\n const message = `effects did not settle after ${MAX_PASSES} passes`\n reportGlobal(new DioramaError('SIGNAL_CYCLE', message))\n break\n }\n const pass = queue.splice(0)\n for (const node of pass) {\n node.queued = false\n if (node.stale()) node.run()\n }\n }\n } finally {\n flushing = false\n }\n}\n\n// Only observed nodes hold subscriptions. Unobserved computeds keep none, so they can be\n// garbage-collected, and verify their sources by version on each read instead.\nfunction relink(observer: Observer, next: Map<Source, number>, watched: boolean): void {\n if (watched) {\n for (const source of observer.deps.keys()) if (!next.has(source)) source.unwatch(observer)\n for (const source of next.keys()) if (!observer.deps.has(source)) source.watch(observer)\n }\n observer.deps = next\n}\n\n/** A writable source. */\nclass SignalNode<T> implements Signal<T>, Source {\n version = 0\n #targets = new Set<Observer>()\n #value: T\n readonly #equals: (a: T, b: T) => boolean\n\n constructor(value: T, options?: SignalOptions<T>) {\n this.#value = value\n this.#equals = options?.equals ?? Object.is\n }\n\n get value(): T {\n track(this)\n return this.#value\n }\n\n set value(next: T) {\n if (this.#equals(this.#value, next)) return\n this.#value = next\n this.version++\n for (const target of this.#targets) target.notify()\n flush()\n }\n\n peek(): T {\n return this.#value\n }\n\n subscribe(listener: (value: T) => void): Off {\n return subscribe(this, listener)\n }\n\n refresh(): void {}\n\n watch(observer: Observer): void {\n this.#targets.add(observer)\n }\n\n unwatch(observer: Observer): void {\n this.#targets.delete(observer)\n }\n}\n\n/** A derived value: a source for its readers and an observer of what it reads. */\nclass ComputedNode<T> implements ReadonlySignal<T>, Source, Observer {\n version = 0\n deps: Map<Source, number> = new Map()\n #targets = new Set<Observer>()\n #value: T | undefined\n #error: unknown\n #failed = false\n #initialized = false\n #dirty = true\n #running = false\n readonly #fn: () => T\n readonly #equals: (a: T, b: T) => boolean\n\n constructor(fn: () => T, options?: SignalOptions<T>) {\n this.#fn = fn\n this.#equals = options?.equals ?? Object.is\n }\n\n get value(): T {\n this.refresh()\n track(this)\n if (this.#failed) throw this.#error\n return this.#value as T\n }\n\n peek(): T {\n this.refresh()\n if (this.#failed) throw this.#error\n return this.#value as T\n }\n\n subscribe(listener: (value: T) => void): Off {\n return subscribe(this, listener)\n }\n\n notify(): void {\n if (this.#dirty) return\n this.#dirty = true\n for (const target of this.#targets) target.notify()\n }\n\n refresh(): void {\n if (this.#running) throw new DioramaError('SIGNAL_CYCLE', 'computed depends on itself')\n if (this.#initialized && !this.#dirty && this.#targets.size > 0) return\n if (this.#initialized) {\n let changed = false\n for (const [source, seen] of this.deps) {\n source.refresh()\n if (source.version !== seen) {\n changed = true\n break\n }\n }\n if (!changed) {\n this.#dirty = false\n return\n }\n }\n this.#recompute()\n }\n\n #recompute(): void {\n const outer = collecting\n const next = new Map<Source, number>()\n collecting = next\n this.#running = true\n let value: T | undefined\n let error: unknown\n let failed = false\n try {\n value = this.#fn()\n } catch (thrown) {\n error = thrown\n failed = true\n } finally {\n collecting = outer\n this.#running = false\n }\n relink(this, next, this.#targets.size > 0)\n const changed =\n !this.#initialized ||\n failed !== this.#failed ||\n (failed ? error !== this.#error : !this.#equals(this.#value as T, value as T))\n this.#initialized = true\n this.#dirty = false\n if (changed) {\n this.#value = value\n this.#error = error\n this.#failed = failed\n this.version++\n }\n }\n\n watch(observer: Observer): void {\n if (this.#targets.size === 0) {\n // Sources may have changed while nobody watched. Catch up first so the new observer\n // sees a fresh version and `#dirty` keeps meaning \"observers notified\".\n try {\n this.refresh()\n } catch {}\n for (const source of this.deps.keys()) source.watch(this)\n }\n this.#targets.add(observer)\n }\n\n unwatch(observer: Observer): void {\n this.#targets.delete(observer)\n if (this.#targets.size === 0) for (const source of this.deps.keys()) source.unwatch(this)\n }\n}\n\n/** Reruns its function when a source it read changes. */\nclass EffectNode implements Observer {\n deps: Map<Source, number> = new Map()\n queued = false\n #disposed = false\n #cleanup: (() => unknown) | undefined\n readonly #fn: EffectFn\n readonly #onError: (error: unknown) => void\n\n constructor(fn: EffectFn, onError: (error: unknown) => void) {\n this.#fn = fn\n this.#onError = onError\n }\n\n notify(): void {\n if (this.queued || this.#disposed) return\n this.queued = true\n queue.push(this)\n }\n\n // Rerun only if a source really changed. A computed that recomputed to an equal value\n // stops propagation here, which also keeps diamonds glitch-free.\n stale(): boolean {\n if (this.#disposed) return false\n for (const [source, seen] of this.deps) {\n try {\n source.refresh()\n } catch {\n return true\n }\n if (source.version !== seen) return true\n }\n return false\n }\n\n run(): void {\n if (this.#disposed) return\n this.#runCleanup()\n const outer = collecting\n const next = new Map<Source, number>()\n collecting = next\n try {\n const result = this.#fn()\n if (typeof result === 'function') this.#cleanup = result as () => unknown\n else if (isThenable(result)) result.then(undefined, this.#onError)\n } catch (error) {\n this.#onError(error)\n } finally {\n collecting = outer\n if (this.#disposed) this.#runCleanup()\n else this.#settle(next)\n }\n }\n\n // Subscriptions start only after the run, so a write made during the run reached no\n // one. Compare versions now and rerun if a dependency moved under us.\n #settle(next: Map<Source, number>): void {\n relink(this, next, true)\n for (const [source, seen] of next) {\n if (source.version !== seen) {\n this.notify()\n flush()\n return\n }\n }\n }\n\n dispose(): void {\n if (this.#disposed) return\n this.#disposed = true\n for (const source of this.deps.keys()) source.unwatch(this)\n this.deps.clear()\n this.#runCleanup()\n }\n\n #runCleanup(): void {\n const cleanup = this.#cleanup\n this.#cleanup = undefined\n if (!cleanup) return\n const outer = collecting\n collecting = undefined\n try {\n cleanup()\n } catch (error) {\n this.#onError(error)\n } finally {\n collecting = outer\n }\n }\n}\n\n/** Svelte store contract: calls `listener` now and after every change. The first call may throw. */\nfunction subscribe<T>(node: ReadonlySignal<T>, listener: (value: T) => void): Off {\n let first = true\n const watcher = new EffectNode(\n () => {\n const value = node.value\n untracked(() => listener(value))\n },\n (error) => {\n if (first) throw error\n reportGlobal(error)\n },\n )\n try {\n watcher.run()\n } catch (error) {\n watcher.dispose()\n throw error\n } finally {\n first = false\n }\n return () => watcher.dispose()\n}\n\n/** A writable reactive value. Reading `value` inside `effect` or `computed` tracks it. */\nexport function signal<T>(value: T, options?: SignalOptions<T>): Signal<T> {\n return new SignalNode(value, options)\n}\n\n/**\n * A read-only value derived from signals, recomputed lazily when they change.\n * @throws {DioramaError} `SIGNAL_CYCLE` on read when the value depends on itself.\n */\nexport function computed<T>(compute: () => T, options?: SignalOptions<T>): ReadonlySignal<T> {\n return new ComputedNode(compute, options)\n}\n\n/** `effect` with a custom error sink. `app.effect` reports through the app. */\nexport function ownedEffect(fn: EffectFn, onError: (error: unknown) => void): Off {\n const node = new EffectNode(fn, onError)\n node.run()\n return () => node.dispose()\n}\n\n/** Runs `fn` now and again whenever a signal it read changes. Returns Off. */\nexport function effect(fn: EffectFn): Off {\n return ownedEffect(fn, reportGlobal)\n}\n\n/** Runs `fn` and notifies effects once at the end, not after each write. */\nexport function batch<T>(fn: () => T): T {\n batchDepth++\n try {\n return fn()\n } finally {\n batchDepth--\n flush()\n }\n}\n\n/** Runs `fn` without tracking the signals it reads. */\nexport function untracked<T>(fn: () => T): T {\n const outer = collecting\n collecting = undefined\n try {\n return fn()\n } finally {\n collecting = outer\n }\n}\n","/**\n * Views are what plugins, scopes and the app itself see as `app`. All views of one app share a\n * prototype and reach their kernel and owner through two symbols, so a scope per entity stays\n * cheap and a call allocates nothing.\n * @module\n */\nimport type { Kernel } from './app'\nimport { RESERVED } from './config'\nimport type { LoopImpl } from './loop'\nimport type { Owner } from './scope'\nimport { ownedEffect } from './signals'\nimport type {\n AppState,\n Cleanup,\n DependencyRef,\n FrameDriver,\n FrameProfiler,\n Logger,\n LoopSettings,\n Off,\n OrderOptions,\n ReadonlySignal,\n RemoveOptions,\n StagePosition,\n System,\n SystemHandle,\n} from './types'\nimport { noop } from './util'\n\nexport const OWNER: unique symbol = Symbol('diorama.owner') as never\nexport const KERNEL: unique symbol = Symbol('diorama.kernel') as never\n\nexport interface View {\n readonly [OWNER]: Owner\n readonly [KERNEL]: Kernel\n}\n\nconst kernelOf = (view: unknown): Kernel => (view as View)[KERNEL]\nconst ownerOf = (view: unknown): Owner => (view as View)[OWNER]\n\n/** The App API every view has. Registrations belong to the view's owner. */\nconst VIEW_METHODS = {\n use(entry: unknown): Promise<unknown> {\n return kernelOf(this).use(entry, ownerOf(this))\n },\n remove(ref: DependencyRef, options?: RemoveOptions): Promise<boolean> {\n return kernelOf(this).remove(ref, options, ownerOf(this))\n },\n has(ref: DependencyRef): boolean {\n return kernelOf(this).has(ref)\n },\n get(ref: DependencyRef): unknown {\n return kernelOf(this).service(ownerOf(this), ref, true)\n },\n find(ref: DependencyRef): unknown {\n return kernelOf(this).service(ownerOf(this), ref, false)\n },\n on(name: string, listener: (payload: unknown) => unknown): Off {\n return kernelOf(this).events.on(name, listener, ownerOf(this), false)\n },\n once(name: string, listener: (payload: unknown) => unknown): Off {\n return kernelOf(this).events.on(name, listener, ownerOf(this), true)\n },\n emit(name: string, payload?: unknown): void {\n if (!ownerOf(this).disposed) kernelOf(this).events.emit(name, payload)\n },\n hook(\n name: string,\n handler: (value: unknown, context: unknown) => unknown,\n options?: OrderOptions,\n ): Off {\n return kernelOf(this).hooks.add(name, handler, ownerOf(this), options)\n },\n callHook(name: string, value: unknown, context?: unknown): unknown {\n return ownerOf(this).disposed ? value : kernelOf(this).hooks.call(name, value, context)\n },\n callHookAsync(name: string, value: unknown, context?: unknown): Promise<unknown> {\n return ownerOf(this).disposed\n ? Promise.resolve(value)\n : kernelOf(this).hooks.callAsync(name, value, context)\n },\n hookVersion(name: string): number {\n return kernelOf(this).hooks.version(name)\n },\n get loop(): LoopImpl {\n return kernelOf(this).loop\n },\n system(stage: string, run: System, options?: OrderOptions): SystemHandle {\n return kernelOf(this).loop.system(stage, run, options, ownerOf(this))\n },\n addStage(name: string, position: StagePosition): Off {\n return kernelOf(this).loop.addStage(name, position, ownerOf(this))\n },\n invalidate(): void {\n const owner = ownerOf(this)\n if (!owner.disposed) kernelOf(this).loop.invalidate(owner)\n },\n keepAwake(seconds: number): void {\n const owner = ownerOf(this)\n if (!owner.disposed) kernelOf(this).loop.keepAwake(owner, seconds)\n },\n hold(): Off {\n return kernelOf(this).loop.hold(ownerOf(this))\n },\n pause(): Off {\n return kernelOf(this).loop.pause(ownerOf(this))\n },\n overrideLoop(settings: LoopSettings): Off {\n return kernelOf(this).loop.overrideLoop(ownerOf(this), settings)\n },\n setDriver(driver: FrameDriver): Off {\n return kernelOf(this).loop.setDriver(ownerOf(this), driver)\n },\n profile(profiler: FrameProfiler): Off {\n return kernelOf(this).loop.profile(ownerOf(this), profiler)\n },\n effect(fn: () => unknown): Off {\n const kernel = kernelOf(this)\n const owner = ownerOf(this)\n if (!owner.open()) return noop\n return owner.add(ownedEffect(fn, (error) => kernel.report(error, 'effect', owner)))\n },\n scope(): unknown {\n return kernelOf(this).view(ownerOf(this).child(), true)\n },\n onDispose(cleanup: Cleanup): Off {\n return ownerOf(this).add(typeof cleanup === 'function' ? cleanup : () => cleanup.dispose())\n },\n get abortSignal(): AbortSignal {\n return ownerOf(this).signal\n },\n get log(): Logger {\n return ownerOf(this).log\n },\n report(error: unknown, target?: string): void {\n const owner = ownerOf(this)\n // An AbortError after this view's own abort is the expected outcome, not a failure.\n if ((error as { name?: unknown } | null)?.name === 'AbortError' && owner.signal.aborted) return\n kernelOf(this).report(error, 'report', owner, target)\n },\n}\n\n/** Lifecycle members of the view `createApp` returns. */\nexport const ROOT_METHODS = {\n get name(): string {\n return kernelOf(this).name\n },\n get state(): ReadonlySignal<AppState> {\n return kernelOf(this).state\n },\n start(): Promise<unknown> {\n return kernelOf(this).start()\n },\n destroy(): Promise<void> {\n return kernelOf(this).destroy()\n },\n}\n\n/** Members of a view made by `app.scope()`. */\nexport const SCOPE_METHODS = {\n dispose(): Promise<void> {\n return ownerOf(this).dispose()\n },\n get disposed(): boolean {\n return ownerOf(this).disposed\n },\n}\n\nexport const describe = (methods: object): PropertyDescriptorMap =>\n Object.getOwnPropertyDescriptors(methods)\n\nexport const VIEW_PROTO: object = Object.defineProperties({}, describe(VIEW_METHODS))\n\n/** Whether a plugin name would shadow a member of the App API. */\nexport const isReserved = (name: string): boolean =>\n // Check the method objects, not a live view, which also carries service getters.\n name in VIEW_PROTO ||\n name in ROOT_METHODS ||\n name in SCOPE_METHODS ||\n (RESERVED as readonly string[]).includes(name)\n","import {\n type Config,\n collectEntries,\n cycleError,\n type Entry,\n LAYER_RUNTIME,\n missingHint,\n orderPlugins,\n type PluginRecord,\n resolveEntries,\n} from './config'\nimport { DioramaError, isDioramaError, messageOf, toDioramaError } from './errors'\nimport { type Depth, EventBus } from './events'\nimport { HookBus } from './hooks'\nimport { LoopImpl } from './loop'\nimport { definitionOf, isPreset, refName } from './plugin'\nimport { Owner } from './scope'\nimport { signal } from './signals'\nimport type {\n AnyPlugin,\n AppOptions,\n AppState,\n DependencyRef,\n ErrorReport,\n ErrorSource,\n Logger,\n PluginStatus,\n RemoveOptions,\n Signal,\n} from './types'\nimport { createLogger, isThenable, noop, resolved, shallowEqual } from './util'\nimport {\n describe,\n isReserved,\n KERNEL,\n OWNER,\n ROOT_METHODS,\n SCOPE_METHODS,\n VIEW_PROTO,\n type View,\n} from './view'\n\n/** `setTimeout` fires at once for longer delays, so such timeouts are not set at all. */\nconst MAX_TIMER_MS = 2 ** 31 - 1\n/** Seconds a setup may take unless `setupTimeout` says otherwise. */\nconst DEFAULT_SETUP_TIMEOUT = 30\n\nconst aborted = (plugin?: string): DioramaError =>\n new DioramaError('ABORTED', 'start was aborted', { plugin })\nconst destroyed = (): DioramaError => new DioramaError('APP_DESTROYED', 'the app is destroyed')\n\n/**\n * One app: its plugins, lifecycle, events, hooks and frame loop. Plugins start in dependency\n * order, each under its own owner, and stop in reverse order.\n */\nexport class Kernel {\n readonly name: string\n readonly state: Signal<AppState> = signal<AppState>('idle')\n readonly events: EventBus\n readonly hooks: HookBus\n readonly loop: LoopImpl\n readonly root: Owner\n readonly rootView: View\n readonly #options: AppOptions\n readonly #config: Config\n readonly #errorLog: Logger\n /** Seconds. */\n readonly #setupTimeout: number\n /** Prototype of every view: the App API plus a getter per running service. */\n readonly #viewProto: object\n readonly #scopeProto: object\n readonly #records = new Map<string, PluginRecord>()\n /** Setups that lost their race and still run. `destroy` waits for them. */\n readonly #orphanSetups = new Set<Promise<unknown>>()\n /** Cleanups of a failed start, awaited by `destroy`. */\n readonly #rollbacks: Promise<unknown>[] = []\n #starting: Promise<unknown> | undefined\n #stopping: Promise<void> | undefined\n /** Tail of the `use`/`remove` queue. */\n #operations: Promise<unknown> = resolved\n /** Aborts on `destroy`. */\n #abortController = new AbortController()\n /** A setup function is running synchronously right now. */\n #inSyncSetup = false\n #reporting = false\n #nextOrdinal = 0\n\n constructor(options: AppOptions, defaults: readonly AnyPlugin[]) {\n this.#options = options\n this.#config = {\n options,\n defaults,\n disabled: new Set(Array.isArray(options.disable) ? options.disable : []),\n reserved: isReserved,\n }\n this.name = options.name ?? 'app'\n const sink = options.logger ?? console\n const level = options.logLevel ?? 'warn'\n this.#errorLog = createLogger(sink, level, '')\n const timeout = options.setupTimeout\n this.#setupTimeout =\n typeof timeout === 'number' && timeout > 0 ? timeout : DEFAULT_SETUP_TIMEOUT\n const depth: Depth = { value: 0 }\n const report = this.report.bind(this)\n this.events = new EventBus(report, depth)\n this.hooks = new HookBus(report, depth)\n // One lazily built logger per owner. The root's is the app-wide one.\n const logFor = (owner: Owner): Logger => {\n const parts = ['diorama', options.name, owner.plugin].filter(Boolean)\n return createLogger(sink, level, `[${parts.join(':')}]`)\n }\n this.root = new Owner({ env: { report, logFor }, label: 'app', rank: Number.POSITIVE_INFINITY })\n this.loop = new LoopImpl(options.loop, report, (message) => this.root.log.warn(message))\n this.#viewProto = Object.create(VIEW_PROTO, { [KERNEL]: { value: this } })\n this.#scopeProto = Object.create(this.#viewProto, describe(SCOPE_METHODS))\n this.rootView = Object.create(Object.create(this.#viewProto, describe(ROOT_METHODS)), {\n [OWNER]: { value: this.root },\n })\n }\n\n view(owner: Owner, scope: boolean): View {\n return Object.create(scope ? this.#scopeProto : this.#viewProto, { [OWNER]: { value: owner } })\n }\n\n report(error: unknown, source: ErrorSource, owner: Owner | undefined, target?: string): void {\n const wrapped = toDioramaError(error, source, owner?.plugin)\n // A failure inside an app:error listener or onError must not recurse.\n if (this.#reporting) {\n console.error(wrapped)\n return\n }\n this.#reporting = true\n try {\n this.#errorLog.error(wrapped)\n const report: ErrorReport = {\n error: wrapped,\n source,\n plugin: owner?.plugin ?? wrapped.plugin,\n target,\n }\n this.events.emit('app:error', report)\n this.#options.onError?.(report)\n } catch (failure) {\n console.error(failure)\n } finally {\n this.#reporting = false\n }\n }\n\n has(ref: DependencyRef): boolean {\n return this.#records.get(refName(ref) ?? '')?.status === 'running'\n }\n\n service(owner: Owner, ref: DependencyRef, required: boolean): unknown {\n const name = refName(ref) ?? String(ref)\n // Plugin views see only their declared dependencies, in every build.\n if (owner.allowed && !owner.allowed.has(name)) {\n throw new DioramaError('UNDECLARED_DEPENDENCY', `\"${name}\" is not a declared dependency`, {\n plugin: owner.plugin,\n })\n }\n const record = this.#records.get(name)\n if (!owner.disposed && record?.status === 'running') return record.service\n if (!required) return undefined\n throw new DioramaError('SERVICE_UNAVAILABLE', this.#whyUnavailable(name, record, owner), {\n plugin: owner.plugin,\n })\n }\n\n #whyUnavailable(name: string, record: PluginRecord | undefined, owner: Owner): string {\n if (this.state.peek() === 'destroyed') return `\"${name}\": the app is destroyed`\n if (owner.disposed) return `\"${name}\": this view is closed`\n if (!record) return `\"${name}\" is not installed${missingHint(this.#config, name)}`\n return `\"${name}\" is ${record.status}${record.error ? `: ${record.error.message}` : ''}`\n }\n\n start(): Promise<unknown> {\n if (this.#starting) return this.#starting\n if (this.#stopping) return Promise.reject(destroyed())\n // The queue must exist before #run flips the state: effects on `state` may call use().\n let release: () => void = noop\n this.#operations = new Promise<void>((resolve) => {\n release = resolve\n })\n this.#starting = this.#run()\n void this.#starting.then(release, release)\n return this.#starting\n }\n\n async #run(): Promise<unknown> {\n this.state.value = 'starting'\n const { signal } = this.#abortController\n try {\n const problems: DioramaError[] = []\n const entries = collectEntries(this.#config, problems)\n const { list, failures } = await resolveEntries(this.#config, entries)\n if (signal.aborted) throw aborted()\n const ordered = this.#register(list, failures, problems)\n for (const record of ordered) {\n if (signal.aborted) throw aborted()\n if (record.status === 'failed') continue\n const stopped = record.deps.find((name) => !this.has(name))\n const error =\n stopped === undefined\n ? await this.#startPlugin(record, signal)\n : this.#skip(record, stopped)\n // failFast ends the start on a plugin's own failure, not on a skipped dependent.\n if (error && (record.critical || (this.#options.failFast && stopped === undefined))) {\n return this.#fail(error)\n }\n }\n if (signal.aborted) throw aborted()\n } catch (error) {\n if (signal.aborted || this.state.peek() !== 'starting') throw error\n // An unexpected throw must not leave the app stuck in `starting`.\n const wrapped = toDioramaError(error, 'config', undefined)\n this.report(wrapped, 'config', undefined)\n return this.#fail(wrapped)\n }\n\n this.state.value = 'running'\n // A `state` subscriber may have destroyed the app on this very transition.\n if (this.#stopping) throw aborted()\n this.loop.attach()\n this.events.emit('app:start', undefined)\n return this.rootView\n }\n\n /**\n * Orders the resolved plugins and registers them. Fails the start on a fatal configuration\n * problem; other problems only fail their plugin.\n */\n #register(\n list: readonly PluginRecord[],\n failures: ReadonlyMap<PluginRecord, DioramaError>,\n problems: DioramaError[],\n ): PluginRecord[] {\n const ordered = orderPlugins(list)\n if (!Array.isArray(ordered)) problems.push(cycleError(ordered.cycle))\n // Configuration errors only cost the plugin unless it is critical or failFast is set.\n for (const [record, error] of failures) {\n if (record.critical || this.#options.failFast) problems.push(error)\n }\n if (problems.length || !Array.isArray(ordered)) {\n const error =\n problems.length === 1\n ? (problems[0] as DioramaError)\n : new DioramaError('CONFIG_INVALID', `${problems.length} configuration problems`, {\n problems,\n })\n this.report(error, 'config', undefined)\n return this.#fail(error)\n }\n\n for (const record of ordered) {\n record.ordinal = this.#nextOrdinal++\n this.#records.set(record.name, record)\n }\n for (const [record, error] of failures) {\n record.error = error\n this.#setStatus(record, 'failed', error)\n this.report(error, 'config', undefined)\n }\n return ordered\n }\n\n /** Skips a plugin whose dependency is not running. The root cause is reported already. */\n #skip(record: PluginRecord, stopped: string): DioramaError {\n const error = new DioramaError(\n 'PLUGIN_DEPENDENCY_FAILED',\n `dependency \"${stopped}\" is not running`,\n { plugin: record.name },\n )\n record.error = error\n this.root.log.warn(error.message)\n this.#setStatus(record, 'skipped', error)\n return error\n }\n\n /** Rolls back a start and enters `failed`. */\n #fail(error: DioramaError): never {\n for (const record of this.#live()) this.#rollbacks.push(this.#stopPlugin(record))\n this.#rollbacks.push(this.root.dispose())\n this.loop.stop()\n this.state.value = 'failed'\n throw error\n }\n\n /** Plugins holding a scope, latest first. */\n #live(): PluginRecord[] {\n return [...this.#records.values()]\n .filter((record) => record.scope)\n .sort((a, b) => b.ordinal - a.ordinal)\n }\n\n #setStatus(record: PluginRecord, status: PluginStatus, error?: DioramaError): void {\n const previous = record.status\n record.status = status\n this.events.emit('plugin:status', { name: record.name, status, previous, error })\n }\n\n /** Runs one setup and returns its failure. ABORTED is thrown to the caller. */\n async #startPlugin(record: PluginRecord, signal: AbortSignal): Promise<DioramaError | undefined> {\n const scope = this.root.child({\n label: record.name,\n rank: record.ordinal,\n plugin: record.name,\n allowed: new Set([record.name, ...record.deps, ...record.optional]),\n })\n scope.ready = false\n record.scope = scope\n record.error = undefined\n this.#setStatus(record, 'starting')\n let service: unknown\n try {\n let result: unknown\n this.#inSyncSetup = true\n try {\n result = record.def.setup(this.view(scope, false), record.options)\n } finally {\n this.#inSyncSetup = false\n }\n service = isThenable(result) ? await this.#race(result, record.name, signal, scope) : result\n // The scope may have closed, or a required dependency stopped, while setup was awaiting.\n if (scope.disposed) throw aborted(record.name)\n const stopped = record.deps.find((name) => !this.has(name))\n if (stopped !== undefined) {\n throw new DioramaError(\n 'PLUGIN_DEPENDENCY_FAILED',\n `dependency \"${stopped}\" stopped during setup`,\n { plugin: record.name },\n )\n }\n } catch (error) {\n return this.#setupFailed(record, scope, signal, error)\n }\n // Running from here on: expose the service as `app.<name>` on every view.\n record.service = service\n record.hasService = service !== undefined\n scope.ready = true\n if (record.hasService) {\n const kernel = this\n Object.defineProperty(this.#viewProto, record.name, {\n configurable: true,\n get(this: View) {\n return kernel.service(this[OWNER], record.name, false)\n },\n })\n }\n this.#setStatus(record, 'running')\n return undefined\n }\n\n /** Undoes a failed setup and returns its error. Rethrows ABORTED of a cancelled start. */\n #setupFailed(\n record: PluginRecord,\n scope: Owner,\n signal: AbortSignal,\n error: unknown,\n ): DioramaError {\n scope.abortOnAdd = true\n void scope.dispose()\n if (record.scope === scope) record.scope = undefined\n if (isDioramaError(error, 'ABORTED') && (signal.aborted || record.status !== 'starting')) {\n throw error\n }\n const failure =\n isDioramaError(error, 'PLUGIN_TIMEOUT') || isDioramaError(error, 'PLUGIN_DEPENDENCY_FAILED')\n ? error\n : new DioramaError('PLUGIN_SETUP', messageOf(error), { plugin: record.name, cause: error })\n record.error = failure\n this.#setStatus(record, 'failed', failure)\n this.report(failure, 'setup', scope)\n return failure\n }\n\n /**\n * Races a setup against the timeout, the app's abort and the plugin scope closing. The\n * losing setup keeps running as an orphan, and `destroy` waits for it, bounded by the timeout.\n */\n #race(\n setup: PromiseLike<unknown>,\n plugin: string,\n appSignal: AbortSignal,\n scope: Owner,\n ): Promise<unknown> {\n const settled = Promise.resolve(setup)\n const orphan = settled.then(noop, noop)\n this.#orphanSetups.add(orphan)\n void orphan.then(() => this.#orphanSetups.delete(orphan))\n return new Promise((resolve, reject) => {\n const signals = [appSignal, scope.signal]\n if (signals.some((s) => s.aborted)) return reject(aborted(plugin))\n const ms = this.#setupTimeout * 1000\n const timer =\n ms <= MAX_TIMER_MS\n ? setTimeout(() => {\n const message = `setup did not finish in ${this.#setupTimeout} s (awaiting use() or remove() from setup deadlocks)`\n reject(new DioramaError('PLUGIN_TIMEOUT', message, { plugin }))\n }, ms)\n : undefined\n const onAbort = (): void => reject(aborted(plugin))\n for (const s of signals) s.addEventListener('abort', onAbort, { once: true })\n const cleanup = (): void => {\n clearTimeout(timer)\n for (const s of signals) s.removeEventListener('abort', onAbort)\n }\n settled.then(\n (value) => {\n cleanup()\n resolve(value)\n },\n (error: unknown) => {\n cleanup()\n reject(error)\n },\n )\n })\n }\n\n #stopPlugin(record: PluginRecord): Promise<void> {\n const { scope } = record\n if (!scope) return resolved\n if (record.status === 'starting') scope.abortOnAdd = true\n this.#setStatus(record, 'stopping')\n if (record.hasService) Reflect.deleteProperty(this.#viewProto, record.name)\n record.hasService = false\n record.service = undefined\n record.scope = undefined\n record.release?.()\n record.release = undefined\n const done = scope.dispose()\n this.#setStatus(record, 'stopped')\n return done\n }\n\n /** Stops required dependents first (latest first), then the plugin itself. */\n #stopTree(record: PluginRecord): Promise<unknown> {\n // A stale record (replaced by a re-install) must not stop its namesake's dependents.\n if (this.#records.get(record.name) !== record) return resolved\n const dependents = this.#dependentsOf(record.name).sort((a, b) => b.ordinal - a.ordinal)\n return Promise.all([...dependents, record].map((r) => this.#stopPlugin(r)))\n }\n\n destroy(): Promise<void> {\n if (this.#stopping) return this.#stopping\n // Claim the promise first so a listener or cleanup calling destroy() again gets this one.\n let finish: (done: Promise<void>) => void = noop\n this.#stopping = new Promise<void>((resolve) => {\n finish = resolve\n })\n const previous = this.state.peek()\n const pending: Promise<unknown>[] = [...this.#rollbacks]\n const waiting = new Set<string>()\n if (previous !== 'idle' && previous !== 'failed') {\n this.state.value = 'destroying'\n this.#abortController.abort()\n // Services are still alive for app:destroy listeners.\n if (previous === 'running') this.events.emit('app:destroy', undefined)\n this.loop.stop()\n for (const record of this.#live()) {\n waiting.add(record.name)\n pending.push(this.#stopPlugin(record).finally(() => waiting.delete(record.name)))\n }\n }\n pending.push(this.root.dispose(), ...this.#orphanSetups)\n this.state.value = 'destroyed'\n finish(this.#settle(pending, waiting))\n return this.#stopping\n }\n\n /** Waits for every cleanup, or warns and gives up after the setup timeout. */\n #settle(pending: Promise<unknown>[], waiting: ReadonlySet<string>): Promise<void> {\n const all = Promise.allSettled(pending).then(noop)\n const ms = this.#setupTimeout * 1000\n if (ms > MAX_TIMER_MS) return all\n return new Promise((resolve) => {\n const timer = setTimeout(() => {\n const message = `destroy: cleanups still pending after ${this.#setupTimeout} s`\n this.root.log.warn(message, [...waiting])\n resolve()\n }, ms)\n void all.then(() => {\n clearTimeout(timer)\n resolve()\n })\n })\n }\n\n /**\n * Runtime operations run one at a time, after start, in call order. Calling one from a\n * running setup is rejected at once: awaiting it there would deadlock the start.\n */\n #enqueue<T>(owner: Owner, operation: () => Promise<T>): Promise<T> {\n const state = this.state.peek()\n if (state === 'destroying' || state === 'destroyed') return Promise.reject(destroyed())\n if (state === 'idle' || state === 'failed') {\n return Promise.reject(new DioramaError('APP_STATE', `the app is ${state}`))\n }\n const ownerStarting = owner.plugin && this.#records.get(owner.plugin)?.status === 'starting'\n if (this.#inSyncSetup || ownerStarting) {\n return Promise.reject(\n new DioramaError('PLUGIN_REENTRANT', 'use() and remove() cannot be called from setup', {\n plugin: owner.plugin,\n }),\n )\n }\n const run = this.#operations.then(() => {\n if (this.#stopping) throw destroyed()\n if (owner.disposed) throw aborted()\n if (this.state.peek() !== 'running') {\n throw new DioramaError('APP_STATE', 'the app did not start')\n }\n return operation()\n })\n this.#operations = run.then(noop, noop)\n return run\n }\n\n use(entry: unknown, owner: Owner): Promise<unknown> {\n return this.#enqueue(owner, () => this.#install(entry, owner))\n }\n\n async #install(entry: unknown, owner: Owner): Promise<unknown> {\n const entries = flattenPlugins(entry).map((plugin, index): Entry => {\n const def = definitionOf(plugin)\n if (!def) throw new DioramaError('PLUGIN_INVALID', `not a plugin: ${String(plugin)}`)\n return { plugin: plugin as AnyPlugin, def, layer: LAYER_RUNTIME, index }\n })\n const { list, failures } = await resolveEntries(this.#config, entries, (name) => this.has(name))\n const cancelled = (): boolean => this.#abortController.signal.aborted || owner.disposed\n if (cancelled()) throw aborted()\n for (const error of failures.values()) throw error\n const ordered = orderPlugins(list.filter((record) => this.#needsInstall(record)))\n if (!Array.isArray(ordered)) throw cycleError(ordered.cycle)\n\n const started: PluginRecord[] = []\n try {\n for (const record of ordered) {\n if (cancelled()) throw aborted()\n record.ordinal = this.#nextOrdinal++\n this.#records.set(record.name, record)\n // Owned before setup, so closing the owner also interrupts a running setup.\n if (owner !== this.root) {\n record.release = owner.add(() => (record.scope ? this.#stopTree(record) : undefined))\n }\n const error = await this.#startPlugin(record, this.#abortController.signal)\n if (error) throw error\n started.push(record)\n }\n } catch (error) {\n for (const record of started.reverse()) await this.#stopPlugin(record)\n // Drop owner links of records that never ran, or a later close could hit a namesake.\n for (const record of ordered) {\n record.release?.()\n record.release = undefined\n }\n throw error\n }\n return typeof entry === 'function' ? this.#records.get(entry.name)?.service : undefined\n }\n\n /**\n * Whether `use` must start this record. Re-installing a running plugin with the same\n * definition and options is a no-op.\n * @throws {DioramaError} `PLUGIN_DUPLICATE` when it runs with other options.\n */\n #needsInstall(record: PluginRecord): boolean {\n const running = this.#records.get(record.name)\n if (running?.status !== 'running') return true\n if (running.def === record.def && shallowEqual(running.raw, record.raw)) return false\n throw new DioramaError(\n 'PLUGIN_DUPLICATE',\n `\"${record.name}\" is already running with other options`,\n { plugin: record.name },\n )\n }\n\n remove(ref: DependencyRef, options: RemoveOptions | undefined, owner: Owner): Promise<boolean> {\n return this.#enqueue(owner, async () => {\n const name = refName(ref) ?? ''\n const record = this.#records.get(name)\n if (!record) return false\n if (record.status === 'running') {\n const dependents = this.#dependentsOf(name)\n if (dependents.length && !options?.cascade) {\n const names = dependents.map((dependent) => dependent.name).join(', ')\n throw new DioramaError('PLUGIN_HAS_DEPENDENTS', `required by ${names}`, { plugin: name })\n }\n await this.#stopTree(record)\n }\n record.release?.()\n this.#records.delete(name)\n return true\n })\n }\n\n /** Running plugins that require `name`, directly or transitively. */\n #dependentsOf(name: string): PluginRecord[] {\n const found = new Set<PluginRecord>()\n const visit = (target: string): void => {\n for (const record of this.#records.values()) {\n if (record.status === 'running' && record.deps.includes(target) && !found.has(record)) {\n found.add(record)\n visit(record.name)\n }\n }\n }\n visit(name)\n return [...found]\n }\n}\n\n/** Synchronous and never throws. Plugins start on `app.start()`. */\nexport function createKernelApp(\n options: AppOptions | undefined,\n defaults: readonly AnyPlugin[],\n): unknown {\n return new Kernel(options ?? {}, defaults).rootView\n}\n\n/** Plugins of a `use()` argument: arrays and presets are opened, falsy entries skipped. */\nfunction flattenPlugins(entry: unknown): unknown[] {\n const plugins: unknown[] = []\n const visit = (value: unknown): void => {\n if (Array.isArray(value)) value.forEach(visit)\n else if (isPreset(value)) [...value.presets, ...value.plugins].forEach(visit)\n else if (value) plugins.push(value)\n }\n visit(entry)\n return plugins\n}\n","/**\n * Calls `swap` after the document's <body> element is replaced (Astro ClientRouter, Turbo).\n * Observes only the childList of <html>, which gives one record per swap and none for page\n * content changes.\n */\nexport function onBodySwap(\n app: { onDispose(cleanup: () => void): unknown },\n swap: (body: HTMLElement, previous: HTMLElement) => void,\n): void {\n if (typeof document === 'undefined' || typeof MutationObserver === 'undefined') return\n let current = document.body\n const observer = new MutationObserver(() => {\n const body = document.body\n if (!body || body === current) return\n const previous = current\n current = body\n swap(body, previous)\n })\n observer.observe(document.documentElement, { childList: true })\n app.onDispose(() => observer.disconnect())\n}\n","import { definePlugin } from '../kernel/plugin'\nimport type { Plugin } from '../kernel/types'\nimport { noop } from '../kernel/util'\nimport { onBodySwap } from './body'\n\n/** An element's box, kept in sync with the page in the `layout` stage. */\nexport interface Anchor {\n /** The tracked element. */\n readonly element: Element\n /** Viewport position and size, CSS px. */\n readonly x: number\n /** Viewport y, CSS px. */\n readonly y: number\n /** Width, CSS px. */\n readonly width: number\n /** Height, CSS px. */\n readonly height: number\n /** Overlaps the viewport. */\n readonly visible: boolean\n /**\n * 0 as the top enters at the bottom of the viewport, 1 as the bottom leaves at the top.\n * Measured along `scroll.state.axis`, so a horizontal source runs it from right to left.\n */\n readonly progress: number\n /**\n * Progress of a section pinned with CSS sticky. 0 while its top is below the viewport top,\n * 1 once it has scrolled `height - viewport height` past it. A section no taller than the\n * viewport switches from 0 to 1 as its top passes the viewport top.\n */\n readonly pin: number\n /** Counts re-measures after layout changes. Per-frame live reads don't bump it. */\n readonly version: number\n /** Stops tracking. Pass the anchor to `app.onDispose` to tie it to a scope. */\n dispose(): void\n}\n\n/** Options of `anchors.track`. */\nexport interface TrackOptions {\n /**\n * Re-read the box every frame while near the viewport, to follow transforms and inline\n * `position: fixed`. Elements inside sticky or fixed ancestors are live by themselves.\n */\n readonly live?: boolean\n}\n\n/** The `anchors` service: element boxes kept in sync with the page. */\nexport interface AnchorsApi {\n /** Starts tracking an element. The anchor updates in the `layout` stage. */\n track(element: Element, options?: TrackOptions): Anchor\n /** Re-measures every anchor after a layout change the observers cannot see. */\n refresh(): void\n}\n\n/** The anchor object itself, with the cached page geometry behind it. */\ninterface Entry {\n element: Element\n x: number\n y: number\n width: number\n height: number\n visible: boolean\n progress: number\n pin: number\n version: number\n /** Position relative to the document, measured with the DOM. */\n pageX: number\n pageY: number\n /** `track` asked for `live`. */\n manual: boolean\n /** Re-read every frame while near the viewport: manual, or inside sticky or fixed. */\n live: boolean\n /** Page band a sticky element moves within along the axis. Unbounded when fixed, else empty. */\n start: number\n end: number\n dispose(): void\n}\n\n/** How far ahead of the viewport, in viewport sizes, a live anchor is still re-read. */\nconst NEAR_AHEAD = 2\n\n/**\n * What moves an element without a layout change: the box its outermost sticky ancestor moves\n * within, `fixed` for a fixed ancestor, or `null`. `positions` caches computed styles per pass.\n */\nconst stickyContainer = (\n element: Element,\n positions: Map<Element, string>,\n): Element | 'fixed' | null => {\n let within: Element | null = null\n for (let node: Element | null = element; node; node = node.parentElement) {\n let position = positions.get(node)\n if (position === undefined) {\n position = getComputedStyle(node).position\n positions.set(node, position)\n }\n if (position === 'fixed') return 'fixed'\n if (position === 'sticky') within = node.parentElement\n }\n return within\n}\n\n/** A page band near the viewport along the scroll axis, at scroll offset `at`. Behind the\n * viewport it counts as near for one viewport size. */\nconst isNear = (start: number, end: number, at: number, size: number): boolean =>\n start - at < NEAR_AHEAD * size && end - at > -size\n\n/**\n * Layout is read only when something may have moved (resize, observed size changes,\n * fonts). Each frame just offsets the cached page boxes by the scroll position. Live anchors\n * near the viewport are re-read every frame, since sticky, fixed and transformed boxes move\n * without a layout change.\n */\nexport const anchors: Plugin<'anchors'> = /*#__PURE__*/ definePlugin({\n name: 'anchors',\n dependencies: ['stage', 'scroll'],\n setup(app): AnchorsApi {\n const { stage, scroll } = app\n const entries = new Set<Entry>()\n // Boxes must be read from the DOM before the next frame uses them.\n let stale = true\n let horizontal = false\n /** Scroll offset along the axis in the last frame. */\n let lastAlong = 0\n const refresh = (): void => {\n stale = true\n app.invalidate()\n }\n\n const observer = typeof ResizeObserver === 'undefined' ? undefined : new ResizeObserver(refresh)\n // Entries of one element share its observation. The last one to go ends it.\n const counts = new Map<Element, number>()\n const observe = (element: Element): void => {\n const count = counts.get(element) ?? 0\n counts.set(element, count + 1)\n if (!count) observer?.observe(element)\n }\n const unobserve = (element: Element): void => {\n const count = (counts.get(element) ?? 1) - 1\n if (count) counts.set(element, count)\n else if (counts.delete(element)) observer?.unobserve(element)\n }\n if (typeof document !== 'undefined') {\n observe(document.body)\n window.addEventListener('resize', refresh, { signal: app.abortSignal })\n document.fonts?.ready.then(refresh, noop)\n onBodySwap(app, (body, previous) => {\n unobserve(previous)\n observe(body)\n refresh()\n })\n }\n app.onDispose(() => {\n observer?.disconnect()\n counts.clear()\n entries.clear()\n })\n\n const readBox = (entry: Entry, scrollX: number, scrollY: number): void => {\n const box = entry.element.getBoundingClientRect()\n entry.pageX = box.left + scrollX\n entry.pageY = box.top + scrollY\n entry.width = box.width\n entry.height = box.height\n }\n\n app.system(\n 'layout',\n () => {\n const { x: scrollX, y: scrollY, axis } = scroll.state\n const width = stage.width.peek()\n const height = stage.height.peek()\n // Progress, pin and nearness run along the scroll axis, so a horizontal source measures\n // by width. Sticky bands are stored along it too, so a new axis re-measures.\n if (horizontal !== (axis === 'x')) {\n horizontal = !horizontal\n stale = true\n }\n const along = horizontal ? scrollX : scrollY\n const size = horizontal ? width : height\n // Reads only in this pass, so layout is forced at most once.\n const positions = stale ? new Map<Element, string>() : undefined\n // Cached boxes cannot be trusted to say what is near after a jump.\n const jumped = Math.abs(along - lastAlong) > size\n stale = false\n lastAlong = along\n for (const entry of entries) {\n if (positions) {\n // Full measure after a layout change: the box and what moves it.\n readBox(entry, scrollX, scrollY)\n entry.version++\n const container = stickyContainer(entry.element, positions)\n const band =\n container && container !== 'fixed' ? container.getBoundingClientRect() : undefined\n entry.live = entry.manual || container !== null\n // A fixed element is near everywhere, one that is not sticky only by its own box.\n const unbounded = container ? Infinity : -Infinity\n entry.start = band ? (horizontal ? band.left : band.top) + along : -unbounded\n entry.end = band ? (horizontal ? band.right : band.bottom) + along : unbounded\n } else if (entry.live) {\n const start = horizontal ? entry.pageX : entry.pageY\n const end = start + (horizontal ? entry.width : entry.height)\n if (\n jumped ||\n isNear(entry.start, entry.end, along, size) ||\n isNear(start, end, along, size)\n ) {\n readBox(entry, scrollX, scrollY)\n }\n }\n // Viewport box, visibility, progress and pin from the cached page box.\n entry.x = entry.pageX - scrollX\n entry.y = entry.pageY - scrollY\n entry.visible =\n entry.width > 0 &&\n entry.x < width &&\n entry.x + entry.width > 0 &&\n entry.y < height &&\n entry.y + entry.height > 0\n const at = horizontal ? entry.x : entry.y\n const length = horizontal ? entry.width : entry.height\n entry.progress = Math.min(1, Math.max(0, (size - at) / (size + length || 1)))\n const travel = length - size\n entry.pin = travel > 0 ? Math.min(1, Math.max(0, -at / travel)) : at <= 0 ? 1 : 0\n }\n },\n { name: 'anchors' },\n )\n\n return {\n refresh,\n track(element, options) {\n const manual = options?.live === true\n const entry: Entry = {\n element,\n x: 0,\n y: 0,\n width: 0,\n height: 0,\n visible: false,\n progress: 0,\n pin: 0,\n version: 0,\n pageX: 0,\n pageY: 0,\n manual,\n live: manual,\n start: Infinity,\n end: -Infinity,\n dispose() {\n if (entries.delete(entry)) unobserve(element)\n },\n }\n entries.add(entry)\n observe(element)\n refresh()\n return entry\n },\n }\n },\n})\n","import type { FrameTime } from '../kernel/types'\n\n/** Smoothing rate of velocities, per second. Frame-rate independent. */\nconst SMOOTHING = 10\n/** Below this speed (px/s) motion counts as settled. */\nconst REST_SPEED = 1\n/** Without frames for this long (ms) a velocity counts as settled. */\nconst STALE_MS = 100\n\n/** A smoothed velocity fed once per frame. */\nexport interface VelocityTracker {\n /** The smoothed velocity. Reading it before it settles asks for the next frame. */\n readonly value: number\n /** Feeds the distance moved since the previous frame. */\n update(distance: number, t: FrameTime): void\n}\n\n/**\n * Exponentially smoothed velocity. Frames keep coming while someone reads it as it decays, so\n * effects driven by it ease out instead of freezing mid-motion. Unread, it asks for none.\n */\nexport function velocityTracker(app: {\n invalidate(): void\n readonly loop: { readonly driver: { now(): number } }\n}): VelocityTracker {\n let velocity = 0\n /** Driver time of the last update. */\n let updatedAt = 0\n return {\n get value() {\n if (velocity) {\n // Nobody read it while frames were stopped, so it would have settled by now.\n if (app.loop.driver.now() - updatedAt > STALE_MS) velocity = 0\n else app.invalidate()\n }\n return velocity\n },\n update(distance, time) {\n const instant = time.delta > 0 ? distance / time.delta : 0\n velocity += (instant - velocity) * (1 - Math.exp(-time.delta * SMOOTHING))\n if (Math.abs(velocity) <= REST_SPEED) velocity = 0\n updatedAt = time.now\n },\n }\n}\n","import { definePlugin } from '../kernel/plugin'\nimport type { Plugin } from '../kernel/types'\nimport { velocityTracker } from './motion'\n\n/**\n * Live pointer state. A move asks for a frame only if someone read the position in the last\n * frame (or since), so a page whose effects ignore the pointer draws nothing on mouse moves.\n */\nexport interface PointerState {\n /** Viewport position, CSS px. */\n readonly x: number\n /** Viewport y, CSS px. */\n readonly y: number\n /** Normalized device coordinates, -1..1, y up. */\n readonly nx: number\n /** Normalized y, -1..1, up is positive. */\n readonly ny: number\n /** Smoothed velocity, px/s. Reading it while it decays keeps frames coming. */\n readonly vx: number\n /** Smoothed vertical velocity, px/s. */\n readonly vy: number\n /** The pointer is over the page. A touch leaves when the finger lifts. */\n readonly inside: boolean\n /** Device of the last pointer event. */\n readonly type: 'mouse' | 'pen' | 'touch'\n}\n\n/** The `pointer` service. */\nexport interface PointerApi {\n /** Pointer state, updated in place every frame. */\n readonly state: PointerState\n}\n\n/** Tracks the pointer over the page. Built in. */\nexport const pointer: Plugin<'pointer'> = /*#__PURE__*/ definePlugin({\n name: 'pointer',\n dependencies: ['stage'],\n setup(app): PointerApi {\n const trackX = velocityTracker(app)\n const trackY = velocityTracker(app)\n let x = 0\n let y = 0\n let inside = false\n // The frame of the last read. Moves wake the loop only for a reader.\n let readFrame = -1\n const markRead = (): void => {\n readFrame = app.loop.time.frame\n }\n const state = {\n get x() {\n markRead()\n return x\n },\n get y() {\n markRead()\n return y\n },\n get nx() {\n markRead()\n return (x / (app.stage.width.peek() || 1)) * 2 - 1\n },\n get ny() {\n markRead()\n return 1 - (y / (app.stage.height.peek() || 1)) * 2\n },\n get vx() {\n markRead()\n return trackX.value\n },\n get vy() {\n markRead()\n return trackY.value\n },\n get inside() {\n markRead()\n return inside\n },\n type: 'mouse' as PointerState['type'],\n }\n if (typeof window === 'undefined') return { state }\n\n const wake = (): void => {\n if (readFrame >= app.loop.time.frame) app.invalidate()\n }\n const listen = { signal: app.abortSignal, passive: true }\n const move = (event: PointerEvent): void => {\n x = event.clientX\n y = event.clientY\n const { pointerType } = event\n state.type = pointerType === 'touch' || pointerType === 'pen' ? pointerType : 'mouse'\n inside = true\n wake()\n }\n const leave = (): void => {\n inside = false\n wake()\n }\n // A lifted finger hovers nothing. Without this, hover sticks after a tap.\n const lift = (event: PointerEvent): void => {\n if (event.pointerType === 'touch') leave()\n }\n window.addEventListener('pointermove', move, listen)\n window.addEventListener('pointerdown', move, listen)\n window.addEventListener('pointerup', lift, listen)\n window.addEventListener('pointercancel', lift, listen)\n document.documentElement.addEventListener('pointerleave', leave, listen)\n\n // Velocity is fed per frame. Entering (first move, back over the page, a new touch)\n // re-bases without a spike.\n let lastX = 0\n let lastY = 0\n let wasInside = false\n app.system(\n 'input',\n (time) => {\n const entered = inside && !wasInside\n wasInside = inside\n trackX.update(entered ? 0 : x - lastX, time)\n trackY.update(entered ? 0 : y - lastY, time)\n lastX = x\n lastY = y\n },\n { name: 'pointer' },\n )\n return { state }\n },\n})\n","import { definePlugin } from '../kernel/plugin'\nimport type { Off, Plugin } from '../kernel/types'\nimport { noop } from '../kernel/util'\nimport { onBodySwap } from './body'\nimport { velocityTracker } from './motion'\n\n/** Scroll axis: `x` for horizontal, `y` for vertical. */\nexport type ScrollAxis = 'x' | 'y'\n\n/** Live scroll state, updated in place in the `input` stage. */\nexport interface ScrollState {\n /** Document scroll offset, CSS px. */\n readonly x: number\n /** Vertical document scroll offset, CSS px. */\n readonly y: number\n /**\n * Smoothed velocity along `axis`, px/s, positive while scrolling down (or right). Reading it\n * while it decays keeps frames coming.\n */\n readonly velocity: number\n /** 1 down, -1 up, 0 at rest. */\n readonly direction: -1 | 0 | 1\n /** 0..1 through the scrollable range along `axis`. */\n readonly progress: number\n /** Axis of `progress`, `velocity` and `direction`. The active source's, or 'y' without one. */\n readonly axis: ScrollAxis\n}\n\n/** One frame's reading of a scroll source, filled in place. */\nexport interface ScrollSample {\n /** Document scroll offset this frame, CSS px, as the page shows it. */\n x: number\n /** Vertical offset this frame, CSS px. */\n y: number\n /** Continuous position along the axis for velocity. An infinite scroller doesn't wrap it. */\n travel: number\n}\n\n/** Where `scroll` takes the offset from. Without one, window scroll events are cached. */\nexport interface ScrollSource {\n /** Label for logs. */\n readonly name: string\n /** Axis of `progress`, `velocity`, `direction`. Default 'y'. */\n readonly axis?: ScrollAxis\n /** Called once per frame at the start of the `scroll` system. Reads only, never writes the DOM. */\n read(out: ScrollSample): void\n /** Scrollable range along the axis, CSS px. Default: the measured document range. */\n limit?(): number\n}\n\n/** The `scroll` service. */\nexport interface ScrollApi {\n /** Scroll state, updated in place every frame. */\n readonly state: ScrollState\n /** Re-reads the scrollable range after a layout change the observers cannot see. */\n measure(): void\n /**\n * Reads offsets from `source` from the next frame on. The newest source wins and Off restores\n * the previous one. The switch frame keeps the previous velocity, so there is no spike.\n */\n source(source: ScrollSource): Off\n}\n\nconst finite = (value: number, fallback: number): number =>\n Number.isFinite(value) ? value : fallback\n\n/** Tracks page scroll, its velocity and progress. Built in. */\nexport const scroll: Plugin<'scroll'> = /*#__PURE__*/ definePlugin({\n name: 'scroll',\n setup(app): ScrollApi {\n const track = velocityTracker(app)\n const state = {\n x: 0,\n y: 0,\n get velocity() {\n return track.value\n },\n get direction() {\n return Math.sign(track.value) as -1 | 0 | 1\n },\n progress: 0,\n axis: 'y' as ScrollAxis,\n }\n if (typeof window === 'undefined') return { state, measure: noop, source: () => noop }\n\n const root = document.documentElement\n let x = window.scrollX\n let y = window.scrollY\n let rangeX = 0\n let rangeY = 0\n state.x = x\n state.y = y\n // Scroll events only record the offset. The frame turns it into state.\n const listen = { signal: app.abortSignal, passive: true }\n window.addEventListener(\n 'scroll',\n () => {\n x = window.scrollX\n y = window.scrollY\n app.invalidate()\n },\n listen,\n )\n const measure = (): void => {\n rangeX = Math.max(0, root.scrollWidth - root.clientWidth)\n rangeY = Math.max(0, root.scrollHeight - root.clientHeight)\n app.invalidate()\n }\n measure()\n window.addEventListener('resize', measure, listen)\n const observer = typeof ResizeObserver === 'undefined' ? undefined : new ResizeObserver(measure)\n observer?.observe(document.body)\n if (observer) app.onDispose(() => observer.disconnect())\n onBodySwap(app, (body, previous) => {\n observer?.unobserve(previous)\n observer?.observe(body)\n measure()\n })\n\n const sources: ScrollSource[] = []\n const sample = { x: 0, y: 0, travel: 0 }\n let lastTravel = y\n // The first frame, and the one after a resync, re-base travel without feeding velocity.\n let resync = true\n // The active source threw last frame. Errors are reported once per streak.\n let failing = false\n const switched = (): void => {\n resync = true\n failing = false\n app.invalidate()\n }\n const source = (added: ScrollSource): Off => {\n sources.push(added)\n switched()\n return () => {\n const index = sources.indexOf(added)\n if (index < 0) return\n sources.splice(index, 1)\n switched()\n }\n }\n\n /** Fills `sample` from the active source, or from native offsets if it throws. */\n const readSource = (active: ScrollSource): number | undefined => {\n sample.x = x\n sample.y = y\n sample.travel = lastTravel\n try {\n active.read(sample)\n const limit = active.limit?.()\n sample.x = finite(sample.x, x)\n sample.y = finite(sample.y, y)\n sample.travel = finite(sample.travel, lastTravel)\n // A recovering source may be in another domain than the native fallback.\n if (failing) resync = true\n failing = false\n return limit\n } catch (error) {\n if (!failing) app.report(error, `scroll:${active.name}`)\n failing = true\n sample.x = x\n sample.y = y\n sample.travel = lastTravel\n return undefined\n }\n }\n\n app.system(\n 'input',\n (time) => {\n const active = sources.at(-1)\n let limit: number | undefined\n if (active) {\n limit = readSource(active)\n } else {\n sample.x = x\n sample.y = y\n sample.travel = y\n }\n const axis = active?.axis ?? 'y'\n const moved = sample.travel - lastTravel\n // A jump (restore, #hash, scrollTo immediate) or a wake after idle is no motion.\n if (resync || time.resumed) resync = false\n else if (Math.abs(moved) > (axis === 'x' ? innerWidth : innerHeight)) resync = false\n else track.update(moved, time)\n lastTravel = sample.travel\n let range = axis === 'x' ? rangeX : rangeY\n if (Number.isFinite(limit) && (limit as number) > 0) range = limit as number\n const offset = axis === 'x' ? sample.x : sample.y\n state.axis = axis\n state.x = sample.x\n state.y = sample.y\n state.progress = range > 0 ? Math.min(1, Math.max(0, offset / range)) : 0\n },\n { name: 'scroll' },\n )\n return { state, measure, source }\n },\n})\n","import type { AppCore, Off } from '../kernel/types'\n\nconst KEYFRAMES = 'dio-stage-scroll'\n/** Scroll covered by the follow animation, px. Past it the canvas stays put. */\nconst RANGE = 1_000_000\n/** Spans that moved less than this, px, keep their keyframes. */\nconst SPAN_TOLERANCE = 0.5\nlet sheet: CSSStyleSheet | undefined\nlet instances = 0\n\n/** A span of page scroll, px from the top, over which content on screen stands still. */\nexport type ScrollSpan = readonly [start: number, end: number]\n\n/** Starts following a canvas; `hold` keeps it still while a predicate is true. */\nexport interface Follow {\n (canvas: HTMLCanvasElement): void\n hold(held: () => boolean): Off\n pin(spans: () => readonly ScrollSpan[]): Off\n}\n\n/**\n * Lets a fixed canvas follow page scroll on the compositor. A scroll timeline applies\n * `translateY(-scroll)` in every compositor frame, and each Diorama frame adds back, through\n * `translate`, the scroll it drew at. Between frames the canvas moves with the page by the\n * scroll the frame has not seen yet.\n *\n * Content that stands still on screen would ride that scroll and jump back when the frame lands.\n * `pin` spans (a pinned sticky stage) go into the keyframes: the timeline stops moving the canvas\n * inside them, so it stops and starts on the compositor where CSS sticky does, between frames.\n * A `hold` predicate (content fixed to the viewport) drops the animation while true, and frames\n * draw at scroll 0. Both are read in `afterRender`, after the frame's layout reads, and the\n * animation and the offset switch in that same frame. Needs a DOM.\n */\nexport function followScroll(app: Pick<AppCore, 'system' | 'onDispose'>): Follow {\n const root = document.documentElement\n const holds = new Set<() => boolean>()\n const pins = new Set<() => readonly ScrollSpan[]>()\n const id = ++instances\n let followed: { canvas: HTMLCanvasElement; computed: CSSStyleDeclaration } | undefined\n /** The site's styles keep the animation. */\n let animated = false\n /** The page scroll this frame draws at. */\n let drawnAt = 0\n /** A hold has dropped the animation. */\n let held = false\n /** The offset last written to `translate`. */\n let written = 0\n /** The spans in the keyframes and the animation name that carries them. */\n let spans: ScrollSpan[] = []\n let name = KEYFRAMES\n let version = 0\n let own: CSSStyleSheet | undefined\n app.system(\n 'layout',\n () => {\n if (!followed) return\n adoptKeyframes(own)\n // A stylesheet that drops the animation (`animation: none !important`) turns following\n // off. While held the computed name is the hold's own `none`, so the last reading stays.\n if (!held) {\n const { animationName, animationTimeline } = followed.computed\n animated =\n animationName.startsWith(KEYFRAMES) && animationTimeline?.startsWith('scroll(') !== false\n }\n // The timeline is clamped to the scroll range, rubber-band overscroll is not. The range\n // ends one visible viewport short of the bottom; on phones that grows as the toolbar hides.\n const viewport = window.visualViewport?.height ?? root.clientHeight\n const max = root.scrollHeight - Math.max(viewport, 0)\n drawnAt = animated ? Math.max(0, Math.min(window.scrollY, max, RANGE)) : 0\n },\n { name: 'stage' },\n )\n app.system(\n 'afterRender',\n () => {\n if (!followed) return\n const { canvas } = followed\n let hold = false\n if (animated) {\n for (const predicate of holds) if (predicate()) hold = true\n }\n if (animated && !hold) {\n const next = collect(pins)\n if (!sameSpans(next, spans)) {\n spans = next\n if (spans.length) {\n // A new name restarts the animation on the new keyframes in every engine.\n name = `${KEYFRAMES}-${id}-${++version % 2}`\n own ??= new CSSStyleSheet()\n own.replaceSync(pinnedKeyframes(name, spans))\n adoptKeyframes(own)\n } else {\n name = KEYFRAMES\n }\n }\n }\n const wanted = hold ? 'none' : name\n if (held !== hold || canvas.style.animationName !== wanted)\n canvas.style.animationName = wanted\n held = hold\n const offset = hold ? 0 : drawnAt - covered(spans, drawnAt)\n if (offset === written) return\n written = offset\n canvas.style.translate = offset ? `0px ${offset}px` : ''\n },\n { name: 'stage' },\n )\n app.onDispose(() => {\n if (own) document.adoptedStyleSheets = document.adoptedStyleSheets.filter((s) => s !== own)\n })\n const follow = ((canvas) => {\n const computed = startAnimation(canvas)\n if (computed) followed = { canvas, computed }\n }) as Follow\n follow.hold = (predicate) => {\n // Its own entry, so one predicate held twice needs both offs.\n const entry = (): boolean => predicate()\n holds.add(entry)\n return () => void holds.delete(entry)\n }\n follow.pin = (source) => {\n const entry = (): readonly ScrollSpan[] => source()\n pins.add(entry)\n return () => void pins.delete(entry)\n }\n return follow\n}\n\n/** All spans, clipped to the animation range, sorted, overlaps merged. */\nfunction collect(pins: Set<() => readonly ScrollSpan[]>): ScrollSpan[] {\n const all: [number, number][] = []\n for (const source of pins) {\n for (const [start, end] of source()) {\n const from = Math.max(0, start)\n const to = Math.min(RANGE, end)\n if (to > from) all.push([from, to])\n }\n }\n all.sort((a, b) => a[0] - b[0])\n const merged: [number, number][] = []\n for (const span of all) {\n const last = merged.at(-1)\n if (last && span[0] <= last[1]) last[1] = Math.max(last[1], span[1])\n else merged.push(span)\n }\n return merged\n}\n\nconst sameSpans = (a: readonly ScrollSpan[], b: readonly ScrollSpan[]): boolean =>\n a.length === b.length &&\n a.every(([start, end], i) => {\n const [from, to] = b[i] as ScrollSpan\n return Math.abs(start - from) < SPAN_TOLERANCE && Math.abs(end - to) < SPAN_TOLERANCE\n })\n\n/** Scroll below `at` that falls inside the spans. */\nfunction covered(spans: readonly ScrollSpan[], at: number): number {\n let sum = 0\n for (const [start, end] of spans) sum += Math.max(0, Math.min(at, end) - start)\n return sum\n}\n\n/** Keyframes that move by the scroll outside the spans and stand still inside them. */\nfunction pinnedKeyframes(name: string, spans: readonly ScrollSpan[]): string {\n const frame = (at: number, by: number): string =>\n `${((at / RANGE) * 100).toFixed(6)}%{transform:translateY(${-by}px)}`\n const frames = [frame(0, 0)]\n let still = 0\n for (const [start, end] of spans) {\n frames.push(frame(start, start - still))\n still += end - start\n frames.push(frame(end, end - still))\n }\n frames.push(frame(RANGE, RANGE - still))\n return `@keyframes ${name}{${frames.join('')}}`\n}\n\n/** Adopts the keyframes, again if a site reassigns `document.adoptedStyleSheets`. */\nfunction adoptKeyframes(own?: CSSStyleSheet): void {\n if (!sheet) {\n sheet = new CSSStyleSheet()\n sheet.replaceSync(`@keyframes ${KEYFRAMES} { to { transform: translateY(-${RANGE}px) } }`)\n }\n const sheets = document.adoptedStyleSheets\n const missing = [sheet, own].filter((s): s is CSSStyleSheet => !!s && !sheets.includes(s))\n if (missing.length) document.adoptedStyleSheets = [...sheets, ...missing]\n}\n\n/** Starts the scroll-timeline animation on `canvas`. `undefined` if the engine lacks it. */\nfunction startAnimation(canvas: HTMLCanvasElement): CSSStyleDeclaration | undefined {\n // Engines with scroll timelines (Chrome 115, Safari 26) all have constructable stylesheets.\n if (typeof CSS === 'undefined' || !CSS.supports?.('animation-timeline: scroll(root y)')) return\n adoptKeyframes()\n canvas.style.cssText +=\n `animation:${KEYFRAMES} linear both;` +\n `animation-timeline:scroll(root y);animation-range:0px ${RANGE}px`\n return getComputedStyle(canvas)\n}\n","import { DioramaError } from '../kernel/errors'\nimport { definePlugin } from '../kernel/plugin'\nimport { batch, signal } from '../kernel/signals'\nimport type { Off, Plugin, ReadonlySignal } from '../kernel/types'\nimport { noop } from '../kernel/util'\nimport { onBodySwap } from './body'\nimport { followScroll, type ScrollSpan } from './follow'\n\nexport type { ScrollSpan } from './follow'\n\n/** Options of the `stage` plugin. */\nexport interface StageOptions {\n /**\n * Canvas or selector to draw into. By default a fixed full-viewport canvas is created. A\n * selector that matches no canvas fails the plugin with `PLUGIN_OPTIONS`.\n */\n readonly canvas: HTMLCanvasElement | string | undefined\n /** z-index of the created canvas. It sits above content, which stays interactive. Default 1. */\n readonly zIndex: number\n /** Upper bound for the device pixel ratio. Default 2. */\n readonly maxPixelRatio: number\n /**\n * Keeps GL copies on their elements while the browser scrolls the page ahead of the next frame\n * (keyboard, scrollbar, native wheel, touch). The created canvas moves with the page on the\n * compositor until the frame lands, and GL content fixed to the viewport moves with it for that\n * time. Inside `stage.pin` spans (effects: a pinned sticky stage of a scroll section) and while\n * a `stage.hold` predicate is true the canvas stays fixed to the viewport instead. Vertical page\n * scroll only. Needs CSS scroll-driven animations. Default true.\n */\n readonly followScroll: boolean\n}\n\n/** The `stage` service: the canvas and the viewport. */\nexport interface StageApi {\n /** The page-wide canvas, created on first access. `undefined` without a DOM. */\n readonly canvas: HTMLCanvasElement | undefined\n /** Viewport width in CSS px, excluding scrollbars. */\n readonly width: ReadonlySignal<number>\n /**\n * Viewport height in CSS px: the large viewport of CSS `100lvh` (`100vh`), so on phones the\n * height with the browser toolbar hidden. It stays put while the toolbar slides, and the\n * created canvas is that tall.\n */\n readonly height: ReadonlySignal<number>\n /** Device pixel ratio, capped by `maxPixelRatio`. */\n readonly pixelRatio: ReadonlySignal<number>\n /** Whether the user prefers reduced motion. */\n readonly reducedMotion: ReadonlySignal<boolean>\n /**\n * Keeps the created canvas from following scroll (`followScroll`) while `held()` is true:\n * for content fixed to the viewport. Read once per frame after the frame is drawn; the switch\n * lands with that frame. Returns a function that removes the predicate. Without following it\n * does nothing.\n */\n hold(held: () => boolean): Off\n /**\n * Scroll spans, in page px from the top, over which content on screen stands still, such as a\n * pinned sticky stage from where it sticks to where it lets go. The created canvas stops\n * following inside them on the compositor, so it stops and starts where CSS sticky does, also\n * between frames. Read once per frame after the frame is drawn. Returns a function that\n * removes the source. Without following it does nothing.\n */\n pin(spans: () => readonly ScrollSpan[]): Off\n}\n\nconst defaults: StageOptions = {\n canvas: undefined,\n zIndex: 1,\n maxPixelRatio: 2,\n followScroll: true,\n}\n\n/** The large viewport, with the fallback for engines without `lvh` first. */\nconst LARGE = ['100vh', '100lvh'] as const\n\n/** Height of the large viewport in CSS px, 0 where it cannot be measured. */\nfunction largeViewport(): number {\n const probe = document.createElement('div')\n probe.style.cssText = `position:fixed;top:0;left:0;width:0;visibility:hidden;pointer-events:none;height:${LARGE[0]};height:${LARGE[1]}`\n // Outside <body>, so routers that swap it and observers of it never see the probe.\n document.documentElement.append(probe)\n const { height } = probe.getBoundingClientRect()\n probe.remove()\n return height\n}\n\n/** Canvases created by live apps. Any other `canvas[data-dio-canvas]` is a stale clone. */\nconst liveCanvases = new WeakSet<Element>()\n\n/** One canvas for the whole site. It outlives page transitions. */\nexport const stage: Plugin<'stage', StageOptions> = /*#__PURE__*/ definePlugin({\n name: 'stage',\n defaults,\n setup(app, options): StageApi {\n const width = signal(0)\n const height = signal(0)\n const pixelRatio = signal(1)\n const reducedMotion = signal(false)\n const api: StageApi = {\n canvas: undefined,\n width,\n height,\n pixelRatio,\n reducedMotion,\n hold: () => noop,\n pin: () => noop,\n }\n if (typeof document === 'undefined') return api\n\n const root = document.documentElement\n const measure = (): void => {\n batch(() => {\n width.value = root.clientWidth\n height.value = Math.max(root.clientHeight, largeViewport())\n pixelRatio.value = Math.min(window.devicePixelRatio || 1, options.maxPixelRatio)\n })\n app.invalidate()\n }\n measure()\n const listen = { signal: app.abortSignal }\n window.addEventListener('resize', measure, listen)\n\n const reduceQuery = window.matchMedia?.('(prefers-reduced-motion: reduce)')\n if (reduceQuery) {\n const update = (): void => {\n reducedMotion.value = reduceQuery.matches\n }\n update()\n reduceQuery.addEventListener('change', update, listen)\n }\n\n const follow = followScroll(app)\n\n let canvas: HTMLCanvasElement | undefined\n // Runs once for a canvas the plugin created: it follows scroll and lives as long as the app.\n const adopt = (created: HTMLCanvasElement): void => {\n if (options.followScroll) follow(created)\n liveCanvases.add(created)\n app.onDispose(() => {\n liveCanvases.delete(created)\n created.remove()\n })\n // A replaced <body> takes the canvas with it, so move it into the new one.\n onBodySwap(app, (body) => {\n // Clones from a cached snapshot are dead full-screen canvases.\n for (const clone of body.querySelectorAll('canvas[data-dio-canvas]')) {\n if (!liveCanvases.has(clone)) clone.remove()\n }\n if (!created.isConnected) body.append(created)\n app.invalidate()\n })\n }\n return {\n ...api,\n hold: follow.hold,\n pin: follow.pin,\n get canvas() {\n canvas ??= resolveCanvas(options, adopt)\n return canvas\n },\n }\n },\n})\n\n/** The canvas of `options.canvas`, or a new full-viewport one passed to `adopt`. */\nfunction resolveCanvas(\n options: StageOptions,\n adopt: (created: HTMLCanvasElement) => void,\n): HTMLCanvasElement {\n const { canvas } = options\n if (canvas instanceof HTMLCanvasElement) return canvas\n if (typeof canvas === 'string') {\n const found = document.querySelector(canvas)\n if (found instanceof HTMLCanvasElement) return found\n throw new DioramaError('PLUGIN_OPTIONS', `no canvas matches \"${canvas}\"`, { plugin: 'stage' })\n }\n const created = document.createElement('canvas')\n created.setAttribute('aria-hidden', 'true')\n // Turbo drops temporary elements from its snapshots. The marker finds clones made otherwise.\n created.setAttribute('data-dio-canvas', '')\n created.setAttribute('data-turbo-temporary', '')\n Object.assign(created.style, {\n position: 'fixed',\n inset: '0',\n width: '100%',\n height: LARGE[0],\n pointerEvents: 'none',\n zIndex: String(options.zIndex),\n })\n // On phones a full-height fixed box resizes as the toolbar slides; the large viewport does not.\n created.style.height = LARGE[1]\n document.body.append(created)\n adopt(created)\n return created\n}\n","import { definePlugin } from '../kernel/plugin'\nimport { signal } from '../kernel/signals'\nimport type { Off, Plugin, ReadonlySignal } from '../kernel/types'\n\n/** The `visibility` service. */\nexport interface VisibilityApi {\n /** Whether the tab is visible. */\n readonly visible: ReadonlySignal<boolean>\n}\n\n/** Options of the `visibility` plugin. */\nexport interface VisibilityOptions {\n /** Pause the frame loop while the tab is hidden. Default true. */\n readonly pause: boolean\n}\n\nconst defaults: VisibilityOptions = { pause: true }\n\n/** Tracks tab visibility and pauses frames while the tab is hidden. Built in. */\nexport const visibility: Plugin<'visibility', VisibilityOptions> = /*#__PURE__*/ definePlugin({\n name: 'visibility',\n defaults,\n setup(app, options): VisibilityApi {\n const visible = signal(true)\n if (typeof document === 'undefined') return { visible }\n // Releases the pause taken while the tab is hidden.\n let resume: Off | undefined\n const update = (): void => {\n visible.value = document.visibilityState !== 'hidden'\n if (!visible.peek() && options.pause) resume ??= app.pause('hidden')\n else if (resume) {\n resume()\n resume = undefined\n }\n }\n update()\n document.addEventListener('visibilitychange', update, { signal: app.abortSignal })\n return { visible }\n },\n})\n","import { createKernelApp } from './kernel/app'\nimport type {\n AnyPlugin,\n App,\n AppOptions,\n PluginEntry,\n PresetEntry,\n PresetPlugins,\n ServicesOf,\n} from './kernel/types'\nimport { anchors } from './web/anchors'\nimport { pointer } from './web/pointer'\nimport { scroll } from './web/scroll'\nimport { stage } from './web/stage'\nimport { visibility } from './web/visibility'\n\nexport { manualDriver, offlineDriver, rafDriver, tickerDriver } from './kernel/drivers'\nexport { DioramaError, isDioramaError } from './kernel/errors'\nexport { cancel, isCancel } from './kernel/hooks'\nexport { definePlugin, definePreset } from './kernel/plugin'\nexport { satisfies } from './kernel/semver'\nexport { batch, computed, effect, signal, untracked } from './kernel/signals'\nexport * from './kernel/types'\nexport { VERSION } from './version'\nexport { type Anchor, type AnchorsApi, anchors, type TrackOptions } from './web/anchors'\nexport { type PointerApi, type PointerState, pointer } from './web/pointer'\nexport {\n type ScrollApi,\n type ScrollAxis,\n type ScrollSample,\n type ScrollSource,\n type ScrollState,\n scroll,\n} from './web/scroll'\nexport { type ScrollSpan, type StageApi, type StageOptions, stage } from './web/stage'\nexport { type VisibilityApi, type VisibilityOptions, visibility } from './web/visibility'\n\n/** Built-in web layer, in start order. Disable one with `disable`, or all with `defaults: false`. */\nconst WEB_DEFAULTS = [\n visibility,\n stage,\n scroll,\n pointer,\n anchors,\n] as unknown as readonly AnyPlugin[]\n\n/**\n * Creates an app with the built-in web layer and the given presets and plugins. Call `start()` to\n * run it.\n */\nexport function createApp<\n const P extends readonly PresetEntry[] = [],\n const E extends readonly PluginEntry[] = [],\n>(\n options?: AppOptions<P, E>,\n): App<ServicesOf<PresetPlugins<P[number]> | Extract<E[number], AnyPlugin>>> {\n return createKernelApp(options as AppOptions | undefined, WEB_DEFAULTS) as App<\n ServicesOf<PresetPlugins<P[number]> | Extract<E[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