brumate 0.8.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{boot-BkUdiYOF.d.ts → boot-ej-9NRT3.d.ts} +20 -2
- package/dist/cli.js +88 -82
- package/dist/cli.js.map +1 -1
- package/dist/{client-B0FXW5Kw.js → client-B-ww-PQ7.js} +402 -63
- package/dist/client-B-ww-PQ7.js.map +1 -0
- package/dist/{client-Cq6aTiDs.d.ts → client-Do6IBIhI.d.ts} +58 -14
- package/dist/{defer-BMIMP4Hq.js → defer-JD2FK9mV.js} +5 -3
- package/dist/defer-JD2FK9mV.js.map +1 -0
- package/dist/{devtools-calls-DGW6nLZ2.js → devtools-calls-DCjuSkim.js} +3 -3
- package/dist/{devtools-calls-DGW6nLZ2.js.map → devtools-calls-DCjuSkim.js.map} +1 -1
- package/dist/{devtools-panel-B1nF1KB7.js → devtools-panel-DLeWTPhU.js} +4 -4
- package/dist/{devtools-panel-B1nF1KB7.js.map → devtools-panel-DLeWTPhU.js.map} +1 -1
- package/dist/{devtools-B4prrxht.js → devtools-tuq7ATGN.js} +10 -7
- package/dist/devtools-tuq7ATGN.js.map +1 -0
- package/dist/{error-catalog-DakxjSgj.js → error-catalog-BBWB7w-E.js} +11 -4
- package/dist/error-catalog-BBWB7w-E.js.map +1 -0
- package/dist/{error-catalog-VxLbz-6p.js → error-catalog-CbmQqfat.js} +1 -1
- package/dist/{events-LgLdp1R7.js → events-BDVITj3P.js} +3 -5
- package/dist/events-BDVITj3P.js.map +1 -0
- package/dist/{features-DwMYKBIC.js → features-Cte5aj20.js} +8 -2
- package/dist/features-Cte5aj20.js.map +1 -0
- package/dist/{files-D5GtxwEQ.js → files-Bz0lAQzD.js} +2 -2
- package/dist/{files-D5GtxwEQ.js.map → files-Bz0lAQzD.js.map} +1 -1
- package/dist/{html-Cf5uKhLs.js → html-BYuHDvxy.js} +10 -3
- package/dist/html-BYuHDvxy.js.map +1 -0
- package/dist/index.d.ts +71 -19
- package/dist/index.js +3 -3
- package/dist/{inspect-CGl5Y8q6.js → inspect-fpaBJ5pm.js} +1305 -75
- package/dist/inspect-fpaBJ5pm.js.map +1 -0
- package/dist/{loader-BsaSuIoG.js → loader-DMxuZ6He.js} +14 -6
- package/dist/loader-DMxuZ6He.js.map +1 -0
- package/dist/{navigate-BlowKvhB.js → navigate-C5PjwYMh.js} +108 -20
- package/dist/navigate-C5PjwYMh.js.map +1 -0
- package/dist/{produce-CLABZ8k2.d.ts → produce-BDkCsGH7.d.ts} +3 -3
- package/dist/{rpc-C1jYVNAe.js → rpc-DOdrekhP.js} +23 -13
- package/dist/rpc-DOdrekhP.js.map +1 -0
- package/dist/runtime/bundles.d.ts +3 -2
- package/dist/runtime/bundles.js +20 -5
- package/dist/runtime/bundles.js.map +1 -1
- package/dist/runtime/client.d.ts +4 -3
- package/dist/runtime/client.js +5 -5
- package/dist/runtime/devtools.d.ts +3 -1
- package/dist/runtime/devtools.js +1 -1
- package/dist/runtime/events.js +1 -1
- package/dist/runtime/hot.d.ts +1 -1
- package/dist/runtime/html.js +1 -1
- package/dist/runtime/loader.d.ts +2 -2
- package/dist/runtime/loader.js +2 -2
- package/dist/runtime/otel.d.ts +18 -0
- package/dist/runtime/otel.js +127 -0
- package/dist/runtime/otel.js.map +1 -0
- package/dist/runtime/server.d.ts +4 -3
- package/dist/runtime/server.js +5 -5
- package/dist/runtime/signals.d.ts +2 -2
- package/dist/runtime/signals.js +4 -1
- package/dist/runtime/signals.js.map +1 -1
- package/dist/runtime/static-loader.d.ts +2 -2
- package/dist/runtime/static-loader.js +1 -1
- package/dist/runtime/store.d.ts +2 -2
- package/dist/runtime/store.js +1 -1
- package/dist/runtime/testing.d.ts +2 -2
- package/dist/runtime/testing.js +2 -2
- package/dist/search-params-qGERTLi3.js +382 -0
- package/dist/search-params-qGERTLi3.js.map +1 -0
- package/dist/{serial-ribg9NAj.js → serial-B2AJ9VGx.js} +1 -1
- package/dist/{serial-ioa17MuY.js → serial-Cj6pDGOq.js} +6 -6
- package/dist/{serial-ioa17MuY.js.map → serial-Cj6pDGOq.js.map} +1 -1
- package/dist/{server-DesBZv5g.d.ts → server-2-LS_KFo.d.ts} +125 -9
- package/dist/{server-BUuf7XPZ.js → server-CRGZMWnK.js} +545 -236
- package/dist/server-CRGZMWnK.js.map +1 -0
- package/dist/{shared-CX_YacDm.js → shared-CUBWrbiM.js} +4 -4
- package/dist/{shared-CX_YacDm.js.map → shared-CUBWrbiM.js.map} +1 -1
- package/dist/sheets-B9Zr50mf.js +105 -0
- package/dist/sheets-B9Zr50mf.js.map +1 -0
- package/dist/{signals-7VVD9C_H.d.ts → signals-BgsJK-uT.d.ts} +16 -6
- package/dist/{static-loader-C_en-4v8.js → static-loader-BDBtWsdg.js} +107 -19
- package/dist/static-loader-BDBtWsdg.js.map +1 -0
- package/dist/{static-loader-UKnK11Em.d.ts → static-loader-CAFn6p0l.d.ts} +2 -2
- package/dist/{store-9_oa0HG1.d.ts → store-BwWg-Iei.d.ts} +79 -2
- package/dist/store-DNr24Z8L.js +950 -0
- package/dist/store-DNr24Z8L.js.map +1 -0
- package/dist/{stream-read-BTsYstJY.js → stream-read-CiLDH60b.js} +2 -2
- package/dist/{stream-read-BTsYstJY.js.map → stream-read-CiLDH60b.js.map} +1 -1
- package/dist/{stream-read-Dek3HnqO.js → stream-read-DVoregpA.js} +1 -1
- package/dist/trace-DT7RGRAV.d.ts +52 -0
- package/dist/trace-browser-C7MFMove.js +170 -0
- package/dist/trace-browser-C7MFMove.js.map +1 -0
- package/dist/trace-flag-Dy267snx.js +7 -0
- package/dist/trace-flag-Dy267snx.js.map +1 -0
- package/dist/{trusted-g_zUJbh2.js → trusted-Bmwg4_hf.js} +12 -5
- package/dist/trusted-Bmwg4_hf.js.map +1 -0
- package/dist/view-transitions-BpnVwtS4.js +141 -0
- package/dist/view-transitions-BpnVwtS4.js.map +1 -0
- package/dist/vite.d.ts +8 -1
- package/dist/vite.js +356 -46
- package/dist/vite.js.map +1 -1
- package/elements.d.ts +8 -0
- package/package.json +13 -1
- package/skills/brumate/SKILL.md +9 -5
- package/skills/brumate/references/errors.md +95 -14
- package/skills/brumate/references/events.md +27 -1
- package/skills/brumate/references/signals.md +4 -4
- package/skills/brumate/references/state.md +79 -4
- package/skills/brumate/references/syntax.md +58 -9
- package/dist/client-B0FXW5Kw.js.map +0 -1
- package/dist/defer-BMIMP4Hq.js.map +0 -1
- package/dist/devtools-B4prrxht.js.map +0 -1
- package/dist/error-catalog-DakxjSgj.js.map +0 -1
- package/dist/events-LgLdp1R7.js.map +0 -1
- package/dist/features-DwMYKBIC.js.map +0 -1
- package/dist/html-Cf5uKhLs.js.map +0 -1
- package/dist/inspect-CGl5Y8q6.js.map +0 -1
- package/dist/loader-BsaSuIoG.js.map +0 -1
- package/dist/navigate-BlowKvhB.js.map +0 -1
- package/dist/rpc-C1jYVNAe.js.map +0 -1
- package/dist/search-params-Wg-0FsMj.js +0 -148
- package/dist/search-params-Wg-0FsMj.js.map +0 -1
- package/dist/server-BUuf7XPZ.js.map +0 -1
- package/dist/static-loader-C_en-4v8.js.map +0 -1
- package/dist/store-Cy4EEyZ7.js +0 -439
- package/dist/store-Cy4EEyZ7.js.map +0 -1
- package/dist/trusted-g_zUJbh2.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"store-DNr24Z8L.js","names":[],"sources":["../src/runtime/store.ts"],"sourcesContent":["// Stores: values that change, which a context can hold while the context itself stays the same.\n// `$toStore` makes the store of a provider, and `$store` reads one in a component. The page state\n// sends only the value of a store; the browser makes a new store for it.\n\nimport type { Context } from './context.ts';\nimport { HAS_BRIDGES } from './features.ts';\n\n/** The pass of the core, which the browser sets, so a store's readers update in one pass. */\nconst PASS = Symbol.for('brumate.pass');\n\n/** True for a context, which `createContext` made. */\nexport function isContext(value: unknown): value is Context<unknown> {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as { key?: unknown }).key === 'string' &&\n Object.keys(value).length === 1 &&\n !isContract(value)\n );\n}\n\n/**\n * The store that `$store` reads: `value` is the store, or for `path` an object that holds it there.\n * `key` names the context that gave `value`, for the message. Throws a `TypeError` for a value that\n * is no store, such as `undefined` or a context, and for `write` on a store that has no `set`.\n */\nexport function findStored(\n value: unknown,\n path: string | undefined,\n write: boolean | undefined,\n key?: string,\n): StoreLike<unknown> {\n const found = path === undefined ? value : (value as Record<string, unknown> | undefined)?.[path];\n if (!isContract(found)) {\n // A context is the most likely mistake, so its message names the read that gives its store.\n if (isContext(found)) {\n throw new TypeError(\n `$store reads the context \"${found.key}\", which is no store. Read the store in it with $store($getContext(Context))`,\n );\n }\n throw new TypeError(\n `$store reads ${key === undefined ? 'a value' : `the context \"${key}\"`}${path === undefined ? '' : ` at \"${path}\"`}, which gives no store: a store has the functions get and subscribe`,\n );\n }\n if (write && !canSet(found)) {\n throw new TypeError(\n `let $store(${key ?? '…'}) writes the store, but the store has no set. Read it with const`,\n );\n }\n return found;\n}\n\n/**\n * The error of `$store` for a store of another library in a value that the page sends, such as a\n * prop: only the value of a store of `brumate/store` crosses. The fix is said here only.\n */\nexport function sentForeignStore(component: string, value: string): Error {\n return new Error(\n `$store in ${component} reads a store of another library from ${value}, which the page sends, and only a store of brumate/store crosses. Wrap the library's store with bridge() in a module, or read it from an import, <script module> or a call in this component`,\n );\n}\n\n/** Where `$toStore` made a store: its scope, the ID of its site, and the slot of its signal. */\nexport type StoreOrigin = [scope: number | string, site: number, slot?: number];\n\n/**\n * The contract of a store, which `$store` reads: `get`, `subscribe` (which returns the function\n * that stops it, and does not call the listener at once) and, for a two-way binding, `set`.\n */\nexport interface StoreLike<T> {\n get(): T;\n subscribe(listener: (value: T) => void): () => void;\n set?(value: T): void;\n}\n\n/** A value that changes, with the functions that read it and write it. */\nexport class Store<T> implements StoreLike<T> {\n /** The value. */\n v: T;\n /** The functions that `subscribe` added. */\n l: Set<(value: T) => void> = new Set();\n /** For a store of `$toStore(signal)`, the write of the signal, which the browser sets. */\n w?: (value: T) => void;\n /** True for a store of `$toStore(memo)`, which only its provider writes. */\n r?: boolean;\n /** Where `$toStore` made it, for the page state. */\n o?: StoreOrigin;\n /** True for a store of `$toStore` in the browser until its first update. */\n f?: boolean;\n /**\n * The mark of a store, which `isStore` reads in every copy of the runtime. A field, so a build\n * without stores drops the class.\n */\n k = 'brumate.store' as const;\n\n constructor(value: T) {\n this.v = value;\n }\n\n /** The current value. */\n get(): T {\n return this.v;\n }\n\n /** Calls `listener` with each new value. Returns the function that stops it. */\n subscribe(listener: (value: T) => void): () => void {\n this.l.add(listener);\n return () => {\n this.l.delete(listener);\n };\n }\n\n /**\n * Writes the value, and calls the listeners when it changed. A store of `$toStore(signal)`\n * writes the signal, and a store of a memo throws.\n */\n set(value: T): void {\n if (this.r) {\n throw new Error('This store follows a memo, so only its provider writes it');\n }\n if (Object.is(this.v, value)) {\n return;\n }\n if (this.w) {\n this.v = value;\n this.w(value);\n return;\n }\n sendStore(this, value);\n }\n}\n\n/** True for a store of `brumate/store`, of any copy of the runtime. */\nexport function isStore(value: unknown): value is Store<unknown> {\n return (\n typeof value === 'object' && value !== null && (value as { k?: unknown }).k === 'brumate.store'\n );\n}\n\n/** True for a value with the functions `get` and `subscribe` of the store contract. */\nexport function isContract(value: unknown): value is StoreLike<unknown> {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as { get?: unknown }).get === 'function' &&\n typeof (value as { subscribe?: unknown }).subscribe === 'function'\n );\n}\n\n/** True for a value of the store contract that is not a store of brumate. */\nexport function isForeignStore(value: unknown): boolean {\n return isContract(value) && !isStore(value) && !(HAS_BRIDGES && isBridged(value));\n}\n\n/** True when `$store` can write the store: it has `set`, and is not the store of a memo. */\nexport function canSet(value: StoreLike<unknown>): boolean {\n return typeof value.set === 'function' && !(value as Store<unknown>).r;\n}\n\n/** Makes a store, such as one that a module holds for the whole app. */\nexport function store<T>(value: T): Store<T> {\n return new Store(value);\n}\n\n/** Writes the value of a store and calls its listeners, in one pass of the page. */\nexport function sendStore<T>(target: Store<T>, value: T, force?: boolean): void {\n // The listeners hear of a change only. A provider's update forces it, since a `set` of\n // `$toStore(signal)` wrote the value before the signal's update came.\n if (!force && Object.is(target.v, value)) {\n return;\n }\n target.v = value;\n const listeners = () => {\n for (const listener of target.l) {\n listener(value);\n }\n };\n const pass = (globalThis as { [key: symbol]: (<R>(run: () => R) => R) | undefined })[PASS];\n if (pass) {\n pass(listeners);\n } else {\n listeners();\n }\n}\n\n// Derived stores: a read-only store that computes its value from other stores, with the API of\n// Svelte 4's `derived`.\n\n/** The stores that `derived` reads: one store, or an array of them. */\nexport type Stores = StoreLike<any> | [StoreLike<any>, ...StoreLike<any>[]] | StoreLike<any>[];\n\n/** The values of `Stores`: a value for one store, an array of values for an array. */\nexport type StoresValues<S> =\n S extends StoreLike<infer U>\n ? U\n : { [K in keyof S]: S[K] extends StoreLike<infer U> ? U : never };\n\n/** The derived stores that heard of a change and wait to compute. */\nconst waiting: Computed[] = [];\n/** The listener sets that have a trailing listener, which computes the waiting stores. */\nconst armed = new Set<Set<unknown>>();\n/** True while the waiting stores compute. */\nlet flushing = false;\n\n/** Computes the waiting derived stores, the ones that read the fewest derived stores first. */\nfunction flushComputed(): void {\n flushing = true;\n try {\n while (waiting.length > 0) {\n let next = 0;\n for (let i = 1; i < waiting.length; i++) {\n if (waiting[i]!.level < waiting[next]!.level) {\n next = i;\n }\n }\n const [computed] = waiting.splice(next, 1);\n computed!.waits = false;\n computed!.run();\n }\n } catch (error) {\n // The stores that still wait would never hear a source again, so they leave the queue.\n for (const computed of waiting) {\n computed.waits = false;\n }\n waiting.length = 0;\n throw error;\n } finally {\n flushing = false;\n }\n}\n\n/** The state of a derived store while it has subscribers. */\ninterface Computed {\n /** The number of derived stores below it, so a store computes after the ones it reads. */\n level: number;\n /** True while it waits in the queue. */\n waits: boolean;\n run(): void;\n}\n\n/**\n * Queues a derived store that a source told of a change. The store waits until the source has\n * called all its listeners, so a store that reads this one and the source computes once, after\n * this one.\n */\nfunction enqueue(state: Computed, source: StoreLike<unknown>): void {\n if (state.waits) {\n return;\n }\n state.waits = true;\n waiting.push(state);\n if (flushing) {\n return;\n }\n const listeners = (source as Partial<Store<unknown>>).l;\n if (!listeners || armed.has(listeners)) {\n if (!listeners) {\n // A store of another library has no listeners to wait behind.\n flushComputed();\n }\n return;\n }\n // A listener added now runs after the ones of the source, in the same send.\n const trail = (): void => {\n listeners.delete(trail);\n armed.delete(listeners);\n flushComputed();\n };\n armed.add(listeners);\n listeners.add(trail as never);\n}\n\n/**\n * A store computed from `sources`. With a function of one parameter, the result is the value. With\n * two or three, the function calls `set` or `update`, and a function it returns runs before the\n * next call and when the last subscriber leaves. It follows its sources only while it has\n * subscribers; `get` computes from the sources otherwise. A source change that reaches it in one\n * pass computes it once, after the stores it reads.\n */\nexport function derived<S extends Stores, T>(\n sources: S,\n fn: (\n values: StoresValues<S>,\n set: (value: T) => void,\n update: (change: (value: T) => T) => void,\n ) => (() => void) | void,\n initial?: T,\n): StoreLike<T>;\nexport function derived<S extends Stores, T>(\n sources: S,\n fn: (values: StoresValues<S>) => T,\n initial?: T,\n): StoreLike<T>;\nexport function derived<T>(\n sources: Stores,\n fn: (\n values: unknown,\n set: (value: T) => void,\n update: (change: (value: T) => T) => void,\n ) => unknown,\n initial?: T,\n): StoreLike<T> {\n const single = !Array.isArray(sources);\n const list: StoreLike<unknown>[] = single ? [sources] : sources;\n for (const source of list) {\n if (!source) {\n throw new Error('derived() expects stores as input, got a falsy value');\n }\n }\n const auto = fn.length < 2;\n const out = new Store<T>(initial as T);\n const subscribers = new Set<() => void>();\n let level = 1;\n // Present only when a source can be pending.\n const pend: Pendable = {};\n for (const source of list) {\n level = Math.max(level, ((source as { d?: number }).d ?? 0) + 1);\n if (pendingOf(source)) {\n pend.q = new Set();\n }\n }\n\n // The state of one run: `cleanup` is what `fn` returned, and `write` is where `set` goes.\n let cleanup: (() => void) | undefined;\n let started = false;\n let starting = false;\n let stops: (() => void)[] = [];\n\n /** Runs `fn` over the current values of the sources. */\n const compute = (write: (value: T) => void): void => {\n const values: unknown[] = [];\n for (const source of list) {\n values.push(source.get());\n }\n const set = write;\n const update = (change: (value: T) => T): void => write(change(out.v));\n cleanup?.();\n cleanup = undefined;\n const result = fn(single ? values[0] : values, set, update);\n if (auto) {\n write(result as T);\n } else if (typeof result === 'function') {\n cleanup = result as () => void;\n }\n };\n\n // The value is written without a notice while the first subscriber starts it, since nobody\n // listens yet and `subscribe` does not call the listener.\n const send = (value: T): void => {\n if (starting) {\n out.v = value;\n } else if (started) {\n sendStore(out, value);\n } else {\n // A late `set` after the last subscriber left keeps its value, as Svelte's store does.\n out.v = value;\n }\n };\n\n const state: Computed = {\n level,\n waits: false,\n run() {\n if (started) {\n compute(send);\n }\n },\n };\n\n /** Called by a source. */\n const heard = (source: StoreLike<unknown>): void => {\n if (started) {\n enqueue(state, source);\n }\n };\n\n const start = (): void => {\n starting = true;\n started = true;\n try {\n compute(send);\n for (const source of list) {\n stops.push(source.subscribe(() => heard(source)));\n }\n // A store that reads a pending store is pending while it is.\n if (pend.q) {\n const check = (): void => {\n let pending = false;\n for (const source of list) {\n pending ||= !!pendingOf(source)?.n;\n }\n setPending(pend, pending);\n };\n for (const source of list) {\n const q = pendingOf(source)?.q;\n if (q) {\n q.add(check);\n stops.push(() => q.delete(check));\n }\n }\n check();\n }\n } catch (error) {\n // A store that failed to start has no subscriptions, so it can start again.\n started = false;\n for (const end of stops) {\n end();\n }\n stops = [];\n cleanup?.();\n cleanup = undefined;\n throw error;\n } finally {\n starting = false;\n }\n };\n\n const stop = (): void => {\n started = false;\n for (const end of stops) {\n end();\n }\n stops = [];\n cleanup?.();\n cleanup = undefined;\n if (state.waits) {\n state.waits = false;\n waiting.splice(waiting.indexOf(state), 1);\n }\n };\n\n const result = Object.assign(\n {\n get(): T {\n if (started) {\n return out.v;\n }\n // No subscriber: compute once from the sources and stop. The async form keeps the\n // initial value until `set` runs.\n let value = out.v;\n started = true;\n try {\n compute((next) => {\n value = next;\n });\n } finally {\n started = false;\n cleanup?.();\n cleanup = undefined;\n }\n return value;\n },\n subscribe(listener: (value: T) => void): () => void {\n const stopListening = out.subscribe(listener);\n if (!started) {\n try {\n start();\n } catch (error) {\n stopListening();\n throw error;\n }\n }\n subscribers.add(stopListening);\n return () => {\n if (subscribers.delete(stopListening)) {\n stopListening();\n if (subscribers.size === 0) {\n stop();\n }\n }\n };\n },\n },\n { d: level },\n );\n if (pend.q) {\n Object.defineProperty(result, PENDING, { value: pend });\n }\n return result;\n}\n\n/** The key of a store that holds the error of a run, which `$store` reads again on each notice. */\nexport const HOLDS: unique symbol = Symbol.for('brumate.holds') as never;\n\n/**\n * The key of the pending state of a store, which a store of a module can hold, as a memo that\n * loads is pending. `$isPending` and `$resolve` read it in a component.\n */\nexport const PENDING: unique symbol = Symbol.for('brumate.pending') as never;\n\n/** The pending state: `n` is true while the store waits, and `q` holds the functions that hear of it. */\nexport interface Pendable {\n n?: boolean;\n q?: Set<(pending: boolean) => void>;\n}\n\n/** The pending state of a store, when it has one. */\nexport function pendingOf(store: unknown): Pendable | undefined {\n const state = (store as { [PENDING]?: Pendable } | null)?.[PENDING];\n return state?.q instanceof Set ? state : undefined;\n}\n\n/** Sets the pending flag of a store, and tells its listeners when it changed. */\nfunction setPending(target: Pendable, pending: boolean): void {\n if (!!target.n !== pending) {\n target.n = pending;\n for (const listener of target.q!) {\n listener(pending);\n }\n }\n}\n\n/** True on the server, or in a test while server code runs. */\nexport function onServer(): boolean {\n const inRequest = (globalThis as Record<symbol, (() => boolean) | undefined>)[\n Symbol.for('brumate.inRequest')\n ];\n return typeof document === 'undefined' || inRequest?.() === true;\n}\n\n// The forms of a module: `$memo`, `$gate`, `$debounced` and `$throttled` at the top level of a\n// module compile to `memoStore`. Its value can load, as the value of a memo of a component can: a\n// promise, or an async iterable whose values it takes in turn. One load serves every reader of the\n// process. The compiler calls it, so it has no docs of its own.\n\n/** Thrown by a read of a memo of a module whose first value still loads. It carries the load. */\nexport class Waiting extends Error {\n /** The load, which settles when the memo has its value or its error. */\n readonly load: Promise<unknown>;\n\n constructor(load: Promise<unknown>) {\n super(\n 'This value is still loading. Wait for it with await $resolve(memo), or check $isPending(memo) first',\n );\n this.load = load;\n }\n}\n\n/** The store that a component that imports a memo of a module reads with `$store`. */\nexport interface MemoFace extends StoreLike<unknown> {\n /** The value that the server rendered, which the browser takes on resume. */\n s(value: unknown): void;\n [HOLDS]: true;\n}\n\n/** The options of the forms other than `$memo`. */\nexport interface MemoOptions<T> {\n /** `$gate`: keeps the value while a subscriber holds the store and this returns false. */\n g?: (prev: T, next: T) => boolean;\n /** `$debounced` and `$throttled`: the wait in milliseconds, in the browser. */\n m?: number;\n /** `$throttled`: at most one value per wait, in place of the value after the last change. */\n t?: boolean;\n /** The names of the sources, which the page state sends for a value that loaded. */\n n?: string[];\n}\n\n/** The store of a memo of a module. */\nexport interface MemoStore<T> extends StoreLike<T> {\n /**\n * The store that a component that imports the memo reads with `$store`. On the server it gives\n * the value, or a promise of it when the value loads, which the page state sends. In the browser\n * it takes that value on resume, and sends on each change, so the memo of the importer computes\n * again.\n */\n i: MemoFace;\n /** The value, or a promise of it while the memo loads. Throws the error of the memo. */\n p(): unknown;\n /** Follows the sources without computing, for a memo that reads this one. */\n f(listener: (value: T) => void): () => void;\n /** An object that changes with each value or error; brought up to date first, unless `raw`. */\n t(raw?: boolean): object;\n /** True when the value loads, or a memo that it reads loads. */\n a(): boolean;\n /** The values of the sources by name, through the memos that it reads, without computing. */\n r(): Record<string, unknown>;\n /** The number of renders of the server that the store holds, which a test reads. */\n h(): number;\n /** The listeners of the value, so a store that reads this one computes after them. */\n l: Set<(value: T) => void>;\n /** The number of derived stores below it. */\n d: number;\n [PENDING]: Pendable;\n [HOLDS]: true;\n}\n\n/** True for a store that `memoStore` made. */\nfunction isMemoStore(value: unknown): value is MemoStore<unknown> {\n return (\n typeof (value as { p?: unknown }).p === 'function' &&\n isContract((value as MemoStore<unknown>).i)\n );\n}\n\n/** True for a promise or an async iterable, which a memo loads. */\nfunction loads(value: unknown): value is PromiseLike<unknown> | AsyncIterable<unknown> {\n return (\n value !== null &&\n typeof value === 'object' &&\n (typeof (value as { then?: unknown }).then === 'function' ||\n typeof (value as { [Symbol.asyncIterator]?: unknown })[Symbol.asyncIterator] === 'function')\n );\n}\n\n/** The value of a store, or the error that its `get` throws. */\nfunction peekStore(source: StoreLike<unknown>): unknown {\n try {\n return source.get();\n } catch (error) {\n return error;\n }\n}\n\n/**\n * The key of what the server sends in the slot of `.i` in place of a value: `0` for a value that\n * the importer's memo sends, or the promise of a value that loaded, with its sources in `s`. A\n * value of a memo never has the key, and a promise in an object stays a promise in the browser.\n */\nconst FACE = '$$ms';\n\n/** True for what the server sends for a value that loaded: its promise and its sources. */\nfunction isLoadedFace(\n value: unknown,\n): value is { [FACE]: Promise<unknown>; s: Record<string, unknown> } {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as { [FACE]?: unknown })[FACE] instanceof Promise\n );\n}\n\n/**\n * True when two values of sources hold the same data, as the page state sends them: plain objects\n * and arrays item by item, a date by its time, a map and a set by their entries, a regular\n * expression by its source and flags, a typed array by its items, anything else by `Object.is`.\n */\nfunction sameSource(a: unknown, b: unknown, open = new Set<object>()): boolean {\n if (Object.is(a, b)) {\n return true;\n }\n if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) {\n return false;\n }\n if (Object.getPrototypeOf(a) !== Object.getPrototypeOf(b)) {\n return false;\n }\n // A value already under compare is a cycle, which counts as the same.\n if (open.has(a)) {\n return true;\n }\n open.add(a);\n if (a instanceof Date) {\n return Object.is(a.getTime(), (b as Date).getTime());\n }\n if (a instanceof RegExp) {\n return a.source === (b as RegExp).source && a.flags === (b as RegExp).flags;\n }\n if (a instanceof Map || a instanceof Set || (ArrayBuffer.isView(a) && !(a instanceof DataView))) {\n return sameSource([...(a as Iterable<unknown>)], [...(b as Iterable<unknown>)], open);\n }\n const left = Object.keys(a);\n if (left.length !== Object.keys(b).length) {\n return false;\n }\n for (const key of left) {\n if (\n !(key in b) ||\n !sameSource((a as Record<string, unknown>)[key], (b as Record<string, unknown>)[key], open)\n ) {\n return false;\n }\n }\n return true;\n}\n\n/** The render of the server that runs now, so a failed load is shared within it only. */\nfunction currentRender(): object | undefined {\n return (globalThis as Record<symbol, object | undefined>)[Symbol.for('brumate.render')];\n}\n\n/**\n * The store of `$memo(expr)` at the top level of a module, and of `$gate`, `$debounced` and\n * `$throttled` with `options`. It computes when it is read, and again when a source changes: while\n * it has subscribers, at once, and otherwise at the next read, which compares the sources. A\n * promise or an async iterable loads: a read gives the last value, and `p` the load, and only the\n * latest run is written. A throw or a rejection is held until the memo computes again; on the\n * server only for the renders that read that run. A memo that reads one with no value yet waits for\n * it.\n */\nexport function memoStore<S extends Stores, T>(\n sources: S,\n fn: (values: StoresValues<S>) => T | PromiseLike<T> | AsyncIterable<T>,\n options?: MemoOptions<T>,\n): MemoStore<T> {\n const single = !Array.isArray(sources);\n const list: StoreLike<unknown>[] = single ? [sources as StoreLike<unknown>] : sources;\n let level = 1;\n for (const source of list) {\n level = Math.max(level, ((source as { d?: number }).d ?? 0) + 1);\n }\n /** The value, which the listeners of the module hear. */\n const out = new Store<T>(undefined as T);\n /** What the memos of importers follow: the value, or an object that is new for each change. */\n const face = new Store<unknown>(undefined);\n const pend: Pendable = { q: new Set() };\n /** True when the latest run loaded, or waited for a memo that loads. */\n let loaded = false;\n /** On the server: the renders that read the latest run, which share its error. */\n let readers: Set<object> | undefined;\n /** On the server: the error of a run that failed, for each render that read it. */\n const failed = new WeakMap<object, { error: unknown }>();\n /** On the server: the promise of a value that loaded, which the page state sends. */\n let sent: Promise<T> | undefined;\n let timer: ReturnType<typeof setTimeout> | undefined;\n /** When the last throttled value was taken. */\n let last = -Infinity;\n let has = false;\n let held: { error: unknown } | undefined;\n /** Changes with each value or error. */\n let token = {};\n /** What the sources were at the last run: their values, or the tokens of memos. */\n let seen: unknown[] | undefined;\n /** The number of the latest run, so a load that a newer run replaced is dropped. */\n let run = 0;\n /** The run whose own load is out, or 0. */\n let loading = 0;\n /** While the memo loads: the promise that its readers wait for. */\n let wait:\n | { promise: Promise<T>; resolve: (value: T) => void; reject: (error: unknown) => void }\n | undefined;\n let stopStream: (() => void) | undefined;\n /** The subscribers of the value and of the sources. */\n let count = 0;\n let stops: (() => void)[] = [];\n\n /** What the sources are now: a memo gives its token, brought up to date unless `raw`. */\n const marks = (raw?: boolean): unknown[] => {\n const values: unknown[] = [];\n for (const source of list) {\n values.push(isMemoStore(source) ? source.t(raw) : peekStore(source));\n }\n return values;\n };\n\n const changed = (raw?: boolean): boolean => {\n if (!seen) {\n return true;\n }\n const now = marks(raw);\n for (const [index, value] of now.entries()) {\n if (!Object.is(value, seen[index])) {\n return true;\n }\n }\n return false;\n };\n\n /** True while a source loads, such as a debounced value that waits. */\n const sourcesPending = (): boolean => {\n for (const source of list) {\n if (pendingOf(source)?.n) {\n return true;\n }\n }\n return false;\n };\n\n /** What a component that imports the memo reads now. In the browser it is new for a load. */\n const show = (): unknown => {\n if (held) {\n throw held.error;\n }\n return wait ? face.v : out.v;\n };\n\n /** The values of the sources by name, through the memos that it reads, without computing. */\n const record = (): Record<string, unknown> => {\n const values: Record<string, unknown> = {};\n for (const [index, source] of list.entries()) {\n values[options?.n?.[index] ?? String(index)] = isMemoStore(source)\n ? source.r()\n : peekStore(source);\n }\n return values;\n };\n\n /**\n * The memos of importers compute again. The reader of the slot reads `show` again, as for any\n * store that holds an error, so what goes out is a notice only.\n */\n const bump = (): void => {\n if (wait) {\n face.v = {};\n }\n if (face.l.size > 0) {\n sendStore(face, face.v, true);\n }\n };\n\n /** The memo loads: its readers get a promise, and it is pending. */\n const enter = (): void => {\n if (wait) {\n return;\n }\n let resolve!: (value: T) => void;\n let reject!: (error: unknown) => void;\n const promise = new Promise<T>((done, fail) => {\n resolve = done;\n reject = fail;\n });\n // A rejection that no reader waits for is held, not reported.\n promise.catch(() => {});\n wait = { promise, resolve, reject };\n setPending(pend, true);\n bump();\n };\n\n /** The load ends: the readers that wait get the value or the error. */\n const release = (): void => {\n if (!wait || loading !== 0 || sourcesPending()) {\n return;\n }\n if (!has && !held) {\n compute();\n return;\n }\n const done = wait;\n wait = undefined;\n setPending(pend, false);\n if (held) {\n done.reject(held.error);\n } else {\n done.resolve(out.v);\n }\n };\n\n /** Writes the value or the error of a run, unless a newer run replaced it. */\n const finish = (id: number, value: T | undefined, failure?: { error: unknown }): void => {\n if (id !== run) {\n return;\n }\n loading = 0;\n const had = held;\n const before = out.v;\n const first = !has;\n held = failure;\n sent = undefined;\n // The renders that read this run keep its error for the rest of their render. The store keeps\n // no render once the load ended.\n if (failure) {\n for (const render of readers ?? []) {\n failed.set(render, failure);\n }\n }\n readers = undefined;\n if (!failure) {\n has = true;\n out.v = value as T;\n }\n // The readers hear of an error, and of the end of one, even with the same value. A value that\n // did not change, such as one that a gate kept, runs no reader.\n const news = !!failure || !!had || first || !Object.is(before, out.v);\n if (news) {\n token = {};\n }\n if (wait) {\n release();\n } else if (news) {\n bump();\n }\n if (news) {\n sendStore(out, out.v, true);\n }\n };\n\n /** Reads a stream: each value is the value, and the first one ends the load. */\n const read = (id: number, stream: AsyncIterable<T>, server: boolean): void => {\n const iterator = stream[Symbol.asyncIterator]();\n stopStream = () => {\n void iterator.return?.();\n };\n const step = (): void => {\n iterator.next().then(\n (result) => {\n if (id !== run) {\n return;\n }\n if (result.done) {\n stopStream = undefined;\n if (loading === id) {\n finish(id, undefined);\n }\n return;\n }\n finish(id, result.value);\n // The server renders the first value, as for a memo of a component.\n if (server) {\n stopStream?.();\n stopStream = undefined;\n return;\n }\n step();\n },\n (error: unknown) => finish(id, undefined, { error }),\n );\n };\n step();\n };\n\n /** Runs the function over the values of the sources, for the run `id`. */\n const evaluate = (id: number): void => {\n let result: unknown;\n loaded = false;\n try {\n seen = marks();\n const values: unknown[] = [];\n for (const source of list) {\n values.push(source.get());\n }\n result = fn((single ? values[0] : values) as StoresValues<S>);\n } catch (error) {\n if (error instanceof Waiting) {\n // A memo that it reads has no value yet: this one waits, and computes when it settles.\n loaded = true;\n loading = id;\n enter();\n const again = (): void => {\n if (id === run) {\n loading = 0;\n evaluate(id);\n }\n };\n error.load.then(again, again);\n return;\n }\n finish(id, undefined, { error });\n return;\n }\n const guard = options?.g;\n if (guard) {\n if (loads(result)) {\n finish(id, undefined, {\n error: new TypeError(\n 'The value of $gate is a promise or a stream. Use $memo for a value that loads',\n ),\n });\n return;\n }\n // A gate keeps no history without a subscriber, and the first value after an error passes.\n if (count > 0 && has && !held) {\n try {\n if (!guard(out.v, result as T)) {\n result = out.v;\n }\n } catch (error) {\n finish(id, undefined, { error });\n return;\n }\n }\n }\n if (!loads(result)) {\n finish(id, result as T);\n return;\n }\n loaded = true;\n loading = id;\n enter();\n const server = onServer();\n Promise.resolve(result).then(\n (value) => {\n if (id !== run) {\n return;\n }\n if (loads(value)) {\n read(id, value as AsyncIterable<T>, server);\n } else {\n finish(id, value as T);\n }\n },\n (error: unknown) => finish(id, undefined, { error }),\n );\n };\n\n /** Fires the wait of a debounced or throttled value: the latest run takes the value. */\n const fire = (): void => {\n timer = undefined;\n last = Date.now();\n loading = 0;\n evaluate(run);\n };\n\n /**\n * Starts a run. A debounced or throttled value that a subscriber holds in the browser waits:\n * it takes the value after `m` once the sources stop changing, or at most once every `m`.\n */\n const compute = (): void => {\n const id = ++run;\n stopStream?.();\n stopStream = undefined;\n loading = 0;\n readers = undefined;\n const ms = options?.m;\n if (ms === undefined || count === 0 || onServer()) {\n evaluate(id);\n return;\n }\n const since = Date.now() - last;\n if (options!.t && timer === undefined && since >= ms) {\n last = Date.now();\n evaluate(id);\n return;\n }\n if (!options!.t) {\n clearTimeout(timer);\n timer = undefined;\n }\n loading = id;\n enter();\n timer ??= setTimeout(fire, options!.t ? ms - since : ms);\n };\n\n /**\n * Computes when the memo has no value, or, with no subscriber, when a source changed. With\n * `retry`, on the server, a held error is read again only by the renders that read its run: a\n * later render loads again.\n */\n const ensure = (retry?: boolean): void => {\n if (!has && !held && !wait) {\n compute();\n } else if (count === 0 && changed()) {\n compute();\n } else if (retry && held && !wait) {\n const render = currentRender();\n if (render && !failed.has(render)) {\n compute();\n }\n }\n };\n\n /**\n * Notes the render of the server that reads the latest run: while it loads, so its error goes to\n * the render, and once it failed, as the render's own error. Returns the error that the render\n * read before, which it keeps, though a later render loaded again. A render that reads a value\n * is not kept.\n */\n const note = (): { error: unknown } | undefined => {\n const render = currentRender();\n if (!render) {\n return undefined;\n }\n const kept = failed.get(render);\n if (kept) {\n return kept;\n }\n if (wait) {\n (readers ??= new Set()).add(render);\n } else if (held) {\n failed.set(render, held);\n }\n return undefined;\n };\n\n const state: Computed = {\n level,\n waits: false,\n run() {\n if (count > 0 && changed()) {\n compute();\n }\n },\n };\n\n /** A subscriber starts to follow the sources; the last one to leave stops it. */\n const follow = (): (() => void) => {\n if (count++ === 0) {\n for (const source of list) {\n const heard = (): void => enqueue(state, source);\n stops.push(isMemoStore(source) ? source.f(heard) : source.subscribe(heard));\n const q = pendingOf(source)?.q;\n if (q) {\n const check = (): void => {\n if (sourcesPending()) {\n enter();\n } else {\n release();\n }\n };\n q.add(check);\n stops.push(() => q.delete(check));\n }\n }\n if (sourcesPending()) {\n enter();\n }\n // A source that changed while nothing followed computes it again. A memo that never ran,\n // such as one that the browser took from the server, waits for a change.\n // The memos that it reads checked their own sources as it followed them, so their tokens\n // are up to date.\n if (seen && changed(true)) {\n compute();\n }\n }\n let done = false;\n return () => {\n if (!done) {\n done = true;\n if (--count === 0) {\n for (const end of stops) {\n end();\n }\n stops = [];\n // A wait that nothing follows ends: the value is the value, as without a subscriber.\n if (timer !== undefined) {\n clearTimeout(timer);\n fire();\n }\n }\n }\n };\n };\n\n /** A subscription of `target`, which also follows the sources. */\n const listen = <V>(target: Store<V>, listener: (value: V) => void): (() => void) => {\n const off = target.subscribe(listener);\n const unfollow = follow();\n return () => {\n off();\n unfollow();\n };\n };\n\n const memo: MemoStore<T> = {\n get(): T {\n ensure();\n if (held) {\n throw held.error;\n }\n if (has) {\n return out.v;\n }\n throw new Waiting(wait!.promise);\n },\n subscribe(listener: (value: T) => void): () => void {\n // The value is there before the listener, which hears of changes only.\n ensure();\n return listen(out, listener);\n },\n p(): unknown {\n ensure(true);\n const kept = note();\n if (kept) {\n throw kept.error;\n }\n if (wait) {\n return wait.promise;\n }\n if (held) {\n throw held.error;\n }\n return out.v;\n },\n f(listener: (value: T) => void): () => void {\n return listen(out, listener);\n },\n t(raw?: boolean): object {\n if (!raw) {\n ensure();\n }\n return token;\n },\n a(): boolean {\n if (loaded) {\n return true;\n }\n for (const source of list) {\n if (isMemoStore(source) && source.a()) {\n return true;\n }\n }\n return false;\n },\n r: record,\n h: () => readers?.size ?? 0,\n i: {\n get(): unknown {\n // The browser subscribes the slot before it reads it. The server only reads.\n if (count > 0) {\n return show();\n }\n // A value that loaded goes as a promise with the values of its sources, so the browser\n // takes it without computing while its own sources are the same. A value that computes at\n // once goes as a marker, since the memo of the importer sends it, and the browser computes\n // it again and writes the slot of each importer; an object goes as it is, which the page\n // state sends once for both, and which the browser compares.\n ensure(true);\n if (note() || (held && !wait)) {\n return undefined;\n }\n if (!wait && !memo.a()) {\n return typeof out.v === 'object' && out.v !== null ? out.v : { [FACE]: 0 };\n }\n // The memo of the importer sends the error itself, so this one is generic. A promise in an\n // object stays a promise in the browser, which puts the value of a promise slot in its place.\n const promise = (wait ? wait.promise : (sent ??= Promise.resolve(out.v))).catch(() => {\n throw new Error('The page could not compute a value');\n });\n return { [FACE]: promise, s: record() };\n },\n subscribe(listener: (value: unknown) => void): () => void {\n return listen(face, listener);\n },\n s(value: unknown): void {\n // Only a memo that has not run takes the value of the server.\n if (has || held || wait || seen || value === undefined) {\n return;\n }\n if (!isLoadedFace(value)) {\n // It computed at once on the server, so it does here. The repair of each importer's slot\n // writes a value that differs, such as one of other sources, and the marker, which no\n // value equals.\n compute();\n return;\n }\n // A value that loaded of other sources than the browser's, such as a signal that a server\n // function wrote on the server, loads again here, and the old value stays meanwhile.\n const promise = value[FACE];\n if (!sameSource(value.s, record())) {\n compute();\n return;\n }\n // The same sources: the browser takes the value, and loads again when a source changes.\n const id = ++run;\n loaded = true;\n loading = id;\n enter();\n face.v = value;\n seen = marks(true);\n promise.then(\n (settled) => finish(id, settled as T),\n (error: unknown) => finish(id, undefined, { error }),\n );\n },\n // `$store` reads it again on each notice, and a read that throws puts the error in the slot.\n [HOLDS]: true,\n },\n l: out.l,\n d: level,\n [PENDING]: pend,\n [HOLDS]: true,\n };\n return memo;\n}\n\n// Bridges: a store of another library that can cross the page state. `bridge()` names how to make\n// the library's store, read it and listen to it, and the page state sends the data that `get`\n// reads, with the name of the bridge. The browser makes the library's store again, once, from\n// that data.\n\n/** What `bridge` takes. */\nexport interface BridgeOptions<S, T> {\n /**\n * Makes the library's store. On the server it runs once for each call of the bridge. In the\n * browser it runs once, when the store gets its first subscriber, with the data that the server\n * sent. It must be in a module that the browser can load.\n */\n create: (snapshot: T | undefined) => S;\n /** The data of the store: plain data that the page state can send. */\n get: (source: S) => T;\n /** Calls `listener` when the store changes. Returns the function that stops it. */\n subscribe: (source: S, listener: () => void) => () => void;\n /** Writes the store. The browser never calls it when the page resumes. */\n set?: (source: S, value: T) => void;\n}\n\n/** A store of `bridge()`: the contract of a store, and the store of the library. */\nexport interface BridgedStore<S, T> extends StoreLike<T> {\n /**\n * The store of the library. In the browser it is undefined until the store has a subscriber,\n * since the browser makes it at the first subscriber.\n */\n readonly source: S | undefined;\n}\n\n/** What `bridge` returns: makes a store, from the data of the server in the browser. */\nexport interface Bridge<S, T> {\n (snapshot?: T): BridgedStore<S, T>;\n /** The options. */\n b: BridgeOptions<S, T>;\n /** The name that the compiler gave, `bridge:<file>#<export>`. */\n i?: string;\n}\n\nconst BRIDGES = Symbol.for('brumate.bridges');\nconst BRIDGE_LOAD = Symbol.for('brumate.bridge-load');\n\ntype Global = { [BRIDGES]?: Map<string, Bridge<never, never>>; [BRIDGE_LOAD]?: Loader };\ntype Loader = [load: (module: string) => Promise<unknown>, report: (error: unknown) => void];\n\n/** The bridges by name, which any copy of the runtime shares. */\nfunction bridges(): Map<string, Bridge<never, never>> {\n return ((globalThis as Global)[BRIDGES] ??= new Map());\n}\n\n/**\n * Sets how the browser loads the module of a bridge, and where a failed load is reported. The\n * core calls it when it starts.\n */\nexport function setBridgeLoader(...loader: Loader): void {\n (globalThis as Global)[BRIDGE_LOAD] = loader;\n}\n\n/** The module of a bridge, from its name. */\nfunction bridgeModule(id: string): string {\n return id.slice(0, id.lastIndexOf('#'));\n}\n\n/**\n * Makes a bridge. Keep its value in a module-level export, so the page state can name it:\n * `export const bears = bridge({ … })`. The compiler gives it its name.\n */\nexport function bridge<S, T>(options: BridgeOptions<S, T>): Bridge<S, T> {\n const made = Object.assign(\n (snapshot?: T): BridgedStore<S, T> => new Bridged(made, options.create(snapshot)),\n { b: options },\n ) as Bridge<S, T>;\n return made;\n}\n\n/** Gives a bridge its name, which the compiler writes at the end of its module. */\nexport function nameBridge(made: Bridge<never, never>, id: string): void {\n made.i = id;\n bridges().set(id, made);\n}\n\n/** True for a store of `bridge()`, of any copy of the runtime. */\nexport function isBridged(value: unknown): value is Bridged<unknown, unknown> {\n return (\n typeof value === 'object' && value !== null && (value as { k?: unknown }).k === 'brumate.bridge'\n );\n}\n\n/**\n * Whether two values hold the same data: the same value, or arrays and plain objects whose items\n * hold the same data. A store that the browser makes again holds a new object with the content\n * the server sent, which needs no repair.\n */\nexport function sameData(a: unknown, b: unknown, open?: Map<object, Set<unknown>>): boolean {\n if (Object.is(a, b)) {\n return true;\n }\n const array = Array.isArray(a);\n if (array ? !Array.isArray(b) || a.length !== b.length : !isPlain(a) || !isPlain(b)) {\n return false;\n }\n const left = a as Record<string, unknown>;\n const right = b as Record<string, unknown>;\n // A pair already under compare is a cycle: it counts as the same, so each pair is compared once.\n open ??= new Map();\n let pairs = open.get(left);\n if (pairs?.has(right)) {\n return true;\n }\n if (!pairs) {\n pairs = new Set();\n open.set(left, pairs);\n }\n pairs.add(right);\n const keys = Object.keys(left);\n if (!array && keys.length !== Object.keys(right).length) {\n return false;\n }\n for (const key of keys) {\n if (!(key in right) || !sameData(left[key], right[key], open)) {\n return false;\n }\n }\n return true;\n}\n\n/** Whether a value is an object of `Object` or of no prototype, as page state holds. */\nfunction isPlain(value: unknown): value is Record<string, unknown> {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n const proto = Object.getPrototypeOf(value);\n return proto === Object.prototype || proto === null;\n}\n\n/**\n * The store that a bridge makes. On the server it holds the library's store from the start. In\n * the browser the page state makes it with the name of the bridge and the data of the server, and\n * it makes the library's store at its first subscriber.\n */\nexport class Bridged<S, T> implements BridgedStore<S, T> {\n /** The mark of a bridged store, which `isBridged` reads in every copy of the runtime. */\n k = 'brumate.bridge' as const;\n /** The bridge. Undefined for a store of the page state until the module of the bridge loads. */\n f?: Bridge<S, T>;\n /** The name of the bridge, for a store of the page state. */\n i?: string;\n /** The library's store. */\n s?: S;\n /** True once the library's store exists. */\n m = false;\n /** The data that the server sent, until the library's store exists. */\n v?: T;\n /** Whether the bridge has `set`, as the server sent it, until the module loads. */\n w?: boolean;\n\n constructor(\n made: Bridge<S, T> | undefined,\n source: S | undefined,\n id?: string,\n snapshot?: T,\n writable?: boolean,\n ) {\n this.f = made;\n this.i = id;\n this.v = snapshot;\n this.w = writable;\n if (made) {\n this.s = source;\n this.m = true;\n }\n }\n\n /**\n * The library's store. In the browser it is undefined until the store has a subscriber and the\n * module of the bridge has loaded.\n */\n get source(): S | undefined {\n return this.s;\n }\n\n /** The name of the bridge. */\n get id(): string | undefined {\n return this.f?.i ?? this.i;\n }\n\n /** The data of the store: what `get` reads, or what the server sent before the first subscriber. */\n get(): T {\n return this.m ? this.f!.b.get(this.s as S) : (this.v as T);\n }\n\n /**\n * Calls `listener` with the data when it changes. The first subscriber makes the library's\n * store in the browser. When the module of the bridge has not loaded, the subscription starts\n * when it has.\n */\n subscribe(listener: (value: T) => void, ...seen: [value?: T]): () => void {\n let stopped = false;\n let stop: (() => void) | undefined;\n // What this subscriber has seen, which `seen` can name: a source that starts later compares\n // with it.\n let last = seen.length > 0 ? (seen[0] as T) : this.get();\n const start = (): void => {\n if (stopped) {\n return;\n }\n const options = this.f!.b;\n const source = this.make();\n stop = options.subscribe(source, () => {\n const next = options.get(source);\n if (!sameData(next, last)) {\n last = next;\n listener(next);\n }\n });\n // A source that starts from other data than this subscriber saw, such as one that keeps its\n // own state, is written once.\n const first = options.get(source);\n if (!sameData(first, last)) {\n last = first;\n listener(first);\n }\n };\n if (this.find()) {\n start();\n } else {\n void this.load().then((loaded) => loaded && start());\n }\n return () => {\n stopped = true;\n stop?.();\n };\n }\n\n /** Writes the library's store, when the bridge has `set`. */\n get set(): ((value: T) => void) | undefined {\n // Before the module loads, the server's word is all there is, so `let` checks the same.\n const writable = this.find() ? !!this.f!.b.set : this.w !== false;\n return writable ? (value) => this.write(value) : undefined;\n }\n\n /** Writes the library's store, after the module of the bridge has loaded. */\n private write(value: T): void {\n if (this.find()) {\n this.f!.b.set!(this.make(), value);\n } else {\n void this.load().then((loaded) => loaded && this.write(value));\n }\n }\n\n /** The bridge, once its module has loaded. */\n private find(): Bridge<S, T> | undefined {\n if (!this.f && this.i !== undefined) {\n this.f = bridges().get(this.i) as Bridge<S, T> | undefined;\n }\n return this.f;\n }\n\n /** Loads the module of the bridge. A failure goes to the core's error path; it gives false. */\n private load(): Promise<boolean> {\n const [load, report] = (globalThis as Global)[BRIDGE_LOAD] ?? [];\n return Promise.resolve(load?.(bridgeModule(this.i!))).then(\n () => {\n if (this.find()) {\n return true;\n }\n this.fail(\n report,\n new Error(\n `The bridge \"${this.i}\" is not in its module. Keep bridge() in a module-level export, as \"export const name = bridge({ … })\"`,\n ),\n );\n return false;\n },\n (error: unknown) => {\n this.fail(report, error);\n return false;\n },\n );\n }\n\n private fail(report: ((error: unknown) => void) | undefined, error: unknown): void {\n if (report) {\n report(error);\n } else {\n console.error(error);\n }\n }\n\n /** Makes the library's store once, with the data of the server. */\n private make(): S {\n if (!this.m) {\n this.s = this.f!.b.create(this.v);\n this.m = true;\n }\n return this.s as S;\n }\n}\n"],"mappings":";;;AAQA,MAAM,OAAO,OAAO,IAAI,cAAc;;AAGtC,SAAgB,UAAU,OAA2C;CACnE,OACE,OAAO,UAAU,YACjB,UAAU,QACV,OAAQ,MAA4B,QAAQ,YAC5C,OAAO,KAAK,KAAK,CAAC,CAAC,WAAW,KAC9B,CAAC,WAAW,KAAK;AAErB;;;;;;AAOA,SAAgB,WACd,OACA,MACA,OACA,KACoB;CACpB,MAAM,QAAQ,SAAS,KAAA,IAAY,QAAS,QAAgD;CAC5F,IAAI,CAAC,WAAW,KAAK,GAAG;EAEtB,IAAI,UAAU,KAAK,GACjB,MAAM,IAAI,UACR,6BAA6B,MAAM,IAAI,6EACzC;EAEF,MAAM,IAAI,UACR,gBAAgB,QAAQ,KAAA,IAAY,YAAY,gBAAgB,IAAI,KAAK,SAAS,KAAA,IAAY,KAAK,QAAQ,KAAK,GAAG,oEACrH;CACF;CACA,IAAI,SAAS,CAAC,OAAO,KAAK,GACxB,MAAM,IAAI,UACR,cAAc,OAAO,IAAI,iEAC3B;CAEF,OAAO;AACT;;;;;AAMA,SAAgB,iBAAiB,WAAmB,OAAsB;CACxE,uBAAO,IAAI,MACT,aAAa,UAAU,yCAAyC,MAAM,8LACxE;AACF;;AAgBA,IAAa,QAAb,MAA8C;;CAE5C;;CAEA,oBAA6B,IAAI,IAAI;;CAErC;;CAEA;;CAEA;;CAEA;;;;;CAKA,IAAI;CAEJ,YAAY,OAAU;EACpB,KAAK,IAAI;CACX;;CAGA,MAAS;EACP,OAAO,KAAK;CACd;;CAGA,UAAU,UAA0C;EAClD,KAAK,EAAE,IAAI,QAAQ;EACnB,aAAa;GACX,KAAK,EAAE,OAAO,QAAQ;EACxB;CACF;;;;;CAMA,IAAI,OAAgB;EAClB,IAAI,KAAK,GACP,MAAM,IAAI,MAAM,2D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AAI,KAAA;CACnD;;CAGA,MAAc,OAAgB;EAC5B,IAAI,KAAK,KAAK,GACZ,KAAK,EAAG,EAAE,IAAK,KAAK,KAAK,GAAG,KAAK;OAEjC,KAAU,KAAK,CAAC,CAAC,MAAM,WAAW,UAAU,KAAK,MAAM,KAAK,CAAC;CAEjE;;CAGA,OAAyC;EACvC,IAAI,CAAC,KAAK,KAAK,KAAK,MAAM,KAAA,GACxB,KAAK,IAAI,QAAQ,CAAC,CAAC,IAAI,KAAK,CAAC;EAE/B,OAAO,KAAK;CACd;;CAGA,OAAiC;EAC/B,MAAM,CAAC,MAAM,UAAW,WAAsB,gBAAgB,CAAC;EAC/D,OAAO,QAAQ,QAAQ,OAAO,aAAa,KAAK,CAAE,CAAC,CAAC,CAAC,CAAC,WAC9C;GACJ,IAAI,KAAK,KAAK,GACZ,OAAO;GAET,KAAK,KACH,wBACA,IAAI,MACF,eAAe,KAAK,EAAE,uGACxB,CACF;GACA,OAAO;EACT,IACC,UAAmB;GAClB,KAAK,KAAK,QAAQ,KAAK;GACvB,OAAO;EACT,CACF;CACF;CAEA,KAAa,QAAgD,OAAsB;EACjF,IAAI,QACF,OAAO,KAAK;OAEZ,QAAQ,MAAM,KAAK;CAEvB;;CAGA,OAAkB;EAChB,IAAI,CAAC,KAAK,GAAG;GACX,KAAK,IAAI,KAAK,EAAG,EAAE,OAAO,KAAK,CAAC;GAChC,KAAK,IAAI;EACX;EACA,OAAO,KAAK;CACd;AACF"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as serialOptions, i as plugins } from "./serial-
|
|
1
|
+
import { a as serialOptions, i as plugins } from "./serial-Cj6pDGOq.js";
|
|
2
2
|
import { fromWebStream } from "@seroval/transport/web";
|
|
3
3
|
import { createJSONReader } from "@seroval/transport/read";
|
|
4
4
|
//#region src/runtime/stream-read.ts
|
|
@@ -19,4 +19,4 @@ async function fromChunkStream(stream) {
|
|
|
19
19
|
//#endregion
|
|
20
20
|
export { fromChunkStream as n, ANSWER as t };
|
|
21
21
|
|
|
22
|
-
//# sourceMappingURL=stream-read-
|
|
22
|
+
//# sourceMappingURL=stream-read-CiLDH60b.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"stream-read-
|
|
1
|
+
{"version":3,"file":"stream-read-CiLDH60b.js","names":[],"sources":["../src/runtime/stream-read.ts"],"sourcesContent":["// The read side of the answer of a server function. The browser loads only this\n// module, not the writer that the server uses (see `stream.ts`).\n\nimport { createJSONReader } from '@seroval/transport/read';\nimport { fromWebStream } from '@seroval/transport/web';\nimport { serialOptions, plugins } from './serial.ts';\n\n/** The key of the answer among the values of the stream. */\nexport const ANSWER = 'answer';\n\n/**\n * Reads the first value of a byte stream, and the rest in the background, so\n * the promises and async iterables in it settle as their messages arrive.\n */\nexport async function fromChunkStream(stream: ReadableStream<Uint8Array>): Promise<unknown> {\n const reader = createJSONReader({ plugins, ...serialOptions() });\n void fromWebStream(stream, reader);\n return reader.get(ANSWER);\n}\n"],"mappings":";;;;;AAQA,MAAa,SAAS;;;;;AAMtB,eAAsB,gBAAgB,QAAsD;CAC1F,MAAM,SAAS,iBAAiB;EAAE;EAAS,GAAG,cAAc;CAAE,CAAC;CAC/D,cAAmB,QAAQ,MAAM;CACjC,OAAO,OAAO,IAAI,MAAM;AAC1B"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export { t as ANSWER, n as fromChunkStream } from "./stream-read-
|
|
1
|
+
export { t as ANSWER, n as fromChunkStream } from "./stream-read-CiLDH60b.js";
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
//#region src/runtime/trace.d.ts
|
|
2
|
+
/** The names of spans. The `brumate.event` family is made in the browser. */
|
|
3
|
+
type TraceName = "brumate.request" | "brumate.render" | "brumate.stream" | "brumate.memo" | "brumate.call" | "brumate.body" | "brumate.event" | "brumate.load" | "brumate.run" | "brumate.navigation" | "brumate.fetch";
|
|
4
|
+
/** A step of the work, handed to `onTrace` when it ends. */
|
|
5
|
+
interface TraceSpan {
|
|
6
|
+
name: TraceName;
|
|
7
|
+
/** The component, function, route or event it is about, such as `GET /todos`, `Todos#add`, `click`. */
|
|
8
|
+
label: string;
|
|
9
|
+
/** 32 hex characters. */
|
|
10
|
+
traceId: string;
|
|
11
|
+
/** 16 hex characters. */
|
|
12
|
+
spanId: string;
|
|
13
|
+
/** The `spanId` of the parent. For a root, the parent of an incoming `traceparent`, if any. */
|
|
14
|
+
parentId?: string;
|
|
15
|
+
/** Epoch milliseconds, with a fraction. */
|
|
16
|
+
start: number;
|
|
17
|
+
/** Epoch milliseconds, with a fraction. */
|
|
18
|
+
end: number;
|
|
19
|
+
status: "ok" | "error";
|
|
20
|
+
attributes: Record<string, string | number | boolean>;
|
|
21
|
+
/** When `status` is `'error'`. It has no stack. */
|
|
22
|
+
error?: {
|
|
23
|
+
message: string;
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
/** The `onTrace` export of `src/middleware.ts`. */
|
|
27
|
+
type TraceHandler = (span: TraceSpan) => void | Promise<void>;
|
|
28
|
+
/** Ends a span. `failed` and the error that caused it are for a span that did not finish well. */
|
|
29
|
+
type EndSpan = (failed?: boolean, error?: unknown) => void;
|
|
30
|
+
/** What the spans of one request or render share. Made only when the app has an `onTrace`. */
|
|
31
|
+
declare class Tracer {
|
|
32
|
+
readonly traceId: string;
|
|
33
|
+
/** The parent of an incoming `traceparent`. */
|
|
34
|
+
readonly incoming: string | undefined;
|
|
35
|
+
/** The `spanId` of the span of the request. */
|
|
36
|
+
root: string | undefined;
|
|
37
|
+
/** The `spanId` of the latest render. */
|
|
38
|
+
render: string | undefined;
|
|
39
|
+
/** The attributes of the span of the request, which the server fills in as it learns them. */
|
|
40
|
+
readonly attributes: TraceSpan["attributes"];
|
|
41
|
+
readonly handler: TraceHandler;
|
|
42
|
+
/** The spans that began and have not ended, except the request, so an aborted request can end them. */
|
|
43
|
+
readonly open: Set<EndSpan>;
|
|
44
|
+
/** The first error that failed a span, which a 5xx answer of the request is the sign of. */
|
|
45
|
+
fault: unknown;
|
|
46
|
+
/** True once a span ended with an answer error such as a `ServerError`, which can have a 5xx status. */
|
|
47
|
+
answered: boolean;
|
|
48
|
+
constructor(handler: TraceHandler, traceparent?: string | null);
|
|
49
|
+
}
|
|
50
|
+
//#endregion
|
|
51
|
+
export { Tracer as a, TraceSpan as i, TraceHandler as n, TraceName as r, EndSpan as t };
|
|
52
|
+
//# sourceMappingURL=trace-DT7RGRAV.d.ts.map
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
//#region src/runtime/trace-browser.ts
|
|
2
|
+
let handler;
|
|
3
|
+
let current;
|
|
4
|
+
let dispatch;
|
|
5
|
+
/** Sets `onTrace`, or turns spans off with undefined. */
|
|
6
|
+
function setTraceHandler(next) {
|
|
7
|
+
handler = next;
|
|
8
|
+
current = dispatch = void 0;
|
|
9
|
+
}
|
|
10
|
+
/** Whether the page has `onTrace`. */
|
|
11
|
+
function isTracing() {
|
|
12
|
+
return handler !== void 0;
|
|
13
|
+
}
|
|
14
|
+
/** The trace that a server function call or a navigation made now joins. */
|
|
15
|
+
function traceContext() {
|
|
16
|
+
return handler ? current : void 0;
|
|
17
|
+
}
|
|
18
|
+
function now() {
|
|
19
|
+
return performance.timeOrigin + performance.now();
|
|
20
|
+
}
|
|
21
|
+
function randomHex(bytes) {
|
|
22
|
+
let text = "";
|
|
23
|
+
for (const byte of crypto.getRandomValues(new Uint8Array(bytes))) text += byte.toString(16).padStart(2, "0");
|
|
24
|
+
return text;
|
|
25
|
+
}
|
|
26
|
+
function messageOf(error) {
|
|
27
|
+
return error instanceof Error ? error.message : String(error);
|
|
28
|
+
}
|
|
29
|
+
function emit(span) {
|
|
30
|
+
try {
|
|
31
|
+
const result = handler?.(span);
|
|
32
|
+
if (result) Promise.resolve(result).catch((error) => console.error(error));
|
|
33
|
+
} catch (error) {
|
|
34
|
+
console.error(error);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
function startSpan(name, label, traceId, parentId, start = now(), attributes = {}) {
|
|
38
|
+
const spanId = randomHex(8);
|
|
39
|
+
let ended = false;
|
|
40
|
+
const span = {
|
|
41
|
+
traceId,
|
|
42
|
+
spanId,
|
|
43
|
+
label,
|
|
44
|
+
end(failed, error, more) {
|
|
45
|
+
if (ended) return;
|
|
46
|
+
ended = true;
|
|
47
|
+
emit({
|
|
48
|
+
name,
|
|
49
|
+
label: span.label,
|
|
50
|
+
traceId,
|
|
51
|
+
spanId,
|
|
52
|
+
...parentId === void 0 ? {} : { parentId },
|
|
53
|
+
start,
|
|
54
|
+
end: now(),
|
|
55
|
+
status: failed ? "error" : "ok",
|
|
56
|
+
attributes: more ? {
|
|
57
|
+
...attributes,
|
|
58
|
+
...more
|
|
59
|
+
} : attributes,
|
|
60
|
+
...failed ? { error: { message: messageOf(error) } } : {}
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
};
|
|
64
|
+
return span;
|
|
65
|
+
}
|
|
66
|
+
function isThenable(value) {
|
|
67
|
+
return typeof value?.then === "function";
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Starts the spans of an event handler, or none when the page has no `onTrace`. The handlers of one
|
|
71
|
+
* event share a trace. `ref` names the handler, such as `Todos#add`, and `waits` is true when
|
|
72
|
+
* the core is not loaded yet.
|
|
73
|
+
*/
|
|
74
|
+
function traceEvent(event, ref, waits) {
|
|
75
|
+
if (!handler) return;
|
|
76
|
+
if (!event || dispatch?.event !== event) dispatch = {
|
|
77
|
+
event,
|
|
78
|
+
traceId: randomHex(16),
|
|
79
|
+
start: now()
|
|
80
|
+
};
|
|
81
|
+
const { traceId, start } = dispatch;
|
|
82
|
+
const type = event?.type ?? "client";
|
|
83
|
+
const name = ref.split("@")[0];
|
|
84
|
+
const root = startSpan("brumate.event", `${type} ${name}`, traceId, void 0, start, { "brumate.event.type": type });
|
|
85
|
+
const trace = {
|
|
86
|
+
waits,
|
|
87
|
+
ready(failed, error) {
|
|
88
|
+
if (trace.waits || failed) startSpan("brumate.load", name.split("#")[0], traceId, root.spanId, start).end(failed, error);
|
|
89
|
+
},
|
|
90
|
+
run(call) {
|
|
91
|
+
const span = startSpan("brumate.run", name, traceId, root.spanId);
|
|
92
|
+
function finish(failed, error) {
|
|
93
|
+
span.end(failed, error);
|
|
94
|
+
root.end(failed, error);
|
|
95
|
+
}
|
|
96
|
+
let value;
|
|
97
|
+
current = {
|
|
98
|
+
traceId,
|
|
99
|
+
spanId: span.spanId
|
|
100
|
+
};
|
|
101
|
+
try {
|
|
102
|
+
value = call();
|
|
103
|
+
} catch (error) {
|
|
104
|
+
finish(true, error);
|
|
105
|
+
throw error;
|
|
106
|
+
} finally {
|
|
107
|
+
current = void 0;
|
|
108
|
+
}
|
|
109
|
+
if (isThenable(value)) value.then(() => finish(), (error) => finish(true, error));
|
|
110
|
+
else finish();
|
|
111
|
+
return value;
|
|
112
|
+
},
|
|
113
|
+
fail(error) {
|
|
114
|
+
root.end(true, error);
|
|
115
|
+
}
|
|
116
|
+
};
|
|
117
|
+
return trace;
|
|
118
|
+
}
|
|
119
|
+
/** The span of a navigation. It has the method only: the path can hold an ID, and is not known to be a route yet. */
|
|
120
|
+
function traceNavigation(url, init) {
|
|
121
|
+
const method = init?.method ?? "GET";
|
|
122
|
+
return traceRequest("brumate.navigation", method, url, { "http.method": method }, current);
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* Starts the span of a request: `brumate.fetch` for a server function, or `brumate.navigation`.
|
|
126
|
+
* It is a child of `parent`, or the root of a trace. Undefined when the page has no `onTrace`.
|
|
127
|
+
*/
|
|
128
|
+
function traceRequest(name, label, url, attributes, parent) {
|
|
129
|
+
if (!handler) return;
|
|
130
|
+
const span = startSpan(name, label, parent?.traceId ?? randomHex(16), parent?.spanId, void 0, attributes);
|
|
131
|
+
return {
|
|
132
|
+
header: new URL(url, location.href).origin === location.origin ? `00-${span.traceId}-${span.spanId}-01` : void 0,
|
|
133
|
+
span,
|
|
134
|
+
end(status, error, more) {
|
|
135
|
+
const failed = status === void 0 || status >= 500;
|
|
136
|
+
span.end(failed, error ?? `Status ${status}`, status === void 0 ? more : {
|
|
137
|
+
...more,
|
|
138
|
+
"http.status_code": status
|
|
139
|
+
});
|
|
140
|
+
},
|
|
141
|
+
route(path, params) {
|
|
142
|
+
const route = routeOf(path, params);
|
|
143
|
+
span.label = `${span.label.split(" ")[0]} ${route}`;
|
|
144
|
+
return route;
|
|
145
|
+
}
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* The route of a page: its path with the values of its parameters, from `b-params`, written as
|
|
150
|
+
* `[name]`, so the label has no ID of a user.
|
|
151
|
+
*/
|
|
152
|
+
function routeOf(path, params) {
|
|
153
|
+
if (!params) return path;
|
|
154
|
+
try {
|
|
155
|
+
const names = /* @__PURE__ */ new Map();
|
|
156
|
+
for (const [name, value] of Object.entries(JSON.parse(params))) if (typeof value === "string") names.set(value, name);
|
|
157
|
+
const parts = [];
|
|
158
|
+
for (const part of path.split("/")) {
|
|
159
|
+
const name = names.get(decodeURIComponent(part));
|
|
160
|
+
parts.push(name === void 0 ? part : `[${name}]`);
|
|
161
|
+
}
|
|
162
|
+
return parts.join("/");
|
|
163
|
+
} catch {
|
|
164
|
+
return path;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
//#endregion
|
|
168
|
+
export { traceNavigation as a, traceEvent as i, setTraceHandler as n, traceRequest as o, traceContext as r, isTracing as t };
|
|
169
|
+
|
|
170
|
+
//# sourceMappingURL=trace-browser-C7MFMove.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"trace-browser-C7MFMove.js","names":[],"sources":["../src/runtime/trace-browser.ts"],"sourcesContent":["// The spans of the browser, for the `onTrace` option of the loader: an event with the load of the\n// code of its handler and the run of the handler, the server functions that the page calls, and\n// navigations. Each caller sits behind `TRACE`, so a build without `onTrace` leaves this out.\n//\n// A span carries no arguments, results, query strings, form values or text.\n\nimport type { TraceHandler, TraceName, TraceSpan } from './trace.ts';\n\ntype Attributes = Record<string, string | number | boolean>;\n\n/** Where a request that the page makes belongs: the trace and the span that it is a child of. */\nexport interface TraceContext {\n traceId: string;\n spanId: string;\n}\n\ninterface Span extends TraceContext {\n label: string;\n end: (failed?: boolean, error?: unknown, attributes?: Attributes) => void;\n}\n\n/** The spans of one event handler. `boot` makes it, and the core calls it. */\nexport interface EventTrace {\n /** True when the handler waits for code, set by the loader and the core. */\n waits: boolean;\n /** The code of the handler has loaded, or failed to. Ends `brumate.load` when it waited. */\n ready: (failed?: boolean, error?: unknown) => void;\n /** Runs the handler inside `brumate.run`. Ends `brumate.event` when its result settles. */\n run: <T>(call: () => T) => T;\n /** Ends the event with an error, such as a handler whose code did not load. */\n fail: (error: unknown) => void;\n}\n\n/** A request that the page sends: a server function call or a navigation. */\nexport interface RequestTrace {\n /** The `traceparent` of the request, for a request to the same origin. */\n header?: string;\n span: Span;\n /** Ends the span with the status of the answer, or with the error of a request that failed. */\n end: (status?: number, error?: unknown, attributes?: Attributes) => void;\n /** Names a page by its route, from its path and the `b-params` of its state, and gives the route. */\n route: (path: string, params?: string | null) => string;\n}\n\nlet handler: TraceHandler | undefined;\n// The handler whose synchronous part runs now. A server function call or a navigation that it\n// makes before its first `await` reads it. It is cleared when that part returns: handlers overlap,\n// so a context that outlived it could give a call of one handler to the trace of another. A call\n// after an `await`, or from a memo, is the root of a trace of its own.\nlet current: TraceContext | undefined;\n// The event that is being dispatched, so its handlers share one trace.\nlet dispatch: { event: Event | undefined; traceId: string; start: number } | undefined;\n\n/** Sets `onTrace`, or turns spans off with undefined. */\nexport function setTraceHandler(next: TraceHandler | undefined): void {\n handler = next;\n current = dispatch = undefined;\n}\n\n/** Whether the page has `onTrace`. */\nexport function isTracing(): boolean {\n return handler !== undefined;\n}\n\n/** The trace that a server function call or a navigation made now joins. */\nexport function traceContext(): TraceContext | undefined {\n return handler ? current : undefined;\n}\n\nfunction now(): number {\n return performance.timeOrigin + performance.now();\n}\n\nfunction randomHex(bytes: number): string {\n let text = '';\n for (const byte of crypto.getRandomValues(new Uint8Array(bytes))) {\n text += byte.toString(16).padStart(2, '0');\n }\n return text;\n}\n\nfunction messageOf(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction emit(span: TraceSpan): void {\n try {\n const result = handler?.(span);\n if (result) {\n // A rejection is logged and changes nothing.\n Promise.resolve(result).catch((error: unknown) => console.error(error));\n }\n } catch (error) {\n console.error(error);\n }\n}\n\nfunction startSpan(\n name: TraceName,\n label: string,\n traceId: string,\n parentId?: string,\n start = now(),\n attributes: Attributes = {},\n): Span {\n const spanId = randomHex(8);\n let ended = false;\n const span: Span = {\n traceId,\n spanId,\n label,\n end(failed, error, more) {\n // A span ends once, such as an event whose handler throws and whose promise rejects.\n if (ended) {\n return;\n }\n ended = true;\n emit({\n name,\n label: span.label,\n traceId,\n spanId,\n ...(parentId === undefined ? {} : { parentId }),\n start,\n end: now(),\n status: failed ? 'error' : 'ok',\n attributes: more ? { ...attributes, ...more } : attributes,\n ...(failed ? { error: { message: messageOf(error) } } : {}),\n });\n },\n };\n return span;\n}\n\nfunction isThenable(value: unknown): value is PromiseLike<unknown> {\n return typeof (value as { then?: unknown } | null)?.then === 'function';\n}\n\n/**\n * Starts the spans of an event handler, or none when the page has no `onTrace`. The handlers of one\n * event share a trace. `ref` names the handler, such as `Todos#add`, and `waits` is true when\n * the core is not loaded yet.\n */\nexport function traceEvent(\n event: Event | undefined,\n ref: string,\n waits: boolean,\n): EventTrace | undefined {\n if (!handler) {\n return undefined;\n }\n // The start is the listener, before any code loads.\n if (!event || dispatch?.event !== event) {\n dispatch = { event, traceId: randomHex(16), start: now() };\n }\n const { traceId, start } = dispatch;\n const type = event?.type ?? 'client';\n const name = ref.split('@')[0]!;\n const root = startSpan('brumate.event', `${type} ${name}`, traceId, undefined, start, {\n 'brumate.event.type': type,\n });\n const trace: EventTrace = {\n waits,\n ready(failed, error) {\n if (trace.waits || failed) {\n const load = startSpan('brumate.load', name.split('#')[0]!, traceId, root.spanId, start);\n load.end(failed, error);\n }\n },\n run(call) {\n const span = startSpan('brumate.run', name, traceId, root.spanId);\n function finish(failed?: boolean, error?: unknown): void {\n span.end(failed, error);\n root.end(failed, error);\n }\n let value: ReturnType<typeof call>;\n current = { traceId, spanId: span.spanId };\n try {\n value = call();\n } catch (error) {\n finish(true, error);\n throw error;\n } finally {\n current = undefined;\n }\n if (isThenable(value)) {\n value.then(\n () => finish(),\n (error: unknown) => finish(true, error),\n );\n } else {\n finish();\n }\n return value;\n },\n fail(error) {\n root.end(true, error);\n },\n };\n return trace;\n}\n\n/** The span of a navigation. It has the method only: the path can hold an ID, and is not known to be a route yet. */\nexport function traceNavigation(url: string, init?: RequestInit): RequestTrace | undefined {\n const method = init?.method ?? 'GET';\n return traceRequest('brumate.navigation', method, url, { 'http.method': method }, current);\n}\n\n/**\n * Starts the span of a request: `brumate.fetch` for a server function, or `brumate.navigation`.\n * It is a child of `parent`, or the root of a trace. Undefined when the page has no `onTrace`.\n */\nexport function traceRequest(\n name: 'brumate.fetch' | 'brumate.navigation',\n label: string,\n url: string,\n attributes: Attributes,\n parent?: TraceContext,\n): RequestTrace | undefined {\n if (!handler) {\n return undefined;\n }\n const span = startSpan(\n name,\n label,\n parent?.traceId ?? randomHex(16),\n parent?.spanId,\n undefined,\n attributes,\n );\n // Another origin gets no header, as it would learn the trace of this page.\n const same = new URL(url, location.href).origin === location.origin;\n return {\n header: same ? `00-${span.traceId}-${span.spanId}-01` : undefined,\n span,\n end(status, error, more) {\n const failed = status === undefined || status >= 500;\n span.end(\n failed,\n error ?? `Status ${status}`,\n status === undefined ? more : { ...more, 'http.status_code': status },\n );\n },\n route(path, params) {\n const route = routeOf(path, params);\n span.label = `${span.label.split(' ')[0]} ${route}`;\n return route;\n },\n };\n}\n\n/**\n * The route of a page: its path with the values of its parameters, from `b-params`, written as\n * `[name]`, so the label has no ID of a user.\n */\nfunction routeOf(path: string, params?: string | null): string {\n if (!params) {\n return path;\n }\n try {\n const names = new Map<string, string>();\n for (const [name, value] of Object.entries(JSON.parse(params) as Record<string, unknown>)) {\n if (typeof value === 'string') {\n names.set(value, name);\n }\n }\n const parts: string[] = [];\n for (const part of path.split('/')) {\n const name = names.get(decodeURIComponent(part));\n parts.push(name === undefined ? part : `[${name}]`);\n }\n return parts.join('/');\n } catch {\n return path;\n }\n}\n"],"mappings":";AA4CA,IAAI;AAKJ,IAAI;AAEJ,IAAI;;AAGJ,SAAgB,gBAAgB,MAAsC;CACpE,UAAU;CACV,UAAU,WAAW,KAAA;AACvB;;AAGA,SAAgB,YAAqB;CACnC,OAAO,YAAY,KAAA;AACrB;;AAGA,SAAgB,eAAyC;CACvD,OAAO,UAAU,UAAU,KAAA;AAC7B;AAEA,SAAS,MAAc;CACrB,OAAO,YAAY,aAAa,YAAY,IAAI;AAClD;AAEA,SAAS,UAAU,OAAuB;CACxC,IAAI,OAAO;CACX,KAAK,MAAM,QAAQ,OAAO,gBAAgB,IAAI,WAAW,KAAK,CAAC,GAC7D,QAAQ,KAAK,SAAS,EAAE,CAAC,CAAC,SAAS,GAAG,GAAG;CAE3C,OAAO;AACT;AAEA,SAAS,UAAU,OAAwB;CACzC,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAC9D;AAEA,SAAS,KAAK,MAAuB;CACnC,IAAI;EACF,MAAM,SAAS,UAAU,IAAI;EAC7B,IAAI,QAEF,QAAQ,QAAQ,MAAM,CAAC,CAAC,OAAO,UAAmB,QAAQ,MAAM,KAAK,CAAC;CAE1E,SAAS,OAAO;EACd,QAAQ,MAAM,KAAK;CACrB;AACF;AAEA,SAAS,UACP,MACA,OACA,SACA,UACA,QAAQ,IAAI,GACZ,aAAyB,CAAC,GACpB;CACN,MAAM,SAAS,UAAU,CAAC;CAC1B,IAAI,QAAQ;CACZ,MAAM,OAAa;EACjB;EACA;EACA;EACA,IAAI,QAAQ,OAAO,MAAM;GAEvB,IAAI,OACF;GAEF,QAAQ;GACR,KA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IAAI,OAAO,UAAU,UACnB,MAAM,IAAI,OAAO,IAAI;EAGzB,MAAM,QAAkB,CAAC;EACzB,KAAK,MAAM,QAAQ,KAAK,MAAM,GAAG,GAAG;GAClC,MAAM,OAAO,MAAM,IAAI,mBAAmB,IAAI,CAAC;GAC/C,MAAM,KAAK,SAAS,KAAA,IAAY,OAAO,IAAI,KAAK,EAAE;EACpD;EACA,OAAO,MAAM,KAAK,GAAG;CACvB,QAAQ;EACN,OAAO;CACT;AACF"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"trace-flag-Dy267snx.js","names":[],"sources":["../src/runtime/trace-flag.ts"],"sourcesContent":["// Whether the build has the spans of the browser. The Vite plugin replaces the global with `true`\n// in a client build whose entry passes `onTrace` to the loader, and with `false` in any other. A\n// bundler then leaves out `trace-browser.ts` and every call into it. Without the plugin, as in a\n// test that does not stub the global, it is off.\n\ndeclare const __BRUMATE_TRACE__: boolean | undefined;\n\n/** True when the page can send spans to `onTrace`. */\nexport const TRACE: boolean = typeof __BRUMATE_TRACE__ !== 'undefined' && __BRUMATE_TRACE__;\n"],"mappings":";;AAQA,MAAa,QAAiB,OAAO,sBAAsB,eAAe"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { h as HAS_SCRIPTS } from "./features-Cte5aj20.js";
|
|
1
2
|
//#region src/runtime/trusted.ts
|
|
2
3
|
/** The name of the policy, for `trusted-types brumate` in the policy of the site. */
|
|
3
4
|
const POLICY = "brumate";
|
|
@@ -16,7 +17,8 @@ function ensure() {
|
|
|
16
17
|
if (factory && !policy) try {
|
|
17
18
|
policy = factory.createPolicy(POLICY, {
|
|
18
19
|
createHTML: (html) => html,
|
|
19
|
-
createScript: (code) => code
|
|
20
|
+
createScript: (code) => code,
|
|
21
|
+
...HAS_SCRIPTS ? { createScriptURL: (url) => url } : {}
|
|
20
22
|
});
|
|
21
23
|
factory[KEY] = policy;
|
|
22
24
|
} catch (error) {
|
|
@@ -28,11 +30,16 @@ function ensure() {
|
|
|
28
30
|
function trustedHTML(html) {
|
|
29
31
|
return ensure()?.createHTML(html) ?? html;
|
|
30
32
|
}
|
|
31
|
-
/**
|
|
32
|
-
|
|
33
|
-
|
|
33
|
+
/**
|
|
34
|
+
* The code of a script that came with the page, as the browser accepts it in a script's text. With
|
|
35
|
+
* `url`, the `src` of a script of markup, as the browser accepts it in `script.src`. It is one
|
|
36
|
+
* function, so a build without scripts in markup has no code for the URL.
|
|
37
|
+
*/
|
|
38
|
+
function trustedScript(code, url) {
|
|
39
|
+
const trusted = ensure();
|
|
40
|
+
return (HAS_SCRIPTS && url ? trusted?.createScriptURL?.(code) : trusted?.createScript(code)) ?? code;
|
|
34
41
|
}
|
|
35
42
|
//#endregion
|
|
36
43
|
export { trustedScript as n, trustedHTML as t };
|
|
37
44
|
|
|
38
|
-
//# sourceMappingURL=trusted-
|
|
45
|
+
//# sourceMappingURL=trusted-Bmwg4_hf.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"trusted-Bmwg4_hf.js","names":[],"sources":["../src/runtime/trusted.ts"],"sourcesContent":["// Trusted Types. A site whose Content Security Policy has\n// `require-trusted-types-for 'script'` refuses a string in `innerHTML` and\n// in the text of a script. The core passes the markup that it inserts, and\n// the scripts that it copies to run them, through a policy named `brumate`:\n// the markup of renders, deferred blocks, client navigation and the devtools.\n// The markup is what brumate's own render code made, with every value\n// escaped, and the scripts come from the server with the page, so the\n// policy passes them as they are.\n\nimport { HAS_SCRIPTS } from './features.ts';\n\n/** The name of the policy, for `trusted-types brumate` in the policy of the site. */\nexport const POLICY = 'brumate';\n\ninterface Policy {\n createHTML(html: string): string;\n createScript(code: string): string;\n /** Only with scripts in markup, so a build without them has no method. */\n createScriptURL?(url: string): string;\n}\n\n/**\n * The key of the policy on the browser's `trustedTypes`. A second copy of the core on the page, or\n * the core after a hot update, reuses it, since the browser refuses a second policy of the same\n * name unless the policy of the site says `'allow-duplicates'`.\n */\nconst KEY = Symbol.for('brumate.trusted-types');\n\ninterface Factory {\n createPolicy(name: string, rules: Policy): Policy;\n [KEY]?: Policy;\n}\n\n/** The policy, made on the first insert. Null where the browser has no Trusted Types. */\nlet policy: Policy | null | undefined;\n\nfunction ensure(): Policy | null {\n if (policy !== undefined) {\n return policy;\n }\n const factory = (globalThis as { trustedTypes?: Factory }).trustedTypes;\n policy = factory?.[KEY] ?? null;\n if (factory && !policy) {\n try {\n policy = factory.createPolicy(POLICY, {\n createHTML: (html) => html,\n createScript: (code) => code,\n ...(HAS_SCRIPTS ? { createScriptURL: (url: string) => url } : {}),\n });\n factory[KEY] = policy;\n } catch (error) {\n // The policy of the site names other policies, so the inserts below fail too.\n console.error(\n `brumate: the Content Security Policy does not allow the Trusted Types policy \"${POLICY}\". Add \"trusted-types ${POLICY}\" to it`,\n error,\n );\n }\n }\n return policy;\n}\n\n/** Markup that the core made, as the browser accepts it in `innerHTML`. */\nexport function trustedHTML(html: string): string {\n return ensure()?.createHTML(html) ?? html;\n}\n\n/**\n * The code of a script that came with the page, as the browser accepts it in a script's text. With\n * `url`, the `src` of a script of markup, as the browser accepts it in `script.src`. It is one\n * function, so a build without scripts in markup has no code for the URL.\n */\nexport function trustedScript(code: string, url?: boolean): string {\n const trusted = ensure();\n return (\n (HAS_SCRIPTS && url ? trusted?.createScriptURL?.(code) : trusted?.createScript(code)) ?? code\n );\n}\n"],"mappings":";;;AAYA,MAAa,SAAS;;;;;;AActB,MAAM,MAAM,OAAO,IAAI,uBAAuB;;AAQ9C,IAAI;AAEJ,SAAS,SAAwB;CAC/B,IAAI,WAAW,KAAA,GACb,OAAO;CAET,MAAM,UAAW,WAA0C;CAC3D,SAAS,UAAU,QAAQ;CAC3B,IAAI,WAAW,CAAC,QACd,IAAI;EACF,SAAS,QAAQ,aAAa,QAAQ;GACpC,aAAa,SAAS;GACtB,eAAe,SAAS;GACxB,GAAI,cAAc,EAAE,kBAAkB,QAAgB,IAAI,IAAI,CAAC;EACjE,CAAC;EACD,QAAQ,OAAO;CACjB,SAAS,OAAO;EAEd,QAAQ,MACN,iFAAiF,OAAO,wBAAwB,OAAO,UACvH,KACF;CACF;CAEF,OAAO;AACT;;AAGA,SAAgB,YAAY,MAAsB;CAChD,OAAO,OAAO,CAAC,EAAE,WAAW,IAAI,KAAK;AACvC;;;;;;AAOA,SAAgB,cAAc,MAAc,KAAuB;CACjE,MAAM,UAAU,OAAO;CACvB,QACG,eAAe,MAAM,SAAS,kBAAkB,IAAI,IAAI,SAAS,aAAa,IAAI,MAAM;AAE7F"}
|