brumate 0.5.1 → 0.6.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-Difa0qdg.d.ts → boot-CMvhoWRu.d.ts} +2 -2
- package/dist/cli.js +2 -2
- package/dist/{client-DvsU9qxG.d.ts → client-C4kNKGwH.d.ts} +18 -5
- package/dist/{client-BYHGusTe.js → client-eVI8Wc95.js} +199 -33
- package/dist/client-eVI8Wc95.js.map +1 -0
- package/dist/{defer-B63oF5Oa.js → defer-pKO0S6UT.js} +2 -2
- package/dist/{defer-B63oF5Oa.js.map → defer-pKO0S6UT.js.map} +1 -1
- package/dist/{devtools-D_SQpXTg.js → devtools-DqqqdI4b.js} +4 -4
- package/dist/{devtools-D_SQpXTg.js.map → devtools-DqqqdI4b.js.map} +1 -1
- package/dist/{devtools-panel-B9yokst5.js → devtools-panel--GYjFZ35.js} +2 -2
- package/dist/{devtools-panel-B9yokst5.js.map → devtools-panel--GYjFZ35.js.map} +1 -1
- package/dist/{features-D5kLyihb.js → features-CbgII-o7.js} +4 -2
- package/dist/features-CbgII-o7.js.map +1 -0
- package/dist/{files-s4wmjcZV.js → files-CR-V05xd.js} +2 -2
- package/dist/{files-s4wmjcZV.js.map → files-CR-V05xd.js.map} +1 -1
- package/dist/index.d.ts +8 -4
- package/dist/index.js +2 -7
- package/dist/index.js.map +1 -1
- package/dist/{inspect-BLPt-dZZ.js → inspect-ddfGeww0.js} +236 -57
- package/dist/inspect-ddfGeww0.js.map +1 -0
- package/dist/{loader-DKxhLjJw.js → loader-CQkAXO0g.js} +11 -3
- package/dist/loader-CQkAXO0g.js.map +1 -0
- package/dist/routes-D21FQyGF.js +51 -0
- package/dist/routes-D21FQyGF.js.map +1 -0
- package/dist/{rpc-CIVU4Ktx.js → rpc-BgYnfg_a.js} +3 -3
- package/dist/{rpc-CIVU4Ktx.js.map → rpc-BgYnfg_a.js.map} +1 -1
- package/dist/runtime/bundles.d.ts +1 -1
- package/dist/runtime/client.d.ts +2 -2
- package/dist/runtime/client.js +3 -3
- package/dist/runtime/devtools.d.ts +1 -1
- package/dist/runtime/devtools.js +1 -1
- package/dist/runtime/hot.d.ts +1 -1
- package/dist/runtime/loader.d.ts +2 -2
- package/dist/runtime/loader.js +2 -2
- package/dist/runtime/routes.js +1 -51
- package/dist/runtime/server.d.ts +2 -2
- package/dist/runtime/server.js +3 -3
- package/dist/runtime/signals.d.ts +2 -140
- 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/testing.d.ts +24 -4
- package/dist/runtime/testing.js +66 -2
- package/dist/runtime/testing.js.map +1 -1
- package/dist/{produce-Cq6KKi7b.js → search-params-CM1RWR2P.js} +25 -3
- package/dist/search-params-CM1RWR2P.js.map +1 -0
- package/dist/{server-Doy5HR7r.js → server-BcT9icQ4.js} +107 -40
- package/dist/server-BcT9icQ4.js.map +1 -0
- package/dist/{server-CAwIqrXl.d.ts → server-dP_ucRiJ.d.ts} +42 -3
- package/dist/signals-BwD4u22K.d.ts +165 -0
- package/dist/{static-loader-9Nc1GvF0.d.ts → static-loader-CGthkX0s.d.ts} +2 -2
- package/dist/{static-loader-Bdet7g76.js → static-loader-DCxASuzA.js} +3 -3
- package/dist/{static-loader-Bdet7g76.js.map → static-loader-DCxASuzA.js.map} +1 -1
- package/dist/{stream-BdhzvPQO.js → stream-DRjx0keF.js} +2 -2
- package/dist/{stream-BdhzvPQO.js.map → stream-DRjx0keF.js.map} +1 -1
- package/dist/vite.d.ts +1 -1
- package/dist/vite.js +17 -12
- package/dist/vite.js.map +1 -1
- package/elements.d.ts +231 -35
- package/package.json +6 -1
- package/skills/brumate/references/errors.md +32 -12
- package/skills/brumate/references/signals.md +27 -25
- package/skills/brumate/references/syntax.md +1 -1
- package/dist/client-BYHGusTe.js.map +0 -1
- package/dist/features-D5kLyihb.js.map +0 -1
- package/dist/inspect-BLPt-dZZ.js.map +0 -1
- package/dist/loader-DKxhLjJw.js.map +0 -1
- package/dist/produce-Cq6KKi7b.js.map +0 -1
- package/dist/runtime/routes.js.map +0 -1
- package/dist/server-Doy5HR7r.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"signals.js","names":[],"sources":["../../src/runtime/signals.ts"],"sourcesContent":["// The compile-time functions of `.brm` files. The compiler replaces every\n// call and removes the import, so this module only gives them their types.\n// A call outside a `.brm` file throws.\n\nimport type { Context, NavigationState, Route } from './context.ts';\nimport type { RoutePath, RouteParams } from './routes.ts';\n\nfunction compileTimeOnly(name: string): never {\n throw new Error(`${name} works only in .brm files, which the brumate compiler compiles`);\n}\n\ndeclare const BINDABLE: unique symbol;\ndeclare const WRITES: unique symbol;\n\n/** The mark of a prop that a parent can bind. It has no value at runtime. */\nexport interface BindableMark<T> {\n readonly [BINDABLE]: T;\n}\n\n/**\n * What a binding writes. A binding of a signal of `T` takes a prop that writes `W` when `W` is\n * assignable to `T`, as a signal of `HTMLElement | undefined` takes the ref of a `div`.\n */\nexport interface WritableMark<W> {\n readonly [WRITES]: (value: W) => void;\n}\n\n/** What `$bind` returns: the mark of a prop, and the write side that checks the type of a ref. */\n// oxlint-disable-next-line typescript/no-empty-object-type, typescript/no-empty-interface -- An interface keeps its name in messages.\nexport interface BoundSignal<T> extends BindableMark<T>, WritableMark<T> {}\n\n/**\n * Marks a prop that a parent can bind with `$bind`, such as\n * `open?: Bindable<boolean>`. The parent passes `T` or `$bind(name)`.\n * Inside the component, `$props<T>()` gives `T`.\n */\nexport type Bindable<T> = T | BindableMark<T>;\n\n/** The props as the component reads them, with `Bindable<T>` as `T`. */\nexport type Unbound<T> = { [K in keyof T]: Exclude<T[K], BindableMark<unknown>> };\n\n/**\n * Returns the props of the component. Destructure the call to keep each prop\n * reactive. Destructure it with `let` to write props, such as\n * `let { open = false } = $props()`.\n */\n// oxlint-disable-next-line typescript/no-explicit-any -- Props are any object unless typed.\nexport function $props<T = Record<string, any>>(): Unbound<T> {\n return compileTimeOnly('$props');\n}\n\n/** Declares writable state. The variable reads and writes the signal. */\nexport function $signal<T>(value: T): T;\nexport function $signal<T>(): T | undefined;\nexport function $signal(): never {\n return compileTimeOnly('$signal');\n}\n\n/** The value of a memo: what a promise settles to, or the latest value of an async iterable. */\nexport type MemoValue<T> = Awaited<T> extends AsyncIterable<infer U> ? U : Awaited<T>;\n\n/**\n * Declares a value computed from other values. A promise is awaited where it\n * is read. An async iterable gives each of its values in turn.\n */\nexport function $memo<T>(_value: T): MemoValue<T> {\n return compileTimeOnly('$memo');\n}\n\n/**\n * Declares a memo that takes the value once it stops changing for `ms`\n * milliseconds, such as a search query while the user types. On the server,\n * and until the value first changes, it is the value.\n */\nexport function $debounced<T>(_value: T, _ms: number): MemoValue<T> {\n return compileTimeOnly('$debounced');\n}\n\n/**\n * Declares a memo that takes the value at most once every `ms`\n * milliseconds, and the last value after the wait, such as a position while\n * the pointer moves. On the server, and until the value first changes, it is the value.\n */\nexport function $throttled<T>(_value: T, _ms: number): MemoValue<T> {\n return compileTimeOnly('$throttled');\n}\n\n/**\n * Declares a value that follows a memo, and that handlers can write. A write\n * shows a guess, such as a new item while the form that adds it posts. The\n * value goes back to the memo when the memo changes, or when the server\n * calls of the page finish, such as after a failed post.\n */\nexport function $optimistic<T>(_source: T): T {\n return compileTimeOnly('$optimistic');\n}\n\n/** Runs a callback when the values it reads change, after the page resumes. Never on load. */\nexport function $effect(_callback: () => void | (() => void)): void {\n compileTimeOnly('$effect');\n}\n\n/** Runs a callback in the browser when a trigger fires. */\nexport function $client(\n _callback: () => void | (() => void),\n _trigger?: 'visible' | 'idle' | 'load',\n): void {\n compileTimeOnly('$client');\n}\n\n/** Reads a value without depending on it. */\nexport function $untrack<T>(_value: T): T {\n return compileTimeOnly('$untrack');\n}\n\n/** True while a new value of a memo, or of a memo it reads, loads on the client. Always false on the server. */\nexport function $isPending(_memo: unknown): boolean {\n return compileTimeOnly('$isPending');\n}\n\n/**\n * Waits for a memo to have its value, and gives it. It resolves at once when the memo is settled,\n * and after the load when the memo loads its first value or loads again. When the inputs of the\n * memo change while it waits, it waits for the load of the current inputs. It rejects with the\n * error of the memo, when `timeout` milliseconds pass, or when `signal` aborts. Use it in a handler,\n * an effect or a `$client` callback, never where a memo computes or markup renders.\n */\nexport function $resolve<T>(\n _memo: T,\n _options?: { timeout?: number; signal?: AbortSignal },\n): Promise<Awaited<T>> {\n return compileTimeOnly('$resolve');\n}\n\n/**\n * True when the parent passed a prop with `$bind`, so a write of it reaches the parent. The prop is\n * one that the component destructures with `let`. Always false on the server, where nothing writes.\n */\nexport function $isBound(_prop: unknown): boolean {\n return compileTimeOnly('$isBound');\n}\n\n/**\n * True when the caller passed the prop, even as `undefined`. A part uses it to tell a controlled\n * value, such as `value=(null)`, from no value. Declare it with `const` in the component script.\n */\nexport function $isPassed(_prop: unknown): boolean {\n return compileTimeOnly('$isPassed');\n}\n\n/** Returns an ID that is unique in the page and the same on the server and the client. */\nexport function $id(): string {\n return compileTimeOnly('$id');\n}\n\n/** Provides a value of a context to the components inside this one. */\nexport function $setContext<T>(_context: Context<T>, _value: T): void {\n compileTimeOnly('$setContext');\n}\n\n/** Reads a context from the nearest component above that provides it, or its default value. */\nexport function $getContext<T>(_context: Context<T>): T {\n return compileTimeOnly('$getContext');\n}\n\n/**\n * The route of the page: its URL, its query string and its params, typed\n * from the route files as `href` is. The server reads the request, and the\n * browser reads `location`. It changes when navigation changes the URL.\n */\nexport function $route<P extends RoutePath = RoutePath>(_path?: P): Route<RouteParams<P>> {\n return compileTimeOnly('$route');\n}\n\n/** The navigation that loads, with `pending` false when none does. Always `{ pending: false }` on the server. */\nexport function $navigation(): NavigationState {\n return compileTimeOnly('$navigation');\n}\n\n/** Changes an object or an array in a signal through a draft, and writes the signal with the result. */\nexport function $produce<T>(_signal: T, _recipe: (draft: T) => T | void): void {\n compileTimeOnly('$produce');\n}\n\n/** Sets the title of the page. The last component that sets it wins. */\nexport function $title(_value: unknown): void {\n compileTimeOnly('$title');\n}\n\n/**\n * The latest result of a server function that a form of this component posts\n * to, or undefined before the first post. Pending while the form sends.\n */\nexport function $action<F extends (...args: never[]) => unknown>(\n _fn: F,\n): Awaited<ReturnType<F>> | undefined {\n return compileTimeOnly('$action');\n}\n\n/**\n * Passes a child a signal, or a prop that the component writes, so a write\n * of the prop in the child writes it. The child destructures the prop with\n * `let`. Pass it as the value of a prop: `<Dialog open=$bind(open) />`.\n *\n * - Only a prop of type `Bindable<T>` takes it.\n * - With `set`, a write calls `set(next)` in place of writing the signal.\n */\nexport function $bind<T>(signal: T, set?: (next: T) => unknown): BoundSignal<T>;\nexport function $bind(): never {\n return compileTimeOnly('$bind');\n}\n\n/**\n * Marks a function that a script makes as an event handler, so a spread can\n * pass it on, as it passes on a handler that a caller writes in markup.\n * `args` are JSON values that go with the handler, and it runs as\n * `fn(...args, event)`.\n */\nexport function $handler<A extends unknown[], E = Event>(\n fn: (...args: [...A, E]) => unknown,\n ...args: A\n): (event: E) => unknown;\n/** A function that does not read the event. */\nexport function $handler<A extends unknown[]>(\n fn: (...args: A) => unknown,\n ...args: A\n): (event: Event) => unknown;\nexport function $handler(): never {\n return compileTimeOnly('$handler');\n}\n\n/**\n * Writes what the writes of the handler so far changed to the page, so the code after it can read\n * the DOM, such as to focus or measure what a write rendered. A handler is one pass, and the page\n * changes when it returns. Does nothing outside a handler, and on the server.\n */\nexport function flush(): void {\n (globalThis as { [key: symbol]: (() => void) | undefined })[Symbol.for('brumate.flush')]?.();\n}\n"],"mappings":";AAOA,SAAS,gBAAgB,MAAqB;CAC5C,MAAM,IAAI,MAAM,GAAG,KAAK,+DAA+D;AACzF;;;;;;AAsCA,SAAgB,SAA8C;CAC5D,OAAO,gBAAgB,QAAQ;AACjC;AAKA,SAAgB,UAAiB;CAC/B,OAAO,gBAAgB,SAAS;AAClC;;;;;AASA,SAAgB,MAAS,QAAyB;CAChD,OAAO,gBAAgB,OAAO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;;;;;AAOA,SAAgB,QAAc;CAC5B,WAA4D,OAAO,IAAI,eAAe,EAAE,GAAG;AAC7F"}
|
|
1
|
+
{"version":3,"file":"signals.js","names":[],"sources":["../../src/runtime/signals.ts"],"sourcesContent":["// The compile-time functions of `.brm` files. The compiler replaces every\n// call and removes the import, so this module only gives them their types.\n// A call outside a `.brm` file throws.\n\nimport type { Context, NavigationState, Route } from './context.ts';\nimport type { RoutePath, RouteParams } from './routes.ts';\n\nfunction compileTimeOnly(name: string): never {\n throw new Error(`${name} works only in .brm files, which the brumate compiler compiles`);\n}\n\ndeclare const BINDABLE: unique symbol;\ndeclare const WRITES: unique symbol;\n\n/** The mark of a prop that a parent can bind. It has no value at runtime. */\nexport interface BindableMark<T> {\n readonly [BINDABLE]: T;\n}\n\n/**\n * What a binding writes. A binding of a signal of `T` takes a prop that writes `W` when `W` is\n * assignable to `T`, as a signal of `HTMLElement | undefined` takes the ref of a `div`.\n */\nexport interface WritableMark<W> {\n readonly [WRITES]: (value: W) => void;\n}\n\n/** What `$bind` returns: the mark of a prop, and the write side that checks the type of a ref. */\n// oxlint-disable-next-line typescript/no-empty-object-type, typescript/no-empty-interface -- An interface keeps its name in messages.\nexport interface BoundSignal<T> extends BindableMark<T>, WritableMark<T> {}\n\n/**\n * Marks a prop that a parent can bind with `$bind`, such as\n * `open?: Bindable<boolean>`. The parent passes `T` or `$bind(name)`.\n * Inside the component, `$props<T>()` gives `T`.\n */\nexport type Bindable<T> = T | BindableMark<T>;\n\n/** The props as the component reads them, with `Bindable<T>` as `T`. */\nexport type Unbound<T> = { [K in keyof T]: Exclude<T[K], BindableMark<unknown>> };\n\n/**\n * Returns the props of the component. Destructure the call to keep each prop\n * reactive. Destructure it with `let` to write props, such as\n * `let { open = false } = $props()`.\n */\n// oxlint-disable-next-line typescript/no-explicit-any -- Props are any object unless typed.\nexport function $props<T = Record<string, any>>(): Unbound<T> {\n return compileTimeOnly('$props');\n}\n\n/** Declares writable state. The variable reads and writes the signal. */\nexport function $signal<T>(value: T): T;\nexport function $signal<T>(): T | undefined;\nexport function $signal(): never {\n return compileTimeOnly('$signal');\n}\n\n/** The value of a memo: what a promise settles to, or the latest value of an async iterable. */\nexport type MemoValue<T> = Awaited<T> extends AsyncIterable<infer U> ? U : Awaited<T>;\n\n/**\n * Declares a value computed from other values. A promise is awaited where it\n * is read. An async iterable gives each of its values in turn.\n */\nexport function $memo<T>(_value: T): MemoValue<T> {\n return compileTimeOnly('$memo');\n}\n\n/**\n * Declares a memo that takes the value once it stops changing for `ms`\n * milliseconds, such as a search query while the user types. On the server,\n * and until the value first changes, it is the value.\n */\nexport function $debounced<T>(_value: T, _ms: number): MemoValue<T> {\n return compileTimeOnly('$debounced');\n}\n\n/**\n * Declares a memo that takes the value at most once every `ms`\n * milliseconds, and the last value after the wait, such as a position while\n * the pointer moves. On the server, and until the value first changes, it is the value.\n */\nexport function $throttled<T>(_value: T, _ms: number): MemoValue<T> {\n return compileTimeOnly('$throttled');\n}\n\n/**\n * Declares a value that follows a memo, and that handlers can write. A write\n * shows a guess, such as a new item while the form that adds it posts. The\n * value goes back to the memo when the memo changes, or when the server\n * calls of the page finish, such as after a failed post.\n */\nexport function $optimistic<T>(_source: T): T {\n return compileTimeOnly('$optimistic');\n}\n\n/** Runs a callback when the values it reads change, after the page resumes. Never on load. */\nexport function $effect(_callback: () => void | (() => void)): void {\n compileTimeOnly('$effect');\n}\n\n/** Runs a callback in the browser when a trigger fires. */\nexport function $client(\n _callback: () => void | (() => void),\n _trigger?: 'visible' | 'idle' | 'load',\n): void {\n compileTimeOnly('$client');\n}\n\n/** Reads a value without depending on it. */\nexport function $untrack<T>(_value: T): T {\n return compileTimeOnly('$untrack');\n}\n\n/** True while a new value of a memo, or of a memo it reads, loads on the client. Always false on the server. */\nexport function $isPending(_memo: unknown): boolean {\n return compileTimeOnly('$isPending');\n}\n\n/**\n * Waits for a memo to have its value, and gives it. It resolves at once when the memo is settled,\n * and after the load when the memo loads its first value or loads again. When the inputs of the\n * memo change while it waits, it waits for the load of the current inputs. It rejects with the\n * error of the memo, when `timeout` milliseconds pass, or when `signal` aborts. Use it in a handler,\n * an effect or a `$client` callback, never where a memo computes or markup renders.\n */\nexport function $resolve<T>(\n _memo: T,\n _options?: { timeout?: number; signal?: AbortSignal },\n): Promise<Awaited<T>> {\n return compileTimeOnly('$resolve');\n}\n\n/**\n * True when the parent passed a prop with `$bind`, so a write of it reaches the parent. The prop is\n * one that the component destructures with `let`. Always false on the server, where nothing writes.\n */\nexport function $isBound(_prop: unknown): boolean {\n return compileTimeOnly('$isBound');\n}\n\n/**\n * True when the caller passed the prop, even as `undefined`. A part uses it to tell a controlled\n * value, such as `value=(null)`, from no value. Declare it with `const` in the component script.\n */\nexport function $isPassed(_prop: unknown): boolean {\n return compileTimeOnly('$isPassed');\n}\n\n/** Returns an ID that is unique in the page and the same on the server and the client. */\nexport function $id(): string {\n return compileTimeOnly('$id');\n}\n\n/** Provides a value of a context to the components inside this one. */\nexport function $setContext<T>(_context: Context<T>, _value: T): void {\n compileTimeOnly('$setContext');\n}\n\n/** Reads a context from the nearest component above that provides it, or its default value. */\nexport function $getContext<T>(_context: Context<T>): T {\n return compileTimeOnly('$getContext');\n}\n\n/**\n * The route of the page: its URL, its query string and its params, typed\n * from the route files as `href` is. The server reads the request, and the\n * browser reads `location`. It changes when navigation changes the URL.\n */\nexport function $route<P extends RoutePath = RoutePath>(_path?: P): Route<RouteParams<P>> {\n return compileTimeOnly('$route');\n}\n\n/** The options of `$searchParam`. */\nexport interface SearchParamOptions<T> {\n /** The value while the parameter is not in the URL. A write of this value leaves the parameter out. */\n default?: T;\n /** Converts the text of the parameter to a value. Defaults to the text. */\n parse?: (text: string) => T;\n /** Converts a value to the text of the parameter. Defaults to `String`. */\n serialize?: (value: T) => string;\n /** `'push'` adds an entry to the history for each change, and `'replace'` (the default) changes the entry. */\n history?: 'push' | 'replace';\n /** True asks the server for the page again when the parameter changes, as a link to the new URL does. */\n server?: boolean;\n}\n\n/**\n * A signal bound to one parameter of the query string. The server reads the URL of the request.\n * A write in the browser changes the URL with `history.replaceState`, or `pushState` with\n * `{ history: 'push' }`, and asks the server nothing. Back and forward write the signal.\n */\nexport function $searchParam(name: string, options?: SearchParamOptions<string>): string | null;\nexport function $searchParam<T>(name: string, options: SearchParamOptions<T> & { default: T }): T;\nexport function $searchParam<T>(\n name: string,\n options: SearchParamOptions<T> & { parse: (text: string) => T },\n): T | null;\nexport function $searchParam(): never {\n return compileTimeOnly('$searchParam');\n}\n\n/** The navigation that loads, with `pending` false when none does. Always `{ pending: false }` on the server. */\nexport function $navigation(): NavigationState {\n return compileTimeOnly('$navigation');\n}\n\n/** Changes an object or an array in a signal through a draft, and writes the signal with the result. */\nexport function $produce<T>(_signal: T, _recipe: (draft: T) => T | void): void {\n compileTimeOnly('$produce');\n}\n\n/** Sets the title of the page. The last component that sets it wins. */\nexport function $title(_value: unknown): void {\n compileTimeOnly('$title');\n}\n\n/**\n * The latest result of a server function that a form of this component posts\n * to, or undefined before the first post. Pending while the form sends.\n */\nexport function $action<F extends (...args: never[]) => unknown>(\n _fn: F,\n): Awaited<ReturnType<F>> | undefined {\n return compileTimeOnly('$action');\n}\n\n/**\n * Passes a child a signal, or a prop that the component writes, so a write\n * of the prop in the child writes it. The child destructures the prop with\n * `let`. Pass it as the value of a prop: `<Dialog open=$bind(open) />`.\n *\n * - Only a prop of type `Bindable<T>` takes it.\n * - With `set`, a write calls `set(next)` in place of writing the signal.\n */\nexport function $bind<T>(signal: T, set?: (next: T) => unknown): BoundSignal<T>;\nexport function $bind(): never {\n return compileTimeOnly('$bind');\n}\n\n/**\n * Marks a function that a script makes as an event handler, so a spread can\n * pass it on, as it passes on a handler that a caller writes in markup.\n * `args` are JSON values that go with the handler, and it runs as\n * `fn(...args, event)`.\n */\nexport function $handler<A extends unknown[], E = Event>(\n fn: (...args: [...A, E]) => unknown,\n ...args: A\n): (event: E) => unknown;\n/** A function that does not read the event. */\nexport function $handler<A extends unknown[]>(\n fn: (...args: A) => unknown,\n ...args: A\n): (event: Event) => unknown;\nexport function $handler(): never {\n return compileTimeOnly('$handler');\n}\n\n/**\n * Writes what the writes of the handler so far changed to the page, so the code after it can read\n * the DOM, such as to focus or measure what a write rendered. A handler is one pass, and the page\n * changes when it returns. Does nothing outside a handler, and on the server.\n */\nexport function flush(): void {\n (globalThis as { [key: symbol]: (() => void) | undefined })[Symbol.for('brumate.flush')]?.();\n}\n"],"mappings":";AAOA,SAAS,gBAAgB,MAAqB;CAC5C,MAAM,IAAI,MAAM,GAAG,KAAK,+DAA+D;AACzF;;;;;;AAsCA,SAAgB,SAA8C;CAC5D,OAAO,gBAAgB,QAAQ;AACjC;AAKA,SAAgB,UAAiB;CAC/B,OAAO,gBAAgB,SAAS;AAClC;;;;;AASA,SAAgB,MAAS,QAAyB;CAChD,OAAO,gBAAgB,OAAO;AAChC;;;;;;AAOA,SAAgB,WAAc,QAAW,KAA2B;CAClE,OAAO,gBAAgB,YAAY;AACrC;;;;;;AAOA,SAAgB,WAAc,QAAW,KAA2B;CAClE,OAAO,gBAAgB,YAAY;AACrC;;;;;;;AAQA,SAAgB,YAAe,SAAe;CAC5C,OAAO,gBAAgB,aAAa;AACtC;;AAGA,SAAgB,QAAQ,WAA4C;CAClE,gBAAgB,SAAS;AAC3B;;AAGA,SAAgB,QACd,WACA,UACM;CACN,gBAAgB,SAAS;AAC3B;;AAGA,SAAgB,SAAY,QAAc;CACxC,OAAO,gBAAgB,UAAU;AACnC;;AAGA,SAAgB,WAAW,OAAyB;CAClD,OAAO,gBAAgB,YAAY;AACrC;;;;;;;;AASA,SAAgB,SACd,OACA,UACqB;CACrB,OAAO,gBAAgB,UAAU;AACnC;;;;;AAMA,SAAgB,SAAS,OAAyB;CAChD,OAAO,gBAAgB,UAAU;AACnC;;;;;AAMA,SAAgB,UAAU,OAAyB;CACjD,OAAO,gBAAgB,WAAW;AACpC;;AAGA,SAAgB,MAAc;CAC5B,OAAO,gBAAgB,KAAK;AAC9B;;AAGA,SAAgB,YAAe,UAAsB,QAAiB;CACpE,gBAAgB,aAAa;AAC/B;;AAGA,SAAgB,YAAe,UAAyB;CACtD,OAAO,gBAAgB,aAAa;AACtC;;;;;;AAOA,SAAgB,OAAwC,OAAkC;CACxF,OAAO,gBAAgB,QAAQ;AACjC;AA2BA,SAAgB,eAAsB;CACpC,OAAO,gBAAgB,cAAc;AACvC;;AAGA,SAAgB,cAA+B;CAC7C,OAAO,gBAAgB,aAAa;AACtC;;AAGA,SAAgB,SAAY,SAAY,SAAuC;CAC7E,gBAAgB,UAAU;AAC5B;;AAGA,SAAgB,OAAO,QAAuB;CAC5C,gBAAgB,QAAQ;AAC1B;;;;;AAMA,SAAgB,QACd,KACoC;CACpC,OAAO,gBAAgB,SAAS;AAClC;AAWA,SAAgB,QAAe;CAC7B,OAAO,gBAAgB,OAAO;AAChC;AAiBA,SAAgB,WAAkB;CAChC,OAAO,gBAAgB,UAAU;AACnC;;;;;;AAOA,SAAgB,QAAc;CAC5B,WAA4D,OAAO,IAAI,eAAe,EAAE,GAAG;AAC7F"}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { t as LoaderOptions } from "../boot-
|
|
2
|
-
import { t as startWithoutNavigation } from "../static-loader-
|
|
1
|
+
import { t as LoaderOptions } from "../boot-CMvhoWRu.js";
|
|
2
|
+
import { t as startWithoutNavigation } from "../static-loader-CGthkX0s.js";
|
|
3
3
|
export { type LoaderOptions, startWithoutNavigation };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export { t as startWithoutNavigation } from "../static-loader-
|
|
1
|
+
export { t as startWithoutNavigation } from "../static-loader-DCxASuzA.js";
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { Wt as ClientModule } from "../client-C4kNKGwH.js";
|
|
2
|
+
import { Vt as EntryMiddleware, Yt as ServerErrorHandler, f as RenderOptions, n as Component } from "../server-dP_ucRiJ.js";
|
|
3
3
|
//#region src/runtime/testing.d.ts
|
|
4
4
|
/** The middleware of files of server functions, by function ID. */
|
|
5
5
|
type FileMiddleware = Record<string, EntryMiddleware>;
|
|
@@ -32,7 +32,25 @@ export interface Actions {
|
|
|
32
32
|
*/
|
|
33
33
|
waitFor: (assertion: () => void, timeout?: number) => Promise<void>;
|
|
34
34
|
}
|
|
35
|
-
|
|
35
|
+
/** The options of `checkAccessibility`. */
|
|
36
|
+
export interface AccessibilityOptions {
|
|
37
|
+
/** Turns axe-core rules on or off by ID, over the defaults of the test. */
|
|
38
|
+
rules?: Record<string, {
|
|
39
|
+
enabled: boolean;
|
|
40
|
+
}>;
|
|
41
|
+
}
|
|
42
|
+
export interface Checks {
|
|
43
|
+
/**
|
|
44
|
+
* Runs axe-core on what the test rendered, and throws with each violation,
|
|
45
|
+
* its element and its fix. Needs `axe-core` installed. Rules about a whole
|
|
46
|
+
* page are off for `mount`. The landmark rules, such as `landmark-one-main`,
|
|
47
|
+
* are off for `visit` while an element with `inert` or `aria-modal="true"`
|
|
48
|
+
* is in the page. Rules that need layout, such as `color-contrast`,
|
|
49
|
+
* are off, since the DOM of a test has none.
|
|
50
|
+
*/
|
|
51
|
+
checkAccessibility: (options?: AccessibilityOptions) => Promise<void>;
|
|
52
|
+
}
|
|
53
|
+
export interface Mounted extends Actions, Checks {
|
|
36
54
|
/** The element that holds the component. */
|
|
37
55
|
container: HTMLElement;
|
|
38
56
|
/** Stops the loader and removes the component. */
|
|
@@ -59,6 +77,8 @@ export interface AnswerOptions {
|
|
|
59
77
|
onCall?: (id: string) => void;
|
|
60
78
|
/** The middleware of the entry, which runs before each call. `virtual:brumate/testing` passes the app's. */
|
|
61
79
|
middleware?: EntryMiddleware;
|
|
80
|
+
/** The `onError` of the entry middleware, which gets the errors of calls. `virtual:brumate/testing` passes the app's. */
|
|
81
|
+
onError?: ServerErrorHandler;
|
|
62
82
|
/**
|
|
63
83
|
* The middleware of each `'use server'` file, by function ID, or a
|
|
64
84
|
* function that imports them. `virtual:brumate/testing` passes them.
|
|
@@ -92,7 +112,7 @@ export interface VisitOptions {
|
|
|
92
112
|
/** A selector of elements that stay out of view until `reveal` brings them in. */
|
|
93
113
|
offscreen?: string;
|
|
94
114
|
}
|
|
95
|
-
export interface Visited extends Actions {
|
|
115
|
+
export interface Visited extends Actions, Checks {
|
|
96
116
|
/** The path and the query of the page, such as `/issues?q=bug`. It changes with client navigation. */
|
|
97
117
|
readonly url: string;
|
|
98
118
|
/** The status of the first page. */
|
package/dist/runtime/testing.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { d as handleRequest, x as render } from "../server-
|
|
2
|
-
import { t as start } from "../loader-
|
|
1
|
+
import { d as handleRequest, x as render } from "../server-BcT9icQ4.js";
|
|
2
|
+
import { t as start } from "../loader-CQkAXO0g.js";
|
|
3
3
|
//#region src/runtime/nodes.ts
|
|
4
4
|
const VOID = /* @__PURE__ */ new Set([
|
|
5
5
|
"area",
|
|
@@ -42,6 +42,67 @@ function wholeNodes(markup) {
|
|
|
42
42
|
}
|
|
43
43
|
//#endregion
|
|
44
44
|
//#region src/runtime/testing.ts
|
|
45
|
+
/** The rules about the document itself, which stay on for a page that an inert background covers. */
|
|
46
|
+
const DOCUMENT_RULES = [
|
|
47
|
+
"bypass",
|
|
48
|
+
"document-title",
|
|
49
|
+
"html-has-lang",
|
|
50
|
+
"html-lang-valid"
|
|
51
|
+
];
|
|
52
|
+
/** The rules about the landmarks of a page, which an inert background breaks. */
|
|
53
|
+
const LANDMARK_RULES = [
|
|
54
|
+
"landmark-one-main",
|
|
55
|
+
"page-has-heading-one",
|
|
56
|
+
"region",
|
|
57
|
+
"landmark-unique",
|
|
58
|
+
"landmark-no-duplicate-banner",
|
|
59
|
+
"landmark-no-duplicate-contentinfo",
|
|
60
|
+
"landmark-no-duplicate-main",
|
|
61
|
+
"landmark-banner-is-top-level",
|
|
62
|
+
"landmark-contentinfo-is-top-level",
|
|
63
|
+
"landmark-main-is-top-level",
|
|
64
|
+
"landmark-complementary-is-top-level"
|
|
65
|
+
];
|
|
66
|
+
/** The rules that need layout, which happy-dom has none of. */
|
|
67
|
+
const LAYOUT_RULES = [
|
|
68
|
+
"color-contrast",
|
|
69
|
+
"color-contrast-enhanced",
|
|
70
|
+
"scrollable-region-focusable"
|
|
71
|
+
];
|
|
72
|
+
/** Loads axe-core, or says how to install it. */
|
|
73
|
+
async function loadAxe() {
|
|
74
|
+
try {
|
|
75
|
+
const module = await import("axe-core");
|
|
76
|
+
return module.default ?? module;
|
|
77
|
+
} catch (cause) {
|
|
78
|
+
throw new Error("checkAccessibility needs axe-core. Install it with: npm install --save-dev axe-core", { cause });
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
/** The accessibility check for the elements inside `root`. */
|
|
82
|
+
function checks(root, wholePage) {
|
|
83
|
+
return { checkAccessibility: async (options = {}) => {
|
|
84
|
+
const axe = await loadAxe();
|
|
85
|
+
const rules = {};
|
|
86
|
+
for (const id of LAYOUT_RULES) rules[id] = { enabled: false };
|
|
87
|
+
const inert = wholePage && document.querySelector("[inert], [aria-modal=\"true\"]") !== null;
|
|
88
|
+
if (!wholePage || inert) for (const id of LANDMARK_RULES) rules[id] = { enabled: false };
|
|
89
|
+
if (!wholePage) for (const id of DOCUMENT_RULES) rules[id] = { enabled: false };
|
|
90
|
+
const { violations } = await axe.run(root, { rules: {
|
|
91
|
+
...rules,
|
|
92
|
+
...options.rules
|
|
93
|
+
} });
|
|
94
|
+
if (violations.length === 0) return;
|
|
95
|
+
const lines = [];
|
|
96
|
+
for (const violation of violations) {
|
|
97
|
+
lines.push(`${violation.id}: ${violation.help} (${violation.helpUrl})`);
|
|
98
|
+
for (const node of violation.nodes) {
|
|
99
|
+
lines.push(` ${node.html}`);
|
|
100
|
+
if (node.failureSummary) lines.push(` ${node.failureSummary.replaceAll("\n", "\n ")}`);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
throw new Error(`${violations.length} accessibility violation(s):\n${lines.join("\n")}`);
|
|
104
|
+
} };
|
|
105
|
+
}
|
|
45
106
|
let view;
|
|
46
107
|
/** Reports an element that waits out of view, as visible. */
|
|
47
108
|
function reveal(element) {
|
|
@@ -251,6 +312,7 @@ function createMount(options) {
|
|
|
251
312
|
return {
|
|
252
313
|
container,
|
|
253
314
|
...actions(container),
|
|
315
|
+
...checks(container, false),
|
|
254
316
|
unmount: () => {
|
|
255
317
|
stop();
|
|
256
318
|
container.remove();
|
|
@@ -305,6 +367,7 @@ function answerCalls(functions, options = {}) {
|
|
|
305
367
|
function handle() {
|
|
306
368
|
return handleRequest(registry, request, prefix, {
|
|
307
369
|
middleware: options.middleware,
|
|
370
|
+
onError: options.onError,
|
|
308
371
|
fileMiddleware
|
|
309
372
|
});
|
|
310
373
|
}
|
|
@@ -465,6 +528,7 @@ function createVisit(options) {
|
|
|
465
528
|
})();
|
|
466
529
|
const current = {
|
|
467
530
|
...actions(document),
|
|
531
|
+
...checks(document, true),
|
|
468
532
|
get url() {
|
|
469
533
|
return location.pathname + location.search;
|
|
470
534
|
},
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"testing.js","names":[],"sources":["../../src/runtime/nodes.ts","../../src/runtime/testing.ts"],"sourcesContent":["// Finds where whole nodes end in markup that arrives in pieces.\n\nconst VOID = new Set([\n 'area',\n 'base',\n 'br',\n 'col',\n 'embed',\n 'hr',\n 'img',\n 'input',\n 'link',\n 'meta',\n 'source',\n 'track',\n 'wbr',\n]);\n\n/**\n * The end of the last whole node at the top level of markup that streams in,\n * so a chunk that ends inside a tag, the text of a script or a template\n * waits for the rest. A `>` in an attribute or a script does not end a node.\n */\nexport function wholeNodes(markup: string): number {\n const tag = /<(\\/?)([a-zA-Z][\\w-]*)(?:[^>\"']|\"[^\"]*\"|'[^']*')*>/g;\n const lower = markup.toLowerCase();\n let depth = 0;\n let end = 0;\n let match: RegExpExecArray | null;\n while ((match = tag.exec(markup))) {\n const [whole, closing, name] = match;\n const element = name!.toLowerCase();\n if (!closing && element === 'script') {\n // The text of a script is not markup, and ends only at `</script`.\n const close = lower.indexOf('</script', tag.lastIndex);\n const after = close < 0 ? -1 : markup.indexOf('>', close);\n if (after < 0) {\n return end;\n }\n tag.lastIndex = after + 1;\n } else if (!VOID.has(element) && !whole.endsWith('/>')) {\n depth += closing ? -1 : 1;\n }\n if (depth === 0) {\n end = tag.lastIndex;\n }\n }\n return end;\n}\n","// Renders a component on the server and resumes it in the DOM of a test, as\n// a page does: the HTML and the state first, then the loader, which loads\n// client code when an event fires. `visit` does the same for a route, with\n// the requests of the page answered by the routes of the app.\n//\n// The triggers of `$client`, `#client` and `#defer` fire as follows:\n// - 'load' fires when the loader starts.\n// - 'visible' fires when the IntersectionObserver that `mount` and `visit`\n// install reports the element, which it does at once unless the test keeps\n// the element out of view.\n// - 'idle' fires as in a browser that has no requestIdleCallback, which\n// includes happy-dom: on a timer after the page starts. The loader decides\n// this, so a test needs no action for it.\n\nimport type { ClientModule } from './client.ts';\nimport { start } from './loader.ts';\nimport { wholeNodes } from './nodes.ts';\nimport { handleRequest, render } from './server.ts';\nimport type { Component, EntryMiddleware, RenderOptions } from './server.ts';\n\n/** The middleware of files of server functions, by function ID. */\ntype FileMiddleware = Record<string, EntryMiddleware>;\n\nexport interface TestingOptions {\n /** Imports the client module of a component, by component ID. */\n load: (id: string) => Promise<ClientModule>;\n /** The URL prefix of server function calls. */\n rpc?: string;\n}\n\n/** What a test does with the page, as a user does. */\nexport interface Actions {\n /** The first element that matches a selector. Throws if none does. */\n get: (selector: string) => HTMLElement;\n /** The text of the first element that matches a selector. */\n text: (selector: string) => string;\n /** Clicks an element. */\n click: (selector: string) => void;\n /** Types a value into a field, and fires `input`. */\n input: (selector: string, value: string) => void;\n /** Submits a form, as its submit button does. */\n submit: (selector: string) => void;\n /**\n * Brings the elements that match a selector into view, so what waits for\n * them with the 'visible' trigger runs. See `offscreen`.\n */\n reveal: (selector: string) => void;\n /**\n * Retries an assertion until it passes. The first event of a test loads\n * client code, so its effects arrive a moment later.\n */\n waitFor: (assertion: () => void, timeout?: number) => Promise<void>;\n}\n\nexport interface Mounted extends Actions {\n /** The element that holds the component. */\n container: HTMLElement;\n /** Stops the loader and removes the component. */\n unmount: () => void;\n}\n\n/** The elements that the test keeps out of view, and the observers that wait for them. */\ninterface View {\n /** The selectors of `offscreen`, one entry for each mount or visit. */\n hidden: Set<{ selector: string }>;\n /** The elements that the test brought into view. */\n revealed: WeakSet<Element>;\n /** Reports an element to the observers that wait for it, as visible. */\n waiting: Set<{ element: Element; report: () => void }>;\n users: number;\n original: typeof IntersectionObserver | undefined;\n}\n\nlet view: View | undefined;\n\n/** Reports an element that waits out of view, as visible. */\nfunction reveal(element: Element): void {\n view?.revealed.add(element);\n for (const entry of view?.waiting ?? []) {\n if (entry.element === element) {\n view!.waiting.delete(entry);\n entry.report();\n }\n }\n}\n\n/**\n * Replaces the IntersectionObserver of the environment with one that reports\n * each element it observes as visible, except the ones that match a selector\n * of `offscreen`. happy-dom has an observer that never reports. Returns what\n * puts the observer of the environment back.\n */\nfunction watchView(offscreen: string | undefined): () => void {\n if (!view) {\n const current: View = {\n hidden: new Set(),\n revealed: new WeakSet(),\n waiting: new Set(),\n users: 0,\n original: globalThis.IntersectionObserver,\n };\n class Reporting {\n readonly #callback: IntersectionObserverCallback;\n readonly #entries = new Set<{ element: Element; report: () => void }>();\n readonly root = null;\n readonly rootMargin = '0px';\n readonly thresholds = [0];\n constructor(callback: IntersectionObserverCallback) {\n this.#callback = callback;\n }\n observe(element: Element): void {\n const report = (): void => {\n const rect = element.getBoundingClientRect();\n this.#callback(\n [\n {\n target: element,\n isIntersecting: true,\n intersectionRatio: 1,\n boundingClientRect: rect,\n intersectionRect: rect,\n rootBounds: null,\n time: performance.now(),\n },\n ],\n this as unknown as IntersectionObserver,\n );\n };\n const entry = { element, report };\n this.#entries.add(entry);\n let isHidden = false;\n if (!current.revealed.has(element)) {\n for (const { selector } of current.hidden) {\n if (element.matches(selector)) {\n isHidden = true;\n break;\n }\n }\n }\n if (isHidden) {\n current.waiting.add(entry);\n } else {\n queueMicrotask(() => {\n if (this.#entries.has(entry)) {\n report();\n }\n });\n }\n }\n unobserve(element: Element): void {\n for (const entry of this.#entries) {\n if (entry.element === element) {\n this.#entries.delete(entry);\n current.waiting.delete(entry);\n }\n }\n }\n disconnect(): void {\n for (const entry of this.#entries) {\n current.waiting.delete(entry);\n }\n this.#entries.clear();\n }\n takeRecords(): IntersectionObserverEntry[] {\n return [];\n }\n }\n globalThis.IntersectionObserver = Reporting as unknown as typeof IntersectionObserver;\n view = current;\n }\n const current = view;\n current.users++;\n // One entry for each user, so two mounts that keep out the same selector do not clear each other.\n const hidden = { selector: offscreen ?? '' };\n if (offscreen !== undefined) {\n current.hidden.add(hidden);\n }\n let released = false;\n return () => {\n if (released) {\n return;\n }\n released = true;\n current.hidden.delete(hidden);\n if (--current.users === 0) {\n if (current.original) {\n globalThis.IntersectionObserver = current.original;\n } else {\n delete (globalThis as { IntersectionObserver?: unknown }).IntersectionObserver;\n }\n current.waiting.clear();\n view = undefined;\n }\n };\n}\n\n/** The actions on the elements inside `root`. */\nfunction actions(root: ParentNode): Actions {\n function get(selector: string): HTMLElement {\n const element = root.querySelector<HTMLElement>(selector);\n if (!element) {\n throw new Error(`No element matches ${selector}`);\n }\n return element;\n }\n return {\n get,\n text: (selector) => get(selector).textContent ?? '',\n click: (selector) => get(selector).click(),\n input: (selector, value) => {\n const field = get(selector) as HTMLInputElement;\n field.value = value;\n field.dispatchEvent(new Event('input', { bubbles: true }));\n },\n submit: (selector) => {\n get(selector).dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }));\n },\n reveal: (selector) => {\n for (const element of root.querySelectorAll(selector)) {\n reveal(element);\n }\n },\n waitFor: async (assertion, timeout = 2000) => {\n const until = Date.now() + timeout;\n for (;;) {\n try {\n assertion();\n return;\n } catch (error) {\n if (Date.now() > until) {\n throw error;\n }\n // oxlint-disable-next-line no-await-in-loop -- It waits between tries.\n await new Promise((resolve) => setTimeout(resolve, 10));\n }\n }\n },\n };\n}\n\n/**\n * Runs an inline script, as a browser does when it adds one. The DOM of a\n * test does not run scripts. The script is `document.currentScript` while it\n * runs, so a state record hands its script to the core.\n */\nfunction run(script: Element): void {\n Object.defineProperty(document, 'currentScript', { configurable: true, value: script });\n try {\n // oxlint-disable-next-line no-eval -- The script is a state record or the swap code from the server.\n (0, eval)(script.textContent!);\n } finally {\n delete (document as { currentScript?: unknown }).currentScript;\n }\n}\n\n/**\n * Appends markup that streams in later, such as a `#loading` body, and runs\n * its inline scripts in order.\n */\nfunction append(container: HTMLElement, html: string): void {\n const template = document.createElement('template');\n template.innerHTML = html;\n // A copy, because appending moves nodes out of the live list.\n // oxlint-disable-next-line unicorn/no-useless-spread\n for (const node of [...template.content.childNodes]) {\n container.append(node);\n if (node.nodeName === 'SCRIPT' && !(node as Element).hasAttribute('type')) {\n run(node as Element);\n }\n }\n}\n\n/** Renders a component on the server and resumes it in the document of a test. */\nexport type Mount = <P>(\n component: Component<P>,\n props: P,\n renderOptions?: MountRenderOptions,\n) => Promise<Mounted>;\n\n/** The options of `render`, and the elements to keep out of view. */\nexport interface MountRenderOptions extends RenderOptions {\n /**\n * A selector of elements that stay out of view, for a test of what waits\n * for them with the 'visible' trigger. `reveal` brings them into view.\n */\n offscreen?: string;\n}\n\n/** Mounts so far, so each starts its scope IDs at a number of its own. */\nlet mounts = 0;\n/** The loader that the mounts of the document share, and how many mounts use it. */\nlet loader: { stop: () => void; users: number } | undefined;\n\n/** Returns `mount`, which loads client modules with `options.load`. */\nexport function createMount(options: TestingOptions): Mount {\n /**\n * Renders a component on the server, puts it in the document with its\n * state, and starts the loader. Markup that streams in later is added as\n * it arrives.\n */\n return async function mount<P>(\n component: Component<P>,\n props: P,\n { offscreen, ...renderOptions }: MountRenderOptions = {},\n ): Promise<Mounted> {\n // IDs of their own, so two mounts in a file do not share scopes or state references.\n const base = renderOptions.base ?? ++mounts * 1_000_000;\n const { html, state, pending } = await render(component, props, { ...renderOptions, base });\n const unwatch = watchView(offscreen);\n const container = document.createElement('div');\n container.innerHTML = html + state;\n document.body.append(container);\n // The page state, which waits for the core.\n for (const script of container.querySelectorAll('script[b-state]')) {\n run(script);\n }\n // One loader for the document, as a page has, however many mounts are in it.\n loader ??= {\n stop: start({ load: options.load, rpc: options.rpc, navigate: false }),\n users: 0,\n };\n loader.users++;\n let mounted = true;\n function stop(): void {\n if (!mounted || !loader) {\n return;\n }\n mounted = false;\n unwatch();\n if (--loader.users === 0) {\n loader.stop();\n loader = undefined;\n }\n }\n void (async () => {\n for await (const chunk of pending) {\n append(container, chunk);\n }\n })();\n return {\n container,\n ...actions(container),\n unmount: () => {\n stop();\n container.remove();\n // The core forgets the scopes of this mount, so a refresh later does not load its memos.\n void import('./client.ts').then((core) => core.removeRoot(String(base)));\n },\n };\n };\n}\n\n/** Server functions by ID, as `functions` of `virtual:brumate/server` has them. */\n// oxlint-disable-next-line typescript/no-explicit-any -- Server functions take any arguments.\nexport type ServerFunctions = Record<string, (...args: any[]) => unknown>;\n\nexport interface AnswerOptions {\n /** The URL prefix of server function calls. Defaults to `/_brumate`. */\n rpc?: string;\n /** Called with the ID of each call, such as `issues_1a2b#toggleStar`, before it runs. */\n onCall?: (id: string) => void;\n /** The middleware of the entry, which runs before each call. `virtual:brumate/testing` passes the app's. */\n middleware?: EntryMiddleware;\n /**\n * The middleware of each `'use server'` file, by function ID, or a\n * function that imports them. `virtual:brumate/testing` passes them.\n */\n fileMiddleware?: FileMiddleware | (() => Promise<FileMiddleware>);\n}\n\n/** What `run` of `AsyncLocalStorage` looks like, the part that `answerCalls` uses. */\ninterface Storage {\n run: <T>(store: string, callback: () => T) => T;\n getStore: () => string | undefined;\n}\n\nlet storage: Promise<Storage | undefined> | undefined;\n\n/**\n * Tells the calls that a server function makes while it is answered. Node\n * has `AsyncLocalStorage`. Elsewhere, such as in a browser, there is none,\n * and nested calls are not told apart.\n */\nfunction callStorage(): Promise<Storage | undefined> {\n storage ??= import('node:async_hooks').then(\n ({ AsyncLocalStorage }) => new AsyncLocalStorage<string>() as Storage,\n () => undefined,\n );\n return storage;\n}\n\n/**\n * Answers the server function calls of the page in the test, with\n * `functions`, through the same request and answer as a server. Calls go\n * through `fetch`, so it replaces `fetch` until the returned function\n * restores it. Other requests go to the `fetch` from before.\n *\n * `functions` can be a function that returns them, so they are imported on\n * the first call. A server function that calls a server function through\n * `fetch`, as a browser stub does, throws: it would call itself without end.\n */\nexport function answerCalls(\n functions: ServerFunctions | (() => Promise<ServerFunctions>),\n options: AnswerOptions = {},\n): () => void {\n const prefix = options.rpc ?? '/_brumate';\n const original = globalThis.fetch;\n let loaded: Promise<ServerFunctions> | undefined;\n /** The error of a call that a server function made through `fetch`. */\n let failure: Error | undefined;\n async function answer(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {\n const base = globalThis.location?.href ?? 'http://localhost/';\n const url = new URL(input instanceof Request ? input.url : String(input), base);\n if (!url.pathname.startsWith(`${prefix}/`)) {\n return original(input, init);\n }\n const id = decodeURIComponent(url.pathname.slice(prefix.length + 1));\n const calls = await callStorage();\n const caller = calls?.getStore();\n if (caller !== undefined) {\n // The outer call answers with a generic error, so the error goes to its caller too.\n failure ??= new Error(\n `The server function \"${caller}\" called \"${id}\" through fetch, as a browser stub does. In a test, server code imports the server code of a 'use server' file: import components with ?brumate-server, and answer calls with the functions of virtual:brumate/server`,\n );\n throw failure;\n }\n options.onCall?.(id);\n loaded ??= Promise.resolve(typeof functions === 'function' ? functions() : functions);\n const registry = await loaded;\n const request = input instanceof Request ? new Request(input, init) : new Request(url, init);\n const guards = options.fileMiddleware;\n const fileMiddleware = typeof guards === 'function' ? await guards() : guards;\n function handle(): Promise<Response | undefined> {\n return handleRequest(registry, request, prefix, {\n middleware: options.middleware,\n fileMiddleware,\n });\n }\n const response = await (calls ? calls.run(id, handle) : handle());\n if (failure) {\n const error = failure;\n failure = undefined;\n throw error;\n }\n return response ?? original(input, init);\n }\n globalThis.fetch = answer as typeof fetch;\n return () => {\n // A later `answerCalls` or stub keeps its own `fetch`.\n if (globalThis.fetch === answer) {\n globalThis.fetch = original;\n }\n };\n}\n\n/** Answers a request as the server of the app does, or undefined when nothing does. */\nexport type RequestHandler = (request: Request) => Promise<Response | undefined>;\n\nexport interface VisitorOptions extends TestingOptions {\n /** Answers the requests for pages, forms without scripts, `#defer` bodies and endpoints. */\n routes: () => Promise<RequestHandler>;\n /** Answers server function calls. */\n calls: () => Promise<RequestHandler>;\n}\n\nexport interface VisitOptions {\n /** Cookies that the browser has before the first request, by name. */\n cookies?: Record<string, string>;\n /** Headers of every request, such as `accept-language`. */\n headers?: HeadersInit;\n /** A selector of elements that stay out of view until `reveal` brings them in. */\n offscreen?: string;\n}\n\nexport interface Visited extends Actions {\n /** The path and the query of the page, such as `/issues?q=bug`. It changes with client navigation. */\n readonly url: string;\n /** The status of the first page. */\n status: number;\n /** The cookies that the browser has now, by name. */\n readonly cookies: Record<string, string>;\n /** Stops the loader, puts `fetch` back and empties the document. */\n close: () => void;\n}\n\n/** Visits a path of the app, as a browser that runs scripts does. */\nexport type Visit = (path: string, options?: VisitOptions) => Promise<Visited>;\n\nconst REDIRECTS = new Set([301, 302, 303, 307, 308]);\n\n/** Reads the `set-cookie` headers of a response into the cookies of the browser. */\nfunction storeCookies(jar: Map<string, string>, response: Response): void {\n for (const header of response.headers.getSetCookie()) {\n const [pair = '', ...attributes] = header.split(';');\n const equals = pair.indexOf('=');\n const name = pair.slice(0, equals).trim();\n if (equals < 1) {\n continue;\n }\n let gone = false;\n for (const attribute of attributes) {\n const [key = '', value = ''] = attribute.trim().split('=');\n const lower = key.toLowerCase();\n if (\n (lower === 'max-age' && Number(value) <= 0) ||\n (lower === 'expires' && Date.parse(value) <= Date.now())\n ) {\n gone = true;\n break;\n }\n }\n if (gone) {\n jar.delete(name);\n } else {\n jar.set(name, pair.slice(equals + 1).trim());\n }\n }\n}\n\n/** The page that a visit holds, so a new visit closes the one before. */\nlet visited: Visited | undefined;\n\n/** Returns `visit`, which answers the requests of the page with the routes of the app. */\nexport function createVisit(options: VisitorOptions): Visit {\n const prefix = options.rpc ?? '/_brumate';\n /**\n * Answers the path with the routes of the app, puts the page in the\n * document, and starts the loader with client navigation. Links, forms,\n * server function calls and `#defer` requests of the page go to the same\n * routes, without a server, with the cookies that the answers set.\n */\n return async function visit(path, visitOptions = {}) {\n visited?.close();\n const jar = new Map(Object.entries(visitOptions.cookies ?? {}));\n const original = globalThis.fetch;\n const origin = location.origin;\n history.replaceState(null, '', new URL(path, origin));\n\n // A browser follows redirects, sends its cookies, and keeps the ones that the answers set.\n async function answer(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {\n let url = new URL(input instanceof Request ? input.url : String(input), location.href);\n if (url.origin !== origin) {\n return original(input, init);\n }\n let method = (\n init?.method ?? (input instanceof Request ? input.method : 'GET')\n ).toUpperCase();\n let body = init?.body ?? undefined;\n const extra = new Headers(input instanceof Request ? input.headers : undefined);\n for (const [name, value] of new Headers(init?.headers)) {\n extra.set(name, value);\n }\n for (let hops = 0; ; hops++) {\n const request = new Request(url, { method, body, signal: init?.signal ?? null });\n // Set after the request is made, since a DOM environment drops these from its init.\n for (const [name, value] of new Headers(visitOptions.headers)) {\n request.headers.set(name, value);\n }\n for (const [name, value] of extra) {\n request.headers.set(name, value);\n }\n if (jar.size > 0) {\n const cookies: string[] = [];\n for (const [name, value] of jar) {\n cookies.push(`${name}=${value}`);\n }\n request.headers.set('cookie', cookies.join('; '));\n }\n if (method !== 'GET' && method !== 'HEAD') {\n request.headers.set('origin', origin);\n }\n const handle = url.pathname.startsWith(`${prefix}/`) ? options.calls : options.routes;\n const answered = handle().then((handler) => handler(request));\n // oxlint-disable-next-line no-await-in-loop -- Each redirect is a request of its own.\n const response = (await answered) ?? new Response('Not found', { status: 404 });\n storeCookies(jar, response);\n const location = response.headers.get('location');\n if (!REDIRECTS.has(response.status) || !location || init?.redirect === 'manual') {\n Object.defineProperty(response, 'url', { value: url.href });\n return response;\n }\n if (hops === 20) {\n throw new TypeError(`Too many redirects from ${path}`);\n }\n url = new URL(location, url);\n // As in fetch: 303 asks for the page with GET, and so do 301 and 302 after a POST.\n // 307 and 308 send the request again as it was.\n if (\n (response.status === 303 && method !== 'HEAD') ||\n (method === 'POST' && (response.status === 301 || response.status === 302))\n ) {\n method = 'GET';\n body = undefined;\n extra.delete('content-type');\n }\n }\n }\n globalThis.fetch = answer as typeof fetch;\n\n // The DOM of a test does not run scripts, so the ones that the page adds run here, once each.\n const ran = new WeakSet<Element>();\n function runOnce(script: Element): void {\n if (!ran.has(script) && !script.hasAttribute('src') && !script.hasAttribute('type')) {\n ran.add(script);\n run(script);\n }\n }\n const scripts = new MutationObserver((records) => {\n for (const record of records) {\n for (const node of record.addedNodes) {\n if (node.nodeName === 'SCRIPT') {\n runOnce(node as Element);\n } else if (node instanceof Element) {\n for (const script of node.querySelectorAll('script')) {\n runOnce(script);\n }\n }\n }\n }\n });\n\n const response = await answer(path);\n // The page is at the URL of the last redirect.\n history.replaceState(null, '', response.url);\n const reader = response.body!.pipeThrough(new TextDecoderStream()).getReader();\n let html = '';\n let end = -1;\n let done = false;\n while (end < 0 && !done) {\n // oxlint-disable-next-line no-await-in-loop -- The page arrives in pieces.\n const chunk = await reader.read();\n done = chunk.done;\n html += chunk.value ?? '';\n end = html.search(/<\\/html>/i);\n }\n const cut = end < 0 ? html.length : end + '</html>'.length;\n const page = new DOMParser().parseFromString(html.slice(0, cut), 'text/html');\n for (const name of document.documentElement.getAttributeNames()) {\n document.documentElement.removeAttribute(name);\n }\n for (const attribute of page.documentElement.attributes) {\n document.documentElement.setAttribute(attribute.name, attribute.value);\n }\n const headNodes: Node[] = [];\n for (const node of page.head.childNodes) {\n headNodes.push(document.importNode(node, true));\n }\n document.head.replaceChildren(...headNodes);\n const bodyNodes: Node[] = [];\n for (const node of page.body.childNodes) {\n bodyNodes.push(document.importNode(node, true));\n }\n document.body.replaceChildren(...bodyNodes);\n for (const script of document.querySelectorAll('script')) {\n runOnce(script);\n }\n scripts.observe(document, { childList: true, subtree: true });\n\n const unwatch = watchView(visitOptions.offscreen);\n const stop = start({ load: options.load, rpc: prefix, navigate: true });\n let rest = html.slice(cut);\n let open = true;\n void (async () => {\n while (!done) {\n // oxlint-disable-next-line no-await-in-loop -- Later markup arrives in pieces.\n const chunk = await reader.read();\n done = chunk.done;\n rest += chunk.value ?? '';\n // A chunk can end inside a tag, a script or a template, so only whole nodes move in.\n const last = done ? rest.length : wholeNodes(rest);\n if (last > 0 && open) {\n // The observer runs its scripts.\n const template = document.createElement('template');\n template.innerHTML = rest.slice(0, last);\n document.body.append(template.content);\n rest = rest.slice(last);\n }\n }\n })();\n\n const current: Visited = {\n ...actions(document),\n get url() {\n return location.pathname + location.search;\n },\n status: response.status,\n get cookies() {\n return Object.fromEntries(jar);\n },\n close: () => {\n if (!open) {\n return;\n }\n open = false;\n visited = undefined;\n stop();\n unwatch();\n scripts.disconnect();\n reader.cancel().catch(() => {});\n if (globalThis.fetch === answer) {\n globalThis.fetch = original;\n }\n // The core forgets the page, so the next visit starts its IDs again.\n void import('./client.ts').then((core) => core.leavePage());\n document.head.replaceChildren();\n document.body.replaceChildren();\n },\n };\n visited = current;\n return current;\n };\n}\n"],"mappings":";;;AAEA,MAAM,uBAAO,IAAI,IAAI;CACnB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;;;;;AAOD,SAAgB,WAAW,QAAwB;CACjD,MAAM,MAAM;CACZ,MAAM,QAAQ,OAAO,YAAY;CACjC,IAAI,QAAQ;CACZ,IAAI,MAAM;CACV,IAAI;CACJ,OAAQ,QAAQ,IAAI,KAAK,MAAM,GAAI;EACjC,MAAM,CAAC,OAAO,SAAS,QAAQ;EAC/B,MAAM,UAAU,KAAM,YAAY;EAClC,IAAI,CAAC,WAAW,YAAY,UAAU;GAEpC,MAAM,QAAQ,MAAM,QAAQ,aAAY,IAAI,SAAS;GACrD,MAAM,QAAQ,QAAQ,IAAI,K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QACvB,WAAW,QAAQ;IAGrB,OAAY,cAAc,CAAC,MAAM,SAAS,KAAK,UAAU,CAAC;IAC1D,SAAS,KAAK,gBAAgB;IAC9B,SAAS,KAAK,gBAAgB;GAChC;EACF;EACA,UAAU;EACV,OAAO;CACT;AACF"}
|
|
1
|
+
{"version":3,"file":"testing.js","names":[],"sources":["../../src/runtime/nodes.ts","../../src/runtime/testing.ts"],"sourcesContent":["// Finds where whole nodes end in markup that arrives in pieces.\n\nconst VOID = new Set([\n 'area',\n 'base',\n 'br',\n 'col',\n 'embed',\n 'hr',\n 'img',\n 'input',\n 'link',\n 'meta',\n 'source',\n 'track',\n 'wbr',\n]);\n\n/**\n * The end of the last whole node at the top level of markup that streams in,\n * so a chunk that ends inside a tag, the text of a script or a template\n * waits for the rest. A `>` in an attribute or a script does not end a node.\n */\nexport function wholeNodes(markup: string): number {\n const tag = /<(\\/?)([a-zA-Z][\\w-]*)(?:[^>\"']|\"[^\"]*\"|'[^']*')*>/g;\n const lower = markup.toLowerCase();\n let depth = 0;\n let end = 0;\n let match: RegExpExecArray | null;\n while ((match = tag.exec(markup))) {\n const [whole, closing, name] = match;\n const element = name!.toLowerCase();\n if (!closing && element === 'script') {\n // The text of a script is not markup, and ends only at `</script`.\n const close = lower.indexOf('</script', tag.lastIndex);\n const after = close < 0 ? -1 : markup.indexOf('>', close);\n if (after < 0) {\n return end;\n }\n tag.lastIndex = after + 1;\n } else if (!VOID.has(element) && !whole.endsWith('/>')) {\n depth += closing ? -1 : 1;\n }\n if (depth === 0) {\n end = tag.lastIndex;\n }\n }\n return end;\n}\n","// Renders a component on the server and resumes it in the DOM of a test, as\n// a page does: the HTML and the state first, then the loader, which loads\n// client code when an event fires. `visit` does the same for a route, with\n// the requests of the page answered by the routes of the app.\n//\n// The triggers of `$client`, `#client` and `#defer` fire as follows:\n// - 'load' fires when the loader starts.\n// - 'visible' fires when the IntersectionObserver that `mount` and `visit`\n// install reports the element, which it does at once unless the test keeps\n// the element out of view.\n// - 'idle' fires as in a browser that has no requestIdleCallback, which\n// includes happy-dom: on a timer after the page starts. The loader decides\n// this, so a test needs no action for it.\n\nimport type { ClientModule } from './client.ts';\nimport { start } from './loader.ts';\nimport { wholeNodes } from './nodes.ts';\nimport { handleRequest, render } from './server.ts';\nimport type { Component, EntryMiddleware, RenderOptions, ServerErrorHandler } from './server.ts';\n\n/** The middleware of files of server functions, by function ID. */\ntype FileMiddleware = Record<string, EntryMiddleware>;\n\nexport interface TestingOptions {\n /** Imports the client module of a component, by component ID. */\n load: (id: string) => Promise<ClientModule>;\n /** The URL prefix of server function calls. */\n rpc?: string;\n}\n\n/** What a test does with the page, as a user does. */\nexport interface Actions {\n /** The first element that matches a selector. Throws if none does. */\n get: (selector: string) => HTMLElement;\n /** The text of the first element that matches a selector. */\n text: (selector: string) => string;\n /** Clicks an element. */\n click: (selector: string) => void;\n /** Types a value into a field, and fires `input`. */\n input: (selector: string, value: string) => void;\n /** Submits a form, as its submit button does. */\n submit: (selector: string) => void;\n /**\n * Brings the elements that match a selector into view, so what waits for\n * them with the 'visible' trigger runs. See `offscreen`.\n */\n reveal: (selector: string) => void;\n /**\n * Retries an assertion until it passes. The first event of a test loads\n * client code, so its effects arrive a moment later.\n */\n waitFor: (assertion: () => void, timeout?: number) => Promise<void>;\n}\n\n/** The options of `checkAccessibility`. */\nexport interface AccessibilityOptions {\n /** Turns axe-core rules on or off by ID, over the defaults of the test. */\n rules?: Record<string, { enabled: boolean }>;\n}\n\n/** The part of axe-core that the check uses. */\ninterface Axe {\n run: (\n context: Element | Document,\n options: { rules: Record<string, { enabled: boolean }> },\n ) => Promise<{\n violations: {\n id: string;\n help: string;\n helpUrl: string;\n nodes: { target: unknown[]; html: string; failureSummary?: string }[];\n }[];\n }>;\n}\n\nexport interface Checks {\n /**\n * Runs axe-core on what the test rendered, and throws with each violation,\n * its element and its fix. Needs `axe-core` installed. Rules about a whole\n * page are off for `mount`. The landmark rules, such as `landmark-one-main`,\n * are off for `visit` while an element with `inert` or `aria-modal=\"true\"`\n * is in the page. Rules that need layout, such as `color-contrast`,\n * are off, since the DOM of a test has none.\n */\n checkAccessibility: (options?: AccessibilityOptions) => Promise<void>;\n}\n\n/** The rules about the document itself, which stay on for a page that an inert background covers. */\nconst DOCUMENT_RULES = ['bypass', 'document-title', 'html-has-lang', 'html-lang-valid'];\n\n/** The rules about the landmarks of a page, which an inert background breaks. */\nconst LANDMARK_RULES = [\n 'landmark-one-main',\n 'page-has-heading-one',\n 'region',\n 'landmark-unique',\n 'landmark-no-duplicate-banner',\n 'landmark-no-duplicate-contentinfo',\n 'landmark-no-duplicate-main',\n 'landmark-banner-is-top-level',\n 'landmark-contentinfo-is-top-level',\n 'landmark-main-is-top-level',\n 'landmark-complementary-is-top-level',\n];\n\n/** The rules that need layout, which happy-dom has none of. */\nconst LAYOUT_RULES = ['color-contrast', 'color-contrast-enhanced', 'scrollable-region-focusable'];\n\n/** Loads axe-core, or says how to install it. */\nasync function loadAxe(): Promise<Axe> {\n try {\n const module = (await import('axe-core')) as { default?: Axe } & Axe;\n return module.default ?? module;\n } catch (cause) {\n throw new Error(\n 'checkAccessibility needs axe-core. Install it with: npm install --save-dev axe-core',\n { cause },\n );\n }\n}\n\n/** The accessibility check for the elements inside `root`. */\nfunction checks(root: Element | Document, wholePage: boolean): Checks {\n return {\n checkAccessibility: async (options = {}) => {\n const axe = await loadAxe();\n const rules: Record<string, { enabled: boolean }> = {};\n for (const id of LAYOUT_RULES) {\n rules[id] = { enabled: false };\n }\n // An element that makes the rest of the page inert breaks the landmark rules.\n const inert = wholePage && document.querySelector('[inert], [aria-modal=\"true\"]') !== null;\n if (!wholePage || inert) {\n for (const id of LANDMARK_RULES) {\n rules[id] = { enabled: false };\n }\n }\n if (!wholePage) {\n for (const id of DOCUMENT_RULES) {\n rules[id] = { enabled: false };\n }\n }\n const { violations } = await axe.run(root, { rules: { ...rules, ...options.rules } });\n if (violations.length === 0) {\n return;\n }\n const lines: string[] = [];\n for (const violation of violations) {\n lines.push(`${violation.id}: ${violation.help} (${violation.helpUrl})`);\n for (const node of violation.nodes) {\n lines.push(` ${node.html}`);\n if (node.failureSummary) {\n lines.push(` ${node.failureSummary.replaceAll('\\n', '\\n ')}`);\n }\n }\n }\n throw new Error(`${violations.length} accessibility violation(s):\\n${lines.join('\\n')}`);\n },\n };\n}\n\nexport interface Mounted extends Actions, Checks {\n /** The element that holds the component. */\n container: HTMLElement;\n /** Stops the loader and removes the component. */\n unmount: () => void;\n}\n\n/** The elements that the test keeps out of view, and the observers that wait for them. */\ninterface View {\n /** The selectors of `offscreen`, one entry for each mount or visit. */\n hidden: Set<{ selector: string }>;\n /** The elements that the test brought into view. */\n revealed: WeakSet<Element>;\n /** Reports an element to the observers that wait for it, as visible. */\n waiting: Set<{ element: Element; report: () => void }>;\n users: number;\n original: typeof IntersectionObserver | undefined;\n}\n\nlet view: View | undefined;\n\n/** Reports an element that waits out of view, as visible. */\nfunction reveal(element: Element): void {\n view?.revealed.add(element);\n for (const entry of view?.waiting ?? []) {\n if (entry.element === element) {\n view!.waiting.delete(entry);\n entry.report();\n }\n }\n}\n\n/**\n * Replaces the IntersectionObserver of the environment with one that reports\n * each element it observes as visible, except the ones that match a selector\n * of `offscreen`. happy-dom has an observer that never reports. Returns what\n * puts the observer of the environment back.\n */\nfunction watchView(offscreen: string | undefined): () => void {\n if (!view) {\n const current: View = {\n hidden: new Set(),\n revealed: new WeakSet(),\n waiting: new Set(),\n users: 0,\n original: globalThis.IntersectionObserver,\n };\n class Reporting {\n readonly #callback: IntersectionObserverCallback;\n readonly #entries = new Set<{ element: Element; report: () => void }>();\n readonly root = null;\n readonly rootMargin = '0px';\n readonly thresholds = [0];\n constructor(callback: IntersectionObserverCallback) {\n this.#callback = callback;\n }\n observe(element: Element): void {\n const report = (): void => {\n const rect = element.getBoundingClientRect();\n this.#callback(\n [\n {\n target: element,\n isIntersecting: true,\n intersectionRatio: 1,\n boundingClientRect: rect,\n intersectionRect: rect,\n rootBounds: null,\n time: performance.now(),\n },\n ],\n this as unknown as IntersectionObserver,\n );\n };\n const entry = { element, report };\n this.#entries.add(entry);\n let isHidden = false;\n if (!current.revealed.has(element)) {\n for (const { selector } of current.hidden) {\n if (element.matches(selector)) {\n isHidden = true;\n break;\n }\n }\n }\n if (isHidden) {\n current.waiting.add(entry);\n } else {\n queueMicrotask(() => {\n if (this.#entries.has(entry)) {\n report();\n }\n });\n }\n }\n unobserve(element: Element): void {\n for (const entry of this.#entries) {\n if (entry.element === element) {\n this.#entries.delete(entry);\n current.waiting.delete(entry);\n }\n }\n }\n disconnect(): void {\n for (const entry of this.#entries) {\n current.waiting.delete(entry);\n }\n this.#entries.clear();\n }\n takeRecords(): IntersectionObserverEntry[] {\n return [];\n }\n }\n globalThis.IntersectionObserver = Reporting as unknown as typeof IntersectionObserver;\n view = current;\n }\n const current = view;\n current.users++;\n // One entry for each user, so two mounts that keep out the same selector do not clear each other.\n const hidden = { selector: offscreen ?? '' };\n if (offscreen !== undefined) {\n current.hidden.add(hidden);\n }\n let released = false;\n return () => {\n if (released) {\n return;\n }\n released = true;\n current.hidden.delete(hidden);\n if (--current.users === 0) {\n if (current.original) {\n globalThis.IntersectionObserver = current.original;\n } else {\n delete (globalThis as { IntersectionObserver?: unknown }).IntersectionObserver;\n }\n current.waiting.clear();\n view = undefined;\n }\n };\n}\n\n/** The actions on the elements inside `root`. */\nfunction actions(root: ParentNode): Actions {\n function get(selector: string): HTMLElement {\n const element = root.querySelector<HTMLElement>(selector);\n if (!element) {\n throw new Error(`No element matches ${selector}`);\n }\n return element;\n }\n return {\n get,\n text: (selector) => get(selector).textContent ?? '',\n click: (selector) => get(selector).click(),\n input: (selector, value) => {\n const field = get(selector) as HTMLInputElement;\n field.value = value;\n field.dispatchEvent(new Event('input', { bubbles: true }));\n },\n submit: (selector) => {\n get(selector).dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }));\n },\n reveal: (selector) => {\n for (const element of root.querySelectorAll(selector)) {\n reveal(element);\n }\n },\n waitFor: async (assertion, timeout = 2000) => {\n const until = Date.now() + timeout;\n for (;;) {\n try {\n assertion();\n return;\n } catch (error) {\n if (Date.now() > until) {\n throw error;\n }\n // oxlint-disable-next-line no-await-in-loop -- It waits between tries.\n await new Promise((resolve) => setTimeout(resolve, 10));\n }\n }\n },\n };\n}\n\n/**\n * Runs an inline script, as a browser does when it adds one. The DOM of a\n * test does not run scripts. The script is `document.currentScript` while it\n * runs, so a state record hands its script to the core.\n */\nfunction run(script: Element): void {\n Object.defineProperty(document, 'currentScript', { configurable: true, value: script });\n try {\n // oxlint-disable-next-line no-eval -- The script is a state record or the swap code from the server.\n (0, eval)(script.textContent!);\n } finally {\n delete (document as { currentScript?: unknown }).currentScript;\n }\n}\n\n/**\n * Appends markup that streams in later, such as a `#loading` body, and runs\n * its inline scripts in order.\n */\nfunction append(container: HTMLElement, html: string): void {\n const template = document.createElement('template');\n template.innerHTML = html;\n // A copy, because appending moves nodes out of the live list.\n // oxlint-disable-next-line unicorn/no-useless-spread\n for (const node of [...template.content.childNodes]) {\n container.append(node);\n if (node.nodeName === 'SCRIPT' && !(node as Element).hasAttribute('type')) {\n run(node as Element);\n }\n }\n}\n\n/** Renders a component on the server and resumes it in the document of a test. */\nexport type Mount = <P>(\n component: Component<P>,\n props: P,\n renderOptions?: MountRenderOptions,\n) => Promise<Mounted>;\n\n/** The options of `render`, and the elements to keep out of view. */\nexport interface MountRenderOptions extends RenderOptions {\n /**\n * A selector of elements that stay out of view, for a test of what waits\n * for them with the 'visible' trigger. `reveal` brings them into view.\n */\n offscreen?: string;\n}\n\n/** Mounts so far, so each starts its scope IDs at a number of its own. */\nlet mounts = 0;\n/** The loader that the mounts of the document share, and how many mounts use it. */\nlet loader: { stop: () => void; users: number } | undefined;\n\n/** Returns `mount`, which loads client modules with `options.load`. */\nexport function createMount(options: TestingOptions): Mount {\n /**\n * Renders a component on the server, puts it in the document with its\n * state, and starts the loader. Markup that streams in later is added as\n * it arrives.\n */\n return async function mount<P>(\n component: Component<P>,\n props: P,\n { offscreen, ...renderOptions }: MountRenderOptions = {},\n ): Promise<Mounted> {\n // IDs of their own, so two mounts in a file do not share scopes or state references.\n const base = renderOptions.base ?? ++mounts * 1_000_000;\n const { html, state, pending } = await render(component, props, { ...renderOptions, base });\n const unwatch = watchView(offscreen);\n const container = document.createElement('div');\n container.innerHTML = html + state;\n document.body.append(container);\n // The page state, which waits for the core.\n for (const script of container.querySelectorAll('script[b-state]')) {\n run(script);\n }\n // One loader for the document, as a page has, however many mounts are in it.\n loader ??= {\n stop: start({ load: options.load, rpc: options.rpc, navigate: false }),\n users: 0,\n };\n loader.users++;\n let mounted = true;\n function stop(): void {\n if (!mounted || !loader) {\n return;\n }\n mounted = false;\n unwatch();\n if (--loader.users === 0) {\n loader.stop();\n loader = undefined;\n }\n }\n void (async () => {\n for await (const chunk of pending) {\n append(container, chunk);\n }\n })();\n return {\n container,\n ...actions(container),\n ...checks(container, false),\n unmount: () => {\n stop();\n container.remove();\n // The core forgets the scopes of this mount, so a refresh later does not load its memos.\n void import('./client.ts').then((core) => core.removeRoot(String(base)));\n },\n };\n };\n}\n\n/** Server functions by ID, as `functions` of `virtual:brumate/server` has them. */\n// oxlint-disable-next-line typescript/no-explicit-any -- Server functions take any arguments.\nexport type ServerFunctions = Record<string, (...args: any[]) => unknown>;\n\nexport interface AnswerOptions {\n /** The URL prefix of server function calls. Defaults to `/_brumate`. */\n rpc?: string;\n /** Called with the ID of each call, such as `issues_1a2b#toggleStar`, before it runs. */\n onCall?: (id: string) => void;\n /** The middleware of the entry, which runs before each call. `virtual:brumate/testing` passes the app's. */\n middleware?: EntryMiddleware;\n /** The `onError` of the entry middleware, which gets the errors of calls. `virtual:brumate/testing` passes the app's. */\n onError?: ServerErrorHandler;\n /**\n * The middleware of each `'use server'` file, by function ID, or a\n * function that imports them. `virtual:brumate/testing` passes them.\n */\n fileMiddleware?: FileMiddleware | (() => Promise<FileMiddleware>);\n}\n\n/** What `run` of `AsyncLocalStorage` looks like, the part that `answerCalls` uses. */\ninterface Storage {\n run: <T>(store: string, callback: () => T) => T;\n getStore: () => string | undefined;\n}\n\nlet storage: Promise<Storage | undefined> | undefined;\n\n/**\n * Tells the calls that a server function makes while it is answered. Node\n * has `AsyncLocalStorage`. Elsewhere, such as in a browser, there is none,\n * and nested calls are not told apart.\n */\nfunction callStorage(): Promise<Storage | undefined> {\n storage ??= import('node:async_hooks').then(\n ({ AsyncLocalStorage }) => new AsyncLocalStorage<string>() as Storage,\n () => undefined,\n );\n return storage;\n}\n\n/**\n * Answers the server function calls of the page in the test, with\n * `functions`, through the same request and answer as a server. Calls go\n * through `fetch`, so it replaces `fetch` until the returned function\n * restores it. Other requests go to the `fetch` from before.\n *\n * `functions` can be a function that returns them, so they are imported on\n * the first call. A server function that calls a server function through\n * `fetch`, as a browser stub does, throws: it would call itself without end.\n */\nexport function answerCalls(\n functions: ServerFunctions | (() => Promise<ServerFunctions>),\n options: AnswerOptions = {},\n): () => void {\n const prefix = options.rpc ?? '/_brumate';\n const original = globalThis.fetch;\n let loaded: Promise<ServerFunctions> | undefined;\n /** The error of a call that a server function made through `fetch`. */\n let failure: Error | undefined;\n async function answer(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {\n const base = globalThis.location?.href ?? 'http://localhost/';\n const url = new URL(input instanceof Request ? input.url : String(input), base);\n if (!url.pathname.startsWith(`${prefix}/`)) {\n return original(input, init);\n }\n const id = decodeURIComponent(url.pathname.slice(prefix.length + 1));\n const calls = await callStorage();\n const caller = calls?.getStore();\n if (caller !== undefined) {\n // The outer call answers with a generic error, so the error goes to its caller too.\n failure ??= new Error(\n `The server function \"${caller}\" called \"${id}\" through fetch, as a browser stub does. In a test, server code imports the server code of a 'use server' file: import components with ?brumate-server, and answer calls with the functions of virtual:brumate/server`,\n );\n throw failure;\n }\n options.onCall?.(id);\n loaded ??= Promise.resolve(typeof functions === 'function' ? functions() : functions);\n const registry = await loaded;\n const request = input instanceof Request ? new Request(input, init) : new Request(url, init);\n const guards = options.fileMiddleware;\n const fileMiddleware = typeof guards === 'function' ? await guards() : guards;\n function handle(): Promise<Response | undefined> {\n return handleRequest(registry, request, prefix, {\n middleware: options.middleware,\n onError: options.onError,\n fileMiddleware,\n });\n }\n const response = await (calls ? calls.run(id, handle) : handle());\n if (failure) {\n const error = failure;\n failure = undefined;\n throw error;\n }\n return response ?? original(input, init);\n }\n globalThis.fetch = answer as typeof fetch;\n return () => {\n // A later `answerCalls` or stub keeps its own `fetch`.\n if (globalThis.fetch === answer) {\n globalThis.fetch = original;\n }\n };\n}\n\n/** Answers a request as the server of the app does, or undefined when nothing does. */\nexport type RequestHandler = (request: Request) => Promise<Response | undefined>;\n\nexport interface VisitorOptions extends TestingOptions {\n /** Answers the requests for pages, forms without scripts, `#defer` bodies and endpoints. */\n routes: () => Promise<RequestHandler>;\n /** Answers server function calls. */\n calls: () => Promise<RequestHandler>;\n}\n\nexport interface VisitOptions {\n /** Cookies that the browser has before the first request, by name. */\n cookies?: Record<string, string>;\n /** Headers of every request, such as `accept-language`. */\n headers?: HeadersInit;\n /** A selector of elements that stay out of view until `reveal` brings them in. */\n offscreen?: string;\n}\n\nexport interface Visited extends Actions, Checks {\n /** The path and the query of the page, such as `/issues?q=bug`. It changes with client navigation. */\n readonly url: string;\n /** The status of the first page. */\n status: number;\n /** The cookies that the browser has now, by name. */\n readonly cookies: Record<string, string>;\n /** Stops the loader, puts `fetch` back and empties the document. */\n close: () => void;\n}\n\n/** Visits a path of the app, as a browser that runs scripts does. */\nexport type Visit = (path: string, options?: VisitOptions) => Promise<Visited>;\n\nconst REDIRECTS = new Set([301, 302, 303, 307, 308]);\n\n/** Reads the `set-cookie` headers of a response into the cookies of the browser. */\nfunction storeCookies(jar: Map<string, string>, response: Response): void {\n for (const header of response.headers.getSetCookie()) {\n const [pair = '', ...attributes] = header.split(';');\n const equals = pair.indexOf('=');\n const name = pair.slice(0, equals).trim();\n if (equals < 1) {\n continue;\n }\n let gone = false;\n for (const attribute of attributes) {\n const [key = '', value = ''] = attribute.trim().split('=');\n const lower = key.toLowerCase();\n if (\n (lower === 'max-age' && Number(value) <= 0) ||\n (lower === 'expires' && Date.parse(value) <= Date.now())\n ) {\n gone = true;\n break;\n }\n }\n if (gone) {\n jar.delete(name);\n } else {\n jar.set(name, pair.slice(equals + 1).trim());\n }\n }\n}\n\n/** The page that a visit holds, so a new visit closes the one before. */\nlet visited: Visited | undefined;\n\n/** Returns `visit`, which answers the requests of the page with the routes of the app. */\nexport function createVisit(options: VisitorOptions): Visit {\n const prefix = options.rpc ?? '/_brumate';\n /**\n * Answers the path with the routes of the app, puts the page in the\n * document, and starts the loader with client navigation. Links, forms,\n * server function calls and `#defer` requests of the page go to the same\n * routes, without a server, with the cookies that the answers set.\n */\n return async function visit(path, visitOptions = {}) {\n visited?.close();\n const jar = new Map(Object.entries(visitOptions.cookies ?? {}));\n const original = globalThis.fetch;\n const origin = location.origin;\n history.replaceState(null, '', new URL(path, origin));\n\n // A browser follows redirects, sends its cookies, and keeps the ones that the answers set.\n async function answer(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {\n let url = new URL(input instanceof Request ? input.url : String(input), location.href);\n if (url.origin !== origin) {\n return original(input, init);\n }\n let method = (\n init?.method ?? (input instanceof Request ? input.method : 'GET')\n ).toUpperCase();\n let body = init?.body ?? undefined;\n const extra = new Headers(input instanceof Request ? input.headers : undefined);\n for (const [name, value] of new Headers(init?.headers)) {\n extra.set(name, value);\n }\n for (let hops = 0; ; hops++) {\n const request = new Request(url, { method, body, signal: init?.signal ?? null });\n // Set after the request is made, since a DOM environment drops these from its init.\n for (const [name, value] of new Headers(visitOptions.headers)) {\n request.headers.set(name, value);\n }\n for (const [name, value] of extra) {\n request.headers.set(name, value);\n }\n if (jar.size > 0) {\n const cookies: string[] = [];\n for (const [name, value] of jar) {\n cookies.push(`${name}=${value}`);\n }\n request.headers.set('cookie', cookies.join('; '));\n }\n if (method !== 'GET' && method !== 'HEAD') {\n request.headers.set('origin', origin);\n }\n const handle = url.pathname.startsWith(`${prefix}/`) ? options.calls : options.routes;\n const answered = handle().then((handler) => handler(request));\n // oxlint-disable-next-line no-await-in-loop -- Each redirect is a request of its own.\n const response = (await answered) ?? new Response('Not found', { status: 404 });\n storeCookies(jar, response);\n const location = response.headers.get('location');\n if (!REDIRECTS.has(response.status) || !location || init?.redirect === 'manual') {\n Object.defineProperty(response, 'url', { value: url.href });\n return response;\n }\n if (hops === 20) {\n throw new TypeError(`Too many redirects from ${path}`);\n }\n url = new URL(location, url);\n // As in fetch: 303 asks for the page with GET, and so do 301 and 302 after a POST.\n // 307 and 308 send the request again as it was.\n if (\n (response.status === 303 && method !== 'HEAD') ||\n (method === 'POST' && (response.status === 301 || response.status === 302))\n ) {\n method = 'GET';\n body = undefined;\n extra.delete('content-type');\n }\n }\n }\n globalThis.fetch = answer as typeof fetch;\n\n // The DOM of a test does not run scripts, so the ones that the page adds run here, once each.\n const ran = new WeakSet<Element>();\n function runOnce(script: Element): void {\n if (!ran.has(script) && !script.hasAttribute('src') && !script.hasAttribute('type')) {\n ran.add(script);\n run(script);\n }\n }\n const scripts = new MutationObserver((records) => {\n for (const record of records) {\n for (const node of record.addedNodes) {\n if (node.nodeName === 'SCRIPT') {\n runOnce(node as Element);\n } else if (node instanceof Element) {\n for (const script of node.querySelectorAll('script')) {\n runOnce(script);\n }\n }\n }\n }\n });\n\n const response = await answer(path);\n // The page is at the URL of the last redirect.\n history.replaceState(null, '', response.url);\n const reader = response.body!.pipeThrough(new TextDecoderStream()).getReader();\n let html = '';\n let end = -1;\n let done = false;\n while (end < 0 && !done) {\n // oxlint-disable-next-line no-await-in-loop -- The page arrives in pieces.\n const chunk = await reader.read();\n done = chunk.done;\n html += chunk.value ?? '';\n end = html.search(/<\\/html>/i);\n }\n const cut = end < 0 ? html.length : end + '</html>'.length;\n const page = new DOMParser().parseFromString(html.slice(0, cut), 'text/html');\n for (const name of document.documentElement.getAttributeNames()) {\n document.documentElement.removeAttribute(name);\n }\n for (const attribute of page.documentElement.attributes) {\n document.documentElement.setAttribute(attribute.name, attribute.value);\n }\n const headNodes: Node[] = [];\n for (const node of page.head.childNodes) {\n headNodes.push(document.importNode(node, true));\n }\n document.head.replaceChildren(...headNodes);\n const bodyNodes: Node[] = [];\n for (const node of page.body.childNodes) {\n bodyNodes.push(document.importNode(node, true));\n }\n document.body.replaceChildren(...bodyNodes);\n for (const script of document.querySelectorAll('script')) {\n runOnce(script);\n }\n scripts.observe(document, { childList: true, subtree: true });\n\n const unwatch = watchView(visitOptions.offscreen);\n const stop = start({ load: options.load, rpc: prefix, navigate: true });\n let rest = html.slice(cut);\n let open = true;\n void (async () => {\n while (!done) {\n // oxlint-disable-next-line no-await-in-loop -- Later markup arrives in pieces.\n const chunk = await reader.read();\n done = chunk.done;\n rest += chunk.value ?? '';\n // A chunk can end inside a tag, a script or a template, so only whole nodes move in.\n const last = done ? rest.length : wholeNodes(rest);\n if (last > 0 && open) {\n // The observer runs its scripts.\n const template = document.createElement('template');\n template.innerHTML = rest.slice(0, last);\n document.body.append(template.content);\n rest = rest.slice(last);\n }\n }\n })();\n\n const current: Visited = {\n ...actions(document),\n ...checks(document, true),\n get url() {\n return location.pathname + location.search;\n },\n status: response.status,\n get cookies() {\n return Object.fromEntries(jar);\n },\n close: () => {\n if (!open) {\n return;\n }\n open = false;\n visited = undefined;\n stop();\n unwatch();\n scripts.disconnect();\n reader.cancel().catch(() => {});\n if (globalThis.fetch === answer) {\n globalThis.fetch = original;\n }\n // The core forgets the page, so the next visit starts its IDs again.\n void import('./client.ts').then((core) => core.leavePage());\n document.head.replaceChildren();\n document.body.replaceChildren();\n },\n };\n visited = current;\n return current;\n };\n}\n"],"mappings":";;;AAEA,MAAM,uBAAO,IAAI,IAAI;CACnB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;;;;;AAOD,SAAgB,WAAW,QAAwB;CACjD,MAAM,MAAM;CACZ,MAAM,QAAQ,OAAO,YA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AAO,KAAK,MAAM,IAAI;IACxB;GACF;EACF,EAAA,CAAG;EAEH,MAAM,UAAmB;GACvB,GAAG,QAAQ,QAAQ;GACnB,GAAG,OAAO,UAAU,IAAI;GACxB,IAAI,MAAM;IACR,OAAO,SAAS,WAAW,SAAS;GACtC;GACA,QAAQ,SAAS;GACjB,IAAI,UAAU;IACZ,OAAO,OAAO,YAAY,GAAG;GAC/B;GACA,aAAa;IACX,IAAI,CAAC,MACH;IAEF,OAAO;IACP,UAAU,KAAA;IACV,KAAK;IACL,QAAQ;IACR,QAAQ,WAAW;IACnB,OAAO,OAAO,CAAC,CAAC,YAAY,CAAC,CAAC;IAC9B,IAAI,WAAW,UAAU,QACvB,WAAW,QAAQ;IAGrB,OAAY,cAAc,CAAC,MAAM,SAAS,KAAK,UAAU,CAAC;IAC1D,SAAS,KAAK,gBAAgB;IAC9B,SAAS,KAAK,gBAAgB;GAChC;EACF;EACA,UAAU;EACV,OAAO;CACT;AACF"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { b as ownValue, t as Internal, x as raw } from "./html-t1JpkODI.js";
|
|
2
|
-
import { i as HAS_CHILDREN, n as HAS_BINDINGS } from "./features-
|
|
2
|
+
import { i as HAS_CHILDREN, n as HAS_BINDINGS } from "./features-CbgII-o7.js";
|
|
3
|
+
import { a as routeContext } from "./context-CTiSzQRc.js";
|
|
3
4
|
//#region src/runtime/shared.ts
|
|
4
5
|
/** The plugins of values of the app, by tag, which the entry `src/serial.ts` exports. */
|
|
5
6
|
const valuePlugins = /* @__PURE__ */ new Map();
|
|
@@ -399,6 +400,27 @@ function resolve(value, seen) {
|
|
|
399
400
|
return value;
|
|
400
401
|
}
|
|
401
402
|
//#endregion
|
|
402
|
-
|
|
403
|
+
//#region src/runtime/search-params.ts
|
|
404
|
+
/** The value of a parameter in a query string: its text parsed, or the default when it is absent. */
|
|
405
|
+
function readParam(search, name, options) {
|
|
406
|
+
const text = search.get(name);
|
|
407
|
+
if (text === null) return options?.default ?? null;
|
|
408
|
+
return options?.parse ? options.parse(text) : text;
|
|
409
|
+
}
|
|
410
|
+
/** The text of a value in the URL, or null for the default, which leaves the parameter out. */
|
|
411
|
+
function writeParam(value, options) {
|
|
412
|
+
const own = textOf(value, options);
|
|
413
|
+
return own === textOf(options?.default, options) ? null : own;
|
|
414
|
+
}
|
|
415
|
+
function textOf(value, options) {
|
|
416
|
+
if (value === null || value === void 0) return null;
|
|
417
|
+
return options?.serialize ? options.serialize(value) : String(value);
|
|
418
|
+
}
|
|
419
|
+
/** `$searchParam` on the server: the parameter of the request's URL. */
|
|
420
|
+
function searchParam(context, name, options) {
|
|
421
|
+
return readParam(context.consume(routeContext, 0).search, name, options);
|
|
422
|
+
}
|
|
423
|
+
//#endregion
|
|
424
|
+
export { parseId as C, useSerialEntry as E, onValuePlugin as S, unbind as T, isBinding as _, Binding as a, mergeHandlers as b, ElementReference as c, PARTS as d, PropPromise as f, isAsyncIterable as g, addEntryHandlers as h, produce as i, FunctionReference as l, SlotReference as m, searchParam as n, CHILDREN_REF as o, SCOPE_IDS as p, writeParam as r, ChildrenReference as s, readParam as t, MemoError as u, isPropWrapper as v, stateValues as w, onSerialOptions as x, isSlotReference as y };
|
|
403
425
|
|
|
404
|
-
//# sourceMappingURL=
|
|
426
|
+
//# sourceMappingURL=search-params-CM1RWR2P.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"search-params-CM1RWR2P.js","names":[],"sources":["../src/runtime/shared.ts","../src/runtime/produce.ts","../src/runtime/search-params.ts"],"sourcesContent":["// Values and types that the server and the browser share. It does not import\n// seroval, so the core, which reads the page state without it, stays small.\n// The plugins that write and read these values are in `serial.ts`.\n\nimport { HAS_BINDINGS, HAS_CHILDREN } from './features.ts';\nimport { Internal, ownValue, raw } from './html.ts';\nimport type { Raw } from './html.ts';\nimport type { SerialEntry, ValuePlugin } from './values.ts';\n\n/** The plugins of values of the app, by tag, which the entry `src/serial.ts` exports. */\nconst valuePlugins = new Map<string, ValuePlugin>();\nconst pluginListeners: ((plugin: ValuePlugin) => void)[] = [];\n/** The options of the entry, which the serializer reads when it loads. */\nlet entryOptions: Omit<SerialEntry, 'plugins'> = {};\nconst optionListeners: ((options: Omit<SerialEntry, 'plugins'>) => void)[] = [];\n\n/**\n * Takes the exports of the serial entry: its plugins and the options that it\n * changes. The server and the loader call it before the first value is\n * written or read.\n */\nexport function useSerialEntry(entry: SerialEntry): void {\n const { plugins = [], ...options } = entry;\n if (options.disabledFeatures !== undefined || options.depthLimit !== undefined) {\n entryOptions = options;\n for (const listener of optionListeners) {\n listener(options);\n }\n }\n registerValues(plugins);\n}\n\n/** Calls `listener` with the options of the entry, now and when they change. */\nexport function onSerialOptions(listener: (options: Omit<SerialEntry, 'plugins'>) => void): void {\n optionListeners.push(listener);\n listener(entryOptions);\n}\n\n/** Adds plugins of values of the app. */\nfunction registerValues(plugins: readonly ValuePlugin[]): void {\n for (const plugin of plugins) {\n if (valuePlugins.get(plugin.tag) === plugin) {\n continue;\n }\n valuePlugins.set(plugin.tag, plugin);\n for (const listener of pluginListeners) {\n listener(plugin);\n }\n }\n}\n\n/** Calls `listener` for each plugin of the app, those added so far and those added later. */\nexport function onValuePlugin(listener: (plugin: ValuePlugin) => void): void {\n pluginListeners.push(listener);\n for (const plugin of valuePlugins.values()) {\n listener(plugin);\n }\n}\n\n/**\n * The ID of a scope or of a `#loading` boundary. The rest of the page numbers\n * its scopes from the base of the render, such as `3`. A `#loading` body\n * numbers its own from 0 after the ID of its boundary and a dot, such as\n * `5.0` and `5.1`, so its IDs do not depend on when its data arrives.\n */\nexport type ScopeId = number | string;\n\n/** Reads a scope or boundary ID from markup. */\nexport function parseId(text: string): ScopeId {\n return /^-?\\d+$/.test(text) ? Number(text) : text;\n}\n\n/** Adds a number to an ID. An ID inside a boundary moves with its boundary. */\nexport function shiftId(id: ScopeId, by: number): ScopeId {\n if (typeof id === 'number') {\n return id + by;\n }\n const dot = id.indexOf('.');\n return `${Number(id.slice(0, dot)) + by}${id.slice(dot)}`;\n}\n\n/** An element that the server rendered. The client finds it by its anchor. */\nexport class ElementReference {\n readonly scope: ScopeId;\n readonly anchor: number;\n\n constructor(scope: ScopeId, anchor: number) {\n this.scope = scope;\n this.anchor = anchor;\n }\n}\n\n/** A client function: an export of a client module, and the scope it reads. */\n/** The key of the reference of children on the server, which the page state sends. */\nexport const CHILDREN_REF: unique symbol = Symbol.for('brumate.children') as never;\n\n/**\n * The children of a component in the page state: the export that renders them in the browser,\n * such as `Page_1a2b#n0`, and the scope that they were written in. Each insert renders them\n * again, with new scopes, as the body of a block does.\n */\nexport class ChildrenReference {\n readonly ref: string;\n readonly scope: ScopeId;\n /** The scope and the anchor of the insert where the server rendered them, if it did. */\n at: ScopeId | undefined;\n anchor: number | undefined;\n\n constructor(ref: string, scope: ScopeId, at?: ScopeId, anchor?: number) {\n this.ref = ref;\n this.scope = scope;\n this.at = at;\n this.anchor = anchor;\n }\n}\n\nexport class FunctionReference {\n /** `<component id>#<export name>`. */\n readonly ref: string;\n readonly scope: ScopeId;\n /** The arguments of a handler that `$handler` made, which come before the event. */\n readonly args: unknown[] | undefined;\n /** The modifiers of the wrappers of a handler, such as `prevent`, for the `b-on` of a spread. */\n readonly modifiers: string[] | undefined;\n\n constructor(ref: string, scope: ScopeId, args?: unknown[] | null, modifiers?: string[]) {\n this.ref = ref;\n this.scope = scope;\n this.args = args ?? undefined;\n this.modifiers = modifiers;\n }\n}\n\n/** The handlers that a merged handler calls, in order. A symbol of the registry. */\nexport const PARTS: unique symbol = Symbol.for('brumate.parts');\n\n// oxlint-disable-next-line typescript/no-explicit-any -- Handlers take any event.\ntype Handler = (...args: any[]) => unknown;\n\n/**\n * One handler that calls each of `handlers` in order, with the same arguments. A prop holds one\n * handler per event, and the browser takes one `b-on` entry for each part. Merged handlers in\n * `handlers` give their parts, so the list stays flat.\n */\nexport function mergeHandlers(handlers: Handler[]): Handler {\n const parts: Handler[] = [];\n for (const handler of handlers) {\n parts.push(...((handler as { [PARTS]?: Handler[] })[PARTS] ?? [handler]));\n }\n return Object.assign(\n (...args: unknown[]): void => {\n for (const part of parts) {\n part(...args);\n }\n },\n { [PARTS]: parts },\n );\n}\n\n/**\n * Adds a handler prop, such as `onClick`, for each entry of the scoped `b-on` of a dynamic tag\n * that names a component. `make` makes the handler of a reference. A handler of the same event in\n * `props`, such as a rest prop passed on, is merged with it and runs first.\n */\nexport function addEntryHandlers(\n props: Record<string, unknown>,\n entries: unknown,\n scope: ScopeId | undefined,\n make: (reference: FunctionReference) => Handler,\n): void {\n for (const entry of (ownValue('b-on', entries) as string | undefined)?.split(' ') ?? []) {\n const [event, target] = entry.split('=') as [string, string];\n const [name, ...modifiers] = event.split(':') as [string, ...string[]];\n const [ref, at] = target.split('@') as [string, string?];\n const handler = make(\n new FunctionReference(\n ref,\n /^\\d+$/.test(at ?? '') ? Number(at) : (at ?? scope!),\n undefined,\n modifiers.length > 0 ? modifiers : undefined,\n ),\n );\n const key = `on${name[0]!.toUpperCase()}${name.slice(1)}`;\n const before = props[key];\n props[key] =\n typeof before === 'function' ? mergeHandlers([before as Handler, handler]) : handler;\n }\n}\n\n// Brands of bindings and slot references, under keys of the registry, so two copies of the\n// runtime, such as a component's and the render context's, know each other's.\nconst BINDING = Symbol.for('brumate.binding');\nconst SLOT = Symbol.for('brumate.slot');\n\n/** A slot of a scope, which a write of a bound prop goes to. */\nexport class SlotReference {\n readonly scope: ScopeId;\n readonly slot: number;\n\n constructor(scope: ScopeId, slot: number) {\n this.scope = scope;\n this.slot = slot;\n }\n}\n\n(SlotReference.prototype as unknown as Record<symbol, boolean>)[SLOT] = true;\n\n/** True for a slot reference of any copy of the runtime. */\nexport function isSlotReference(value: unknown): value is SlotReference {\n return typeof value === 'object' && value !== null && SLOT in value;\n}\n\n/** True for a binding of any copy of the runtime. */\nexport function isBinding(value: unknown): value is Binding {\n return typeof value === 'object' && value !== null && BINDING in value;\n}\n\n/**\n * What `$bind(name)` passes a child: the value of the name, and its slot,\n * which the child's writes of the prop go to.\n */\nexport class Binding<T = unknown> {\n readonly value: T;\n readonly ref: SlotReference;\n /** The function of `$bind(name, fn)`, which a write calls in place of writing the slot. */\n readonly set: unknown;\n\n constructor(value: T, ref: SlotReference, set?: unknown) {\n this.value = value;\n this.ref = ref;\n this.set = set;\n }\n\n /** What a write of the bound prop goes to: the setter, or else the slot. */\n get target(): unknown {\n return this.set ?? this.ref;\n }\n}\n\n(Binding.prototype as unknown as Record<symbol, boolean>)[BINDING] = true;\n\n/**\n * The props that a component destructures, with the values of their\n * bindings. `names` are the props that it destructures by name: the others,\n * which a rest prop holds, keep their bindings, so a spread passes them on.\n * Without `names`, every binding gives its value. `omit` are props that a rest\n * leaves out, because another `$props()` call of the component names them.\n */\nexport function unbind(\n props: Record<string, unknown>,\n names?: readonly string[],\n omit?: readonly string[],\n sink?: PropSink,\n): Record<string, unknown> {\n let result: Record<string, unknown> | undefined;\n // The props that another `$props()` call of the component names, which a rest leaves out.\n if (omit) {\n result = { ...props };\n for (const key of omit) {\n delete result[key];\n }\n props = result;\n }\n for (const key of names ?? Object.keys(props)) {\n const value = props[key];\n if (sink && value instanceof Promise) {\n (sink.props ??= []).push(value);\n }\n if (isBinding(value)) {\n result ??= { ...props };\n result[key] = value.value;\n }\n }\n return result ?? props;\n}\n\n/**\n * What the slot of a memo holds while its compute throws or its promise rejects, and a memo that\n * failed on the server holds from the page state. Each read of the slot throws the error.\n */\nexport class MemoError {\n readonly error: unknown;\n\n constructor(error: unknown) {\n this.error = error;\n }\n}\n\n/**\n * A promise that a parent passed as a prop. It stays a promise in the child, so `await` and\n * `then` work on it. The page state holds it in this wrapper, so the browser knows the slot is\n * a prop and does not replace the promise with its value, as it does for a memo that streams.\n */\nexport class PropPromise {\n readonly promise: Promise<unknown>;\n\n constructor(promise: Promise<unknown>) {\n this.promise = promise;\n (this as Record<symbol, unknown>)[PROP_WRAPPER] = true;\n }\n}\n\n// Symbol.for, so copies of the runtime agree on the marks.\nconst PROP_WRAPPER = Symbol.for('brumate.propWrapper');\n\n/** A scope that collects the promise props that its component receives. */\nexport interface PropSink {\n props?: Promise<unknown>[] | undefined;\n}\n\n/** True for the wrapper that holds a promise prop in the page state. */\nexport function isPropWrapper(value: unknown): value is PropPromise {\n return typeof value === 'object' && value !== null && PROP_WRAPPER in value;\n}\n\n/** A component, which the compiler marks with its ID. */\nexport type ComponentValue = ((...args: never[]) => unknown) & { brumateId: string };\n\n/** The value of a feature that the build turned off, which no page state of it holds. */\nfunction unused(): never {\n throw new Error('The page state holds a value of a feature that no component of the build uses');\n}\n\n/**\n * Makes the values of brumate's plugins. A state record calls them as `$b`,\n * with one letter each, and the plugins read nodes of server function calls\n * with them too, so both give the same values.\n */\nexport const stateValues: {\n /** An element that the server rendered, by its scope and anchor. */\n e: (scope: ScopeId, anchor: number) => ElementReference;\n /** A client function, by its reference and scope. */\n f: (\n ref: string,\n scope: ScopeId,\n args?: unknown[] | null,\n modifiers?: string[],\n ) => FunctionReference;\n /** The parts of a merged handler, which `callable` makes one handler of. */\n m: (parts: FunctionReference[]) => FunctionReference[];\n /** A value of an attribute that brumate writes, such as the scope attribute of a style. */\n i: (value: unknown) => Internal;\n /** HTML that the client may insert again. */\n r: (html: string) => Raw;\n /** Children, by the export that renders them and their scope. */\n n: (ref: string, scope: ScopeId, at?: ScopeId, anchor?: number) => ChildrenReference;\n /**\n * A component, such as the value of a dynamic tag. The client gets a\n * function with the same ID that renders nothing. The client code that\n * changes the value uses the component's render module instead.\n */\n c: (id: string) => ComponentValue;\n /** A slot of a scope, which a bound prop writes. */\n l: (scope: ScopeId, slot: number) => SlotReference;\n /** A binding that a rest prop holds, with its value and its slot. */\n b: (value: unknown, scope: ScopeId, slot: number, set?: unknown) => Binding;\n /** A promise prop. See `PropPromise`. */\n q: (promise: Promise<unknown>) => PropPromise;\n /** The error of a memo that failed on the server. See `MemoError`. */\n x: (error: unknown) => MemoError;\n /** A value of the app, which a plugin of the entry makes from its data. */\n u: (tag: string, data: unknown) => unknown;\n} = {\n e: (scope, anchor) => new ElementReference(scope, anchor),\n f: (ref, scope, args, modifiers) => new FunctionReference(ref, scope, args, modifiers),\n m: (parts) => Object.assign(parts, { [PARTS]: parts }),\n i: (value) => new Internal(value),\n r: raw,\n n: HAS_CHILDREN\n ? (ref, scope, at, anchor) => new ChildrenReference(ref, scope, at, anchor)\n : unused,\n c: (id) => Object.assign(() => '', { brumateId: id }),\n l: (scope, slot) => new SlotReference(scope, slot),\n b: HAS_BINDINGS\n ? (value, scope, slot, set) => new Binding(value, new SlotReference(scope, slot), set)\n : unused,\n q: (promise) => new PropPromise(promise),\n x: (error) => new MemoError(error),\n u: (tag, data) => {\n const plugin = valuePlugins.get(tag);\n if (!plugin) {\n throw new Error(\n `No plugin reads the value \"${tag}\". Export it in the plugins of the serial entry, src/serial.ts`,\n );\n }\n return plugin.fromData(data);\n },\n};\n\n/** True for a value that `for await` reads, such as the result of an async generator. */\nexport function isAsyncIterable(value: unknown): value is AsyncIterable<unknown> {\n return (\n value !== null &&\n typeof value === 'object' &&\n typeof (value as AsyncIterable<unknown>)[Symbol.asyncIterator] === 'function'\n );\n}\n\n/** The state of one scope in the page. */\nexport interface ScopeState {\n /** The scope's ID in the compiled component. */\n k?: number;\n /** The ID of the scope that contains this one. Component root scopes have none. */\n p?: ScopeId;\n /** The component ID of a component's root scope. */\n m?: string;\n /** The item of a list item scope. */\n i?: unknown;\n /** The scope that rendered a component's root scope, for finding contexts. */\n o?: ScopeId;\n /**\n * For a scope of children that a component inserted, the scope where they\n * are, which contexts are found from in place of `p` and `o`.\n */\n t?: ScopeId;\n /** For a component that passes its children on, the scope where they are finally inserted. */\n f?: ScopeId;\n /** For the scope of a template, the scope where it was called, which errors go to. */\n l?: ScopeId;\n /** The values that the scope provides, by context key. */\n v?: Record<string, unknown>;\n /** The slots that hold the contexts that the scope reads, by context key. */\n x?: Record<string, number>;\n /** Slot values, in the order of the scope's layout. */\n s?: unknown[];\n /** The scope IDs of child components, by anchor index. */\n c?: Record<number, ScopeId>;\n /**\n * What the bound props of a component write, by the slot of the prop: a\n * slot of a parent, or the function of `$bind(name, fn)`.\n */\n b?: Record<number, unknown>;\n /**\n * The setters of `ref=$bind(x, fn)` that reached an element through rest props, by the anchor\n * of the element. The client calls each once on resume.\n */\n r?: Record<number, unknown>;\n}\n\n/** The state of a page, by scope ID. */\nexport type PageState = Record<ScopeId, ScopeState>;\n\n/**\n * The flags of a group of scope records in `PackedState`:\n * - `ITEM_SLOT`: the item of each scope is its first slot.\n * - `ITEM`: each scope has its item after its slots.\n * - `CHILDREN`: each scope has its child components after that.\n * - `OWNER`: the scopes are component root scopes. `base` is the distance from the scope that\n * rendered each one, `o`, to the scope, and the first gap is from 0. Otherwise `base` is the\n * parent, `p`, of every scope.\n * - `MODULE`: the group has the component ID of its scopes after its header.\n * - `SOURCE`: the scopes are the items of a list whose list is a slot of an enclosing scope.\n * The header then has that scope's ID and the slot's index, and the items are not written:\n * the item of the scope at position `n` in the group is the value at `n` of the list, or of\n * `Array.from` of a Set. With `ITEM_SLOT`, each scope writes its slots after the first.\n * - `PREFIX`: the scopes are inside a `#loading` body. The header ends with the prefix of\n * their IDs, such as `5.`, and the gaps count the numbers after it.\n */\nexport const ITEM_SLOT = 1;\nexport const ITEM = 2;\nexport const CHILDREN = 4;\nexport const OWNER = 8;\nexport const MODULE = 16;\nexport const SOURCE = 32;\nexport const PREFIX = 64;\n\n/**\n * The page state as the server writes it. Records of scopes that share their\n * kind, their parent or owner, and their shape are in one group of `g`,\n * such as the items of a list, instead of one object each. A group is a flat\n * array: `[kind, base, flags, slotCount, module?, source?, sourceSlot?, prefix?, ...scopes]`, and each scope\n * is its ID as the gap from the one before it (the first from `base`), its\n * slots, and then its item and its child components, as `flags` says.\n */\nexport type PackedState = PageState & { g?: unknown[][] };\n\n/**\n * How a field of a state record holds scope IDs:\n * - `none`: no ID.\n * - `id`: the value is an ID.\n * - `ids`: an object whose values are IDs.\n * - `value`: a value that may hold references, such as an item.\n * - `values`: an array of such values.\n * - `map`: an object whose values are such values.\n */\nexport type FieldKind = 'none' | 'id' | 'ids' | 'value' | 'values' | 'map';\n\n/**\n * A table of the fields of a state record and the reference classes that hold\n * a scope ID, which each keep it in `scope`. Code that moves the IDs reads it.\n * A new field of `ScopeState` fails to compile until it is in `fields`, and\n * `holders` are the classes that keep references in their own fields, such as\n * `Binding`, whose `ref` and `set` hold IDs. `scope-ids.test.ts` parses this\n * file and fails for any class in it, of any shape, that is not in\n * `references` or `holders` or in the test's list of classes without IDs.\n * It checks class names only, so a person decides which list a new class\n * belongs in.\n */\nexport const SCOPE_IDS: {\n fields: Record<keyof ScopeState, FieldKind>;\n references: readonly (abstract new (...args: never[]) => { scope: ScopeId })[];\n holders: readonly (abstract new (...args: never[]) => object)[];\n} = {\n fields: {\n k: 'none',\n p: 'id',\n m: 'none',\n i: 'value',\n o: 'id',\n t: 'id',\n f: 'id',\n l: 'id',\n v: 'map',\n x: 'none',\n s: 'values',\n c: 'ids',\n b: 'map',\n r: 'map',\n },\n references: [ElementReference, FunctionReference, ChildrenReference, SlotReference],\n holders: [Binding],\n};\n","const DRAFT = Symbol('brumate.draft');\n\ninterface DraftState {\n base: Record<PropertyKey, unknown>;\n /** A shallow copy, made on the first change. */\n copy: Record<PropertyKey, unknown> | undefined;\n parent: DraftState | undefined;\n /** Drafts of the objects inside, by key. */\n children: Map<PropertyKey, DraftState & { proxy: object }>;\n modified: boolean;\n}\n\n/** Plain objects and arrays can be drafted. Other values, such as `Map`, are used as they are. */\nfunction isDraftable(value: unknown): value is Record<PropertyKey, unknown> {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n if (Array.isArray(value)) {\n return true;\n }\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction latest(state: DraftState): Record<PropertyKey, unknown> {\n return state.copy ?? state.base;\n}\n\n/** Copies an object and its parents on the first change. */\nfunction prepare(state: DraftState): Record<PropertyKey, unknown> {\n for (\n let current: DraftState | undefined = state;\n current && !current.modified;\n current = current.parent\n ) {\n current.modified = true;\n current.copy = (\n Array.isArray(current.base) ? [...current.base] : { ...current.base }\n ) as Record<PropertyKey, unknown>;\n }\n return state.copy!;\n}\n\nfunction getDraftState(value: unknown): DraftState | undefined {\n return typeof value === 'object' && value !== null\n ? ((value as Record<PropertyKey, unknown>)[DRAFT] as DraftState | undefined)\n : undefined;\n}\n\nfunction createDraft(\n base: Record<PropertyKey, unknown>,\n parent: DraftState | undefined,\n): DraftState & { proxy: object } {\n const state = {\n base,\n copy: undefined,\n parent,\n children: new Map(),\n modified: false,\n } as DraftState & {\n proxy: object;\n };\n // An empty target, so the draft can report the keys of the copy.\n const target = Array.isArray(base) ? [] : Object.create(Object.getPrototypeOf(base));\n state.proxy = new Proxy(target, {\n get(_, key) {\n if (key === DRAFT) {\n return state;\n }\n const source = latest(state);\n const value = source[key];\n if (!Object.hasOwn(source, key) || !isDraftable(value) || value !== state.base[key]) {\n return value;\n }\n let child = state.children.get(key);\n if (!child) {\n child = createDraft(value, state);\n state.children.set(key, child);\n }\n return child.proxy;\n },\n set(_, key, value) {\n const source = latest(state);\n if (Object.is(source[key], value) && Object.hasOwn(source, key)) {\n return true;\n }\n prepare(state)[key] = value;\n state.children.delete(key);\n return true;\n },\n deleteProperty(_, key) {\n if (Object.hasOwn(latest(state), key)) {\n delete prepare(state)[key];\n state.children.delete(key);\n }\n return true;\n },\n has(_, key) {\n return key in latest(state);\n },\n ownKeys() {\n return Reflect.ownKeys(latest(state));\n },\n getOwnPropertyDescriptor(_, key) {\n const descriptor = Reflect.getOwnPropertyDescriptor(latest(state), key);\n if (descriptor && key !== 'length') {\n descriptor.configurable = true;\n descriptor.writable = true;\n }\n return descriptor;\n },\n defineProperty(_, key, descriptor) {\n prepare(state);\n return Reflect.defineProperty(state.copy!, key, descriptor);\n },\n });\n return state;\n}\n\n/** Returns the final value of a draft: the base if nothing changed, or a new object that shares what did not. */\nfunction finalize(state: DraftState): unknown {\n if (!state.modified) {\n // A child can change without its parent being copied yet.\n for (const child of state.children.values()) {\n if (child.modified) {\n prepare(state);\n break;\n }\n }\n if (!state.modified) {\n return state.base;\n }\n }\n const copy = state.copy!;\n for (const [key, child] of state.children) {\n if (copy[key] === child.base) {\n copy[key] = finalize(child);\n }\n }\n // Drafts can also be assigned to other keys, such as when an array is reordered.\n for (const key of Reflect.ownKeys(copy)) {\n const draft = getDraftState(copy[key]);\n if (draft) {\n copy[key] = finalize(draft);\n }\n }\n return copy;\n}\n\n/**\n * Returns a changed copy of a value. The recipe changes a draft as if it\n * were the value. Objects that it does not change keep their identity, and\n * if it changes nothing, the value itself is returned. A recipe can also\n * return a new value. Only plain objects and arrays are drafted.\n */\nexport function produce<T>(base: T, recipe: (draft: T) => T | void): T {\n if (!isDraftable(base)) {\n const result = recipe(base);\n return result === undefined ? base : result;\n }\n const state = createDraft(base, undefined);\n const result = recipe(state.proxy as T);\n if (result !== undefined && result !== state.proxy) {\n return resolve(result, new Set()) as T;\n }\n return finalize(state) as T;\n}\n\n/** Replaces the drafts in a value that a recipe returns, such as the result of `draft.filter(…)`. */\nfunction resolve(value: unknown, seen: Set<unknown>): unknown {\n const draft = getDraftState(value);\n if (draft) {\n return finalize(draft);\n }\n if (!isDraftable(value) || seen.has(value)) {\n return value;\n }\n seen.add(value);\n for (const key of Reflect.ownKeys(value)) {\n value[key] = resolve(value[key], seen);\n }\n return value;\n}\n","// `$searchParam`: the value of a parameter of the query string. The server and the browser read\n// it the same way, and the browser writes it back with `client/search.ts`.\nimport type { SearchParamOptions } from './signals.ts';\nimport { routeContext } from './context.ts';\nimport type { Context } from './context.ts';\n\n/** The value of a parameter in a query string: its text parsed, or the default when it is absent. */\nexport function readParam(\n search: URLSearchParams,\n name: string,\n options?: SearchParamOptions<unknown>,\n): unknown {\n const text = search.get(name);\n if (text === null) {\n return options?.default ?? null;\n }\n return options?.parse ? options.parse(text) : text;\n}\n\n/** The text of a value in the URL, or null for the default, which leaves the parameter out. */\nexport function writeParam(value: unknown, options?: SearchParamOptions<unknown>): string | null {\n const own = textOf(value, options);\n return own === textOf(options?.default, options) ? null : own;\n}\n\nfunction textOf(value: unknown, options?: SearchParamOptions<unknown>): string | null {\n if (value === null || value === undefined) {\n return null;\n }\n return options?.serialize ? options.serialize(value) : String(value);\n}\n\n/** `$searchParam` on the server: the parameter of the request's URL. */\nexport function searchParam(\n context: { consume<T>(context: Context<T>, scope: number): T },\n name: string,\n options?: SearchParamOptions<unknown>,\n): unknown {\n return readParam(context.consume(routeContext, 0).search, name, options);\n}\n"],"mappings":";;;;;AAUA,MAAM,+BAAe,IAAI,IAAyB;AAClD,MAAM,kBAAqD,CAAC;;AAE5D,IAAI,eAA6C,CAAC;AAClD,MAAM,kBAAuE,CAAC;;;;;;AAO9E,SAAgB,eAAe,OAA0B;CACvD,MAAM,EAAE,UAAU,CAAC,GAAG,GAAG,YAAY;CACrC,IAAI,QAAQ,qBAAqB,KAAA,KAAa,QAAQ,eAAe,KAAA,GAAW;EAC9E,eAAe;EACf,KAAK,MAAM,YAAY,iBACrB,SAAS,OAAO;CAEpB;CACA,eAAe,OAAO;AACxB;;AAGA,SAAgB,gBAAgB,UAAiE;CAC/F,gBAAgB,KAAK,QAAQ;CAC7B,SAAS,YAAY;AACvB;;AAGA,SAAS,eAAe,SAAuC;CAC7D,KAAK,MAAM,UAAU,SAAS;EAC5B,IAAI,aAAa,IAAI,OAAO,GAAG,MAAM,QACnC;EAEF,aAAa,IAAI,OAAO,KAAK,MAAM;EACnC,KAAK,MAAM,YAAY,iBACrB,SAAS,MAAM;CAEnB;AACF;;AAGA,SAAgB,cAAc,UAA+C;CAC3E,gBAAgB,KAAK,QAAQ;CAC7B,KAAK,MAAM,UAAU,aAAa,OAAO,GACvC,SAAS,MAAM;AAEnB;;AAWA,SAAgB,QAAQ,MAAuB;CAC7C,OAAO,UAAU,KAAK,IAAI,IAAI,OAAO,IAAI,IAAI;AAC/C;;AAYA,IAAa,mBAAb,MAA8B;CAC5B;CACA;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