@orieljs/live 0.1.0-alpha.4 → 0.1.0-alpha.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +45 -1
- package/dist/index.d.ts +66 -10
- package/dist/index.js +249 -50
- package/dist/index.js.map +1 -1
- package/package.json +5 -5
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../Component.ts","../metadata.ts","../embed.ts","../Testable.ts","../errors.ts","../html.ts","../LiveComponentManager.ts","../checksum.ts","../naming.ts","../persistent.ts","../security.ts","../synthesizers.ts","../LiveServiceProvider.ts","../commands.ts"],"sourcesContent":["import { LiveManager, UrlGenerator, ValidationFactory, type Class, type MessageBag, type Rules } from '@orieljs/contracts'\nimport { inject } from '@orieljs/container'\nimport { forgetComputed } from './metadata'\n\n/** Marks Live component classes (Symbol.for, so two copies of the package agree). */\nexport const COMPONENT: unique symbol = Symbol.for('oriel:live.component') as never\n\n/** A browser event queued by dispatch(). `to` is resolved to a component name when the effects are built. */\nexport interface QueuedDispatch {\n name: string\n params: Record<string, unknown>\n self?: true\n to?: string | Class<Component>\n}\n\n/** Per-request bookkeeping of one component instance. Kept outside the instance so it never becomes state. */\nexport interface ComponentState {\n id: string\n name: string\n errors: Record<string, string[]>\n dispatches: QueuedDispatch[]\n redirect?: string\n redirectUsingNavigate?: true\n skipRender: boolean\n}\n\nconst states = new WeakMap<object, ComponentState>()\n\n/** The bookkeeping of an instance, created on first use (an instance built by the router has none yet). */\nexport function stateOf(component: object): ComponentState {\n let state = states.get(component)\n if (state === undefined) states.set(component, (state = { id: '', name: '', errors: {}, dispatches: [], skipRender: false }))\n return state\n}\n\n/** Whether `value` is a class extending Component. */\nexport function isComponentClass(value: unknown): value is Class<Component> {\n return typeof value === 'function' && (value as unknown as Record<symbol, unknown>)[COMPONENT] === true\n}\n\n/** The validation errors of a component (Laravel's MessageBag), for render(): `this.errors.first('title')`. */\nexport class ErrorBag implements MessageBag {\n constructor(private readonly messages: Record<string, string[]>) {}\n\n has(key: string): boolean {\n return (this.messages[key]?.length ?? 0) > 0\n }\n\n first(key?: string): string | undefined {\n return key === undefined ? this.all()[0] : this.messages[key]?.[0]\n }\n\n get(key: string): string[] {\n return [...(this.messages[key] ?? [])]\n }\n\n all(): string[] {\n return Object.values(this.messages).flat()\n }\n\n any(): boolean {\n return !this.isEmpty()\n }\n\n isEmpty(): boolean {\n return this.count() === 0\n }\n\n count(): number {\n return this.all().length\n }\n\n toObject(): Record<string, string[]> {\n return Object.fromEntries(Object.entries(this.messages).map(([key, messages]) => [key, [...messages]]))\n }\n}\n\n/** What dispatch() returns: `this.dispatch('saved').self()` or `.to(Sidebar)`. */\nexport class PendingEvent {\n constructor(private readonly event: QueuedDispatch) {}\n\n /** Only this component's own listeners receive the event. */\n self(): this {\n this.event.self = true\n delete this.event.to\n return this\n }\n\n /** Only components of this class (or registered name) receive the event. */\n to(component: string | Class<Component>): this {\n this.event.to = component\n delete this.event.self\n return this\n }\n}\n\n/**\n * A Live component (Livewire 3): public fields are its state, public methods are actions the browser can call, and\n * render() returns its TSX. Lifecycle hooks, all optional: `boot()`, `mount(params)`, `hydrate()`, `dehydrate()`,\n * `updating(name, value)`/`updated(name, value)` and per property `updatingTitle(value)`/`updatedTitle(value)`,\n * `rendering()`/`rendered(html)`. Fields that must not be state use `#private` syntax.\n */\nexport abstract class Component {\n static readonly [COMPONENT] = true\n\n /** The view that wraps a full-page component (default: config `live.layout`). */\n static layout?: string\n /** The page title passed to the layout as `title`. */\n static title?: string\n /** Static fallbacks for runtimes without decorators: { event: 'method' }, locked names, computed getter names. */\n static listeners?: Record<string, string>\n static locked?: string[]\n static computed?: string[]\n\n abstract render(): unknown\n\n getId(): string {\n return stateOf(this).id\n }\n\n getName(): string {\n return stateOf(this).name\n }\n\n /** Dispatches a browser event; every component listening for it (@On) runs its handler. */\n dispatch(name: string, params: Record<string, unknown> = {}): PendingEvent {\n const event: QueuedDispatch = { name, params }\n stateOf(this).dispatches.push(event)\n return new PendingEvent(event)\n }\n\n /** Sends the browser to `url` after this request; `navigate` uses o:navigate instead of a full page load. */\n redirect(url: string, options: { navigate?: boolean } = {}): void {\n const state = stateOf(this)\n state.redirect = url\n if (options.navigate === true) state.redirectUsingNavigate = true\n else delete state.redirectUsingNavigate\n }\n\n redirectRoute(name: string, parameters?: unknown, options: { navigate?: boolean } = {}): void {\n this.redirect(inject(UrlGenerator).route(name, parameters), options)\n }\n\n /**\n * Validates the public state. On success clears the error bag and returns the validated data; on failure fills the\n * error bag and throws (the rest of the action is skipped and the component re-renders with `errors`).\n */\n async validate<T = Record<string, unknown>>(rules: Rules, messages?: Record<string, string>, attributes?: Record<string, string>): Promise<T> {\n const validator = inject(ValidationFactory).make(Object.fromEntries(Object.entries(this)), rules, messages, attributes)\n try {\n const data = await validator.validated<T>()\n stateOf(this).errors = {}\n return data\n } catch (error) {\n const errors = (error as { kind?: unknown; errors?: Record<string, string[]> }).errors\n if ((error as { kind?: unknown }).kind === 'Validation' && errors !== undefined) stateOf(this).errors = { ...errors }\n throw error\n }\n }\n\n addError(key: string, message: string): void {\n ;(stateOf(this).errors[key] ??= []).push(message)\n }\n\n /** Clears every error, or only those of `keys`. */\n resetErrorBag(...keys: string[]): void {\n const state = stateOf(this)\n if (keys.length === 0) state.errors = {}\n else for (const key of keys) delete state.errors[key]\n }\n\n get errors(): ErrorBag {\n return new ErrorBag(stateOf(this).errors)\n }\n\n /** Puts public properties (all of them when none are named) back to their initial values. */\n reset(...properties: string[]): void {\n const fresh = new (this.constructor as new () => Record<string, unknown>)()\n const names = properties.length > 0 ? properties : Object.keys(this)\n for (const name of names) if (Object.hasOwn(fresh, name)) (this as unknown as Record<string, unknown>)[name] = fresh[name]\n forgetComputed(this)\n }\n\n /** Keeps the current HTML: the response carries the new state but no `html` effect. */\n skipRender(): void {\n stateOf(this).skipRender = true\n }\n\n /** A full-page component as a route action: Route.get('/counter', Counter). Route parameters go to mount(). */\n async __invoke(): Promise<unknown> {\n return inject(LiveManager).page(this)\n }\n}\n","/**\n * TC39 decorators for Live components (@On, @Locked, @Computed) and the readers that merge them with the static\n * fallbacks (`static listeners`, `static locked`, `static computed`).\n *\n * Neither Node 24 nor Bun defines Symbol.metadata, and compilers only attach decorator metadata when it exists, so it\n * is installed (as the registered symbol, which TypeScript, esbuild and Bun agree on) before any component loads.\n */\n;(Symbol as { metadata?: symbol }).metadata ??= Symbol.for('Symbol.metadata')\n\nconst LISTENERS = Symbol.for('oriel:live.listeners')\nconst LOCKED = Symbol.for('oriel:live.locked')\nconst COMPUTED = Symbol.for('oriel:live.computed')\n\ntype Metadata = Record<PropertyKey, unknown>\n\n/**\n * The subclass's metadata object inherits from its parent's through the prototype chain, so a list read from it may\n * be the parent's: copy it onto the subclass before adding to it.\n */\nfunction own<T>(metadata: Metadata, key: symbol, empty: () => T, copy: (inherited: T) => T): T {\n if (!Object.hasOwn(metadata, key)) metadata[key] = metadata[key] === undefined ? empty() : copy(metadata[key] as T)\n return metadata[key] as T\n}\n\n/** @On('post-created'): calls the method when the event is dispatched (by this or any component, or the browser). */\nexport function On(event: string) {\n return function (_method: unknown, context: ClassMethodDecoratorContext): void {\n const listeners = own<Record<string, string[]>>(context.metadata as Metadata, LISTENERS, () => ({}), (inherited) =>\n Object.fromEntries(Object.entries(inherited).map(([name, methods]) => [name, [...methods]])),\n )\n // An override decorated like the method it replaces is still one listener.\n const methods = (listeners[event] ??= [])\n if (!methods.includes(String(context.name))) methods.push(String(context.name))\n }\n}\n\n/** @Locked: a property the browser can't change, or a method the browser can't call. */\nexport function Locked(_target: unknown, context: ClassFieldDecoratorContext | ClassMethodDecoratorContext): void {\n own<string[]>(context.metadata as Metadata, LOCKED, () => [], (inherited) => [...inherited]).push(String(context.name))\n}\n\n/** Per-instance caches of @Computed getters. A component instance lives for one request, so this is per request. */\nconst computedCache = new WeakMap<object, Map<string, unknown>>()\n\n/** Runs the getter once per instance (one request) and returns the cached value afterwards. */\nexport function cachedGetter<T>(name: string, getter: (this: object) => T): (this: object) => T {\n return function (this: object): T {\n let cache = computedCache.get(this)\n if (cache === undefined) computedCache.set(this, (cache = new Map()))\n if (!cache.has(name)) cache.set(name, getter.call(this))\n return cache.get(name) as T\n }\n}\n\n/** @Computed: a getter cached for the rest of the request, never part of the component's state. */\nexport function Computed<T>(getter: (this: object) => T, context: ClassGetterDecoratorContext): (this: object) => T {\n own<string[]>(context.metadata as Metadata, COMPUTED, () => [], (inherited) => [...inherited]).push(String(context.name))\n return cachedGetter(String(context.name), getter)\n}\n\n/** Drops the cached @Computed values of one instance (after `reset()`, for example). */\nexport function forgetComputed(instance: object): void {\n computedCache.delete(instance)\n}\n\ninterface Statics {\n listeners?: Record<string, string>\n locked?: string[]\n computed?: string[]\n [key: symbol]: unknown\n}\n\nfunction metadataOf(cls: Statics): Metadata {\n return (cls[(Symbol as unknown as { metadata: symbol }).metadata] as Metadata | undefined) ?? {}\n}\n\n/**\n * The classes from the root of the chain down to `cls`. Static properties shadow along the chain instead of merging, so\n * each level's own statics are read separately and added to its parent's.\n */\nfunction chainOf(cls: object): Statics[] {\n const chain: Statics[] = []\n for (let c: object | null = cls; c !== null && c !== Function.prototype; c = Object.getPrototypeOf(c) as object | null) {\n chain.unshift(c as Statics)\n }\n return chain\n}\n\n/** The values of the own static `key` of every class in the chain, parents first. */\nfunction staticsOf<K extends 'listeners' | 'locked' | 'computed'>(cls: object, key: K): NonNullable<Statics[K]>[] {\n return chainOf(cls).flatMap((c) => (Object.hasOwn(c, key) && c[key] !== undefined ? [c[key] as NonNullable<Statics[K]>] : []))\n}\n\n/** Event name → method names, from @On and `static listeners` (of the class and its parents). */\nexport function listenersOf(cls: object): Record<string, string[]> {\n const result: Record<string, string[]> = {}\n for (const [event, methods] of Object.entries((metadataOf(cls as Statics)[LISTENERS] as Record<string, string[]> | undefined) ?? {})) {\n result[event] = [...methods]\n }\n for (const listeners of staticsOf(cls, 'listeners')) {\n for (const [event, method] of Object.entries(listeners)) {\n const methods = (result[event] ??= [])\n if (!methods.includes(method)) methods.push(method)\n }\n }\n return result\n}\n\n/** Locked property and method names, from @Locked and `static locked` (of the class and its parents). */\nexport function lockedOf(cls: object): Set<string> {\n return new Set([...((metadataOf(cls as Statics)[LOCKED] as string[] | undefined) ?? []), ...staticsOf(cls, 'locked').flat()])\n}\n\n/** Computed getter names, from @Computed and `static computed` (of the class and its parents). */\nexport function computedOf(cls: object): Set<string> {\n return new Set([...((metadataOf(cls as Statics)[COMPUTED] as string[] | undefined) ?? []), ...staticsOf(cls, 'computed').flat()])\n}\n","import { LiveManager, type Class, type Htmlable } from '@orieljs/contracts'\nimport { inject } from '@orieljs/container'\nimport type { Component } from './Component'\nimport { Testable } from './Testable'\n\n/** Props of `<Live component={Counter} count={3} o:key=\"c1\" />`: the rest become mount params. */\nexport interface LiveProps {\n component: Class<Component> | string\n /** Identifies a child inside its parent across re-renders (Livewire's :key / wire:key). */\n 'o:key'?: string | number\n [param: string]: unknown\n}\n\n/** Blade's @livewire('counter', ['count' => 3], key('c1')): the component's first render, as trusted HTML. */\nexport async function live(component: Class<Component> | string, params: Record<string, unknown> = {}, key?: string | number): Promise<Htmlable> {\n const html = await inject(LiveManager).mount(component, params, key === undefined ? undefined : String(key))\n return { toHtml: () => html }\n}\n\n/** `<Live component={Counter} />` in any view or component. */\nfunction LiveComponent({ component, 'o:key': key, children: _children, ...params }: LiveProps): Promise<Htmlable> {\n return live(component, params, key)\n}\n\n/** The `<Live />` element, and the Live facade: Live.component(name, Class), Live.test(Component). */\nexport const Live = Object.assign(LiveComponent, {\n /** Registers a component under a name (components in app/Live are registered at boot). */\n component(name: string, component: Class<Component>): void {\n inject(LiveManager).register(component, name)\n },\n /** Livewire::test(): mounts `component` for assertions. */\n test<C extends Component>(component: Class<C> | string, params: Record<string, unknown> = {}): Promise<Testable<C>> {\n return Testable.create(component, params)\n },\n})\n","import { AssertionError } from 'node:assert'\nimport { isDeepStrictEqual } from 'node:util'\nimport { LiveManager, token, type Class, type LiveEffects } from '@orieljs/contracts'\nimport { Container, currentContainer, inject } from '@orieljs/container'\nimport { stateOf, type Component } from './Component'\nimport { escapeAttribute } from './html'\nimport type { ComponentResult, LiveComponentManager } from './LiveComponentManager'\n\nconst fail = (message: string, actual?: unknown, expected?: unknown): never => {\n throw new AssertionError({ message, actual, expected, operator: 'live' })\n}\n\nconst getPath = (target: unknown, path: string): unknown =>\n path.split('.').reduce<unknown>((node, segment) => (typeof node === 'object' && node !== null ? (node as Record<string, unknown>)[segment] : undefined), target)\n\n/**\n * Runs Live.test()'s mount and each update. The testing package binds one for every test, so they run in a request\n * scope like the test's HTTP requests (a request, the carried session, actingAs users) and what they change carries\n * on to the next request. Without one they run in the current scope.\n */\nexport type TestRequestScope = <T>(run: () => Promise<T>) => Promise<T>\nexport const TestRequestScope = token<TestRequestScope>('Testing.RequestScope')\n\nfunction requestScope(): TestRequestScope {\n const container = currentContainer() ?? Container.getInstance()\n return container?.bound(TestRequestScope) === true ? container.make(TestRequestScope) : (run) => run()\n}\n\n/**\n * Livewire's Livewire::test(): drives one component through the real mount → snapshot → checksum → update pipeline\n * (no HTTP), inside the test's request scope. Actions are async (`await counter.call('increment')`); assertions are\n * sync and return `this`.\n */\nexport class Testable<C extends Component = Component> {\n #snapshot: string\n #html: string\n #effects: LiveEffects\n #instance: C\n\n private constructor(\n private readonly manager: LiveComponentManager,\n private readonly scope: TestRequestScope,\n result: ComponentResult,\n ) {\n this.#snapshot = JSON.stringify(result.snapshot)\n this.#html = result.html ?? ''\n this.#effects = result.effects\n this.#instance = result.instance as C\n }\n\n /** Mounts `component` with `params`, as `<Live component={…} {...params} />` would. */\n static async create<C extends Component>(component: Class<C> | string, params: Record<string, unknown> = {}): Promise<Testable<C>> {\n const scope = requestScope()\n const manager = inject(LiveManager) as unknown as LiveComponentManager\n return new Testable<C>(manager, scope, await scope(() => manager.mountComponent(component, params)))\n }\n\n /** The component instance after the last request. */\n instance(): C {\n return this.#instance\n }\n\n /** A public property (dotted paths reach into arrays and objects). */\n get<T = unknown>(path: string): T {\n return getPath(this.#instance, path) as T\n }\n\n /** The last rendered HTML, without the o:id, o:snapshot and o:effects attributes (Livewire strips them too). */\n html(): string {\n return this.#html.replace(/ o:(id|snapshot|effects)=\"[^\"]*\"/g, '')\n }\n\n /** The effects of the last request. */\n effects(): LiveEffects {\n return this.#effects\n }\n\n async set(path: string | Record<string, unknown>, value?: unknown): Promise<this> {\n return this.#update(typeof path === 'string' ? { [path]: value } : path, [])\n }\n\n async call(method: string, ...params: unknown[]): Promise<this> {\n return this.#update({}, [{ method, params }])\n }\n\n async toggle(path: string): Promise<this> {\n return this.#update({}, [{ method: '$toggle', params: [path] }])\n }\n\n /** Dispatches an event to this component, as the browser does for its listeners. */\n async dispatch(event: string, params: Record<string, unknown> = {}): Promise<this> {\n return this.#update({}, [{ method: '__dispatch', params: [event, params] }])\n }\n\n async refresh(): Promise<this> {\n return this.#update({}, [{ method: '$refresh', params: [] }])\n }\n\n async #update(updates: Record<string, unknown>, calls: Array<{ method: string; params: unknown[] }>): Promise<this> {\n const result = await this.scope(() => this.manager.updateComponent(this.#snapshot, updates, calls))\n this.#snapshot = JSON.stringify(result.snapshot)\n if (result.html !== undefined) this.#html = result.html\n this.#effects = result.effects\n this.#instance = result.instance as C\n return this\n }\n\n assertSet(path: string, value: unknown): this {\n const actual = this.get(path)\n if (!isDeepStrictEqual(actual, value)) fail(`Failed asserting that property [${path}] is set to the expected value.`, actual, value)\n return this\n }\n\n assertNotSet(path: string, value: unknown): this {\n if (isDeepStrictEqual(this.get(path), value)) fail(`Failed asserting that property [${path}] is not set to the given value.`, this.get(path), value)\n return this\n }\n\n /** Each value, HTML-escaped, appears in the rendered HTML. */\n assertSee(...values: string[]): this {\n for (const value of values) if (!this.html().includes(escapeAttribute(value))) fail(`Failed asserting that [${value}] is in the rendered HTML.`, this.html(), value)\n return this\n }\n\n assertDontSee(...values: string[]): this {\n for (const value of values) if (this.html().includes(escapeAttribute(value))) fail(`Failed asserting that [${value}] is not in the rendered HTML.`, this.html(), value)\n return this\n }\n\n /** Each value appears in the rendered HTML as written (not escaped). */\n assertSeeHtml(...values: string[]): this {\n for (const value of values) if (!this.html().includes(value)) fail(`Failed asserting that [${value}] is in the rendered HTML.`, this.html(), value)\n return this\n }\n\n assertDispatched(name: string, params?: Record<string, unknown>): this {\n const dispatched = (this.#effects.dispatches ?? []).filter((event) => event.name === name)\n if (dispatched.length === 0) fail(`Failed asserting that an event [${name}] was dispatched.`, this.#effects.dispatches ?? [], name)\n if (params !== undefined && !dispatched.some((event) => isDeepStrictEqual(event.params, params))) {\n fail(`Failed asserting that event [${name}] was dispatched with the expected params.`, dispatched.map((event) => event.params), params)\n }\n return this\n }\n\n assertNotDispatched(name: string): this {\n if ((this.#effects.dispatches ?? []).some((event) => event.name === name)) fail(`Failed asserting that an event [${name}] was not dispatched.`)\n return this\n }\n\n /** The error bag has errors for every key given (or any error at all with no keys). */\n assertHasErrors(keys: string | string[] = []): this {\n const errors = stateOf(this.#instance).errors\n const wanted = [keys].flat()\n if (wanted.length === 0 && Object.keys(errors).length === 0) fail('Component has no errors.', errors)\n for (const key of wanted) if ((errors[key]?.length ?? 0) === 0) fail(`Component missing error: ${key}`, errors, key)\n return this\n }\n\n /** No errors for the keys given (or none at all with no keys). */\n assertHasNoErrors(keys: string | string[] = []): this {\n const errors = stateOf(this.#instance).errors\n const wanted = [keys].flat()\n const found = wanted.length === 0 ? Object.keys(errors).filter((key) => (errors[key]?.length ?? 0) > 0) : wanted.filter((key) => (errors[key]?.length ?? 0) > 0)\n if (found.length > 0) fail(`Component has errors: \"${found.join('\", \"')}\"`, errors)\n return this\n }\n\n assertRedirect(url?: string): this {\n const redirect = this.#effects.redirect\n if (redirect === undefined) fail('Component did not perform a redirect.')\n if (url !== undefined && redirect !== url) fail('Component redirected to an unexpected URL.', redirect, url)\n return this\n }\n\n assertNoRedirect(): this {\n if (this.#effects.redirect !== undefined) fail('Component performed a redirect.', this.#effects.redirect)\n return this\n }\n\n /** The last call returned `value`. */\n assertReturned(value: unknown): this {\n const returned = this.#effects.returns?.at(-1)\n if (!isDeepStrictEqual(returned, value)) fail('Failed asserting that the method returned the expected value.', returned, value)\n return this\n }\n}\n","import type { ErrorKind, OrielError } from '@orieljs/contracts'\n\n/** A Live programming error (unsupported state, a missing root element, an unknown component): a 500. */\nexport class LiveError extends Error implements OrielError {\n override readonly name: string = 'LiveError'\n readonly kind: ErrorKind = 'Server'\n readonly status: number = 500\n}\n\n/** A snapshot whose checksum doesn't match (tampered with, or signed with another APP_KEY). Nothing is hydrated. */\nexport class CorruptComponentPayloadError extends LiveError {\n override readonly name: string = 'CorruptComponentPayloadError'\n override readonly kind: ErrorKind = 'Authorization'\n override readonly status: number = 403\n\n constructor(component = 'unknown') {\n super(`Live encountered corrupt data when trying to hydrate the [${component}] component.`)\n }\n}\n\n/** The browser asked for a method that isn't a public action of the component. */\nexport class MethodNotCallableError extends LiveError {\n override readonly name: string = 'MethodNotCallableError'\n override readonly kind: ErrorKind = 'Authorization'\n override readonly status: number = 403\n\n constructor(method: string, component: string) {\n super(`Unable to call component method. Public method [${method}] not found on component [${component}].`)\n }\n}\n\n/** The browser tried to set a property that is locked, computed, private (`_x`) or not declared. */\nexport class PropertyNotUpdatableError extends LiveError {\n override readonly name: string = 'PropertyNotUpdatableError'\n override readonly kind: ErrorKind = 'Authorization'\n override readonly status: number = 403\n\n constructor(path: string, component: string) {\n super(`Cannot update property [${path}] on component [${component}]: it is not a public, unlocked property.`)\n }\n}\n\n/** A snapshot names a component that isn't registered. */\nexport class LiveComponentNotFoundError extends LiveError {\n override readonly name: string = 'LiveComponentNotFoundError'\n override readonly kind: ErrorKind = 'Http'\n override readonly status: number = 404\n\n constructor(component: string) {\n super(`Unable to find component: [${component}].`)\n }\n}\n\n/** An update request without the X-Oriel-Live header or with a malformed body. */\nexport class InvalidLiveRequestError extends LiveError {\n override readonly name: string = 'InvalidLiveRequestError'\n override readonly kind: ErrorKind = 'Http'\n override readonly status: number = 400\n}\n","import { LiveError } from './errors'\n\nconst ESCAPES: Record<string, string> = { '&': '&', '<': '<', '>': '>', '\"': '"', \"'\": ''' }\n\n/** Laravel's e(): for attribute values (the snapshot JSON goes into an attribute). */\nexport function escapeAttribute(value: string): string {\n return value.replace(/[&<>\"']/g, (char) => ESCAPES[char]!)\n}\n\nconst VOID = new Set(['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'source', 'track', 'wbr'])\nconst RAW_TEXT = new Set(['script', 'style', 'textarea', 'title'])\n/** A closing tag, or an opening tag with its (quoted) attributes. */\nconst TOKEN = /<\\/([A-Za-z][\\w:-]*)\\s*>|<([A-Za-z][\\w:-]*)(?:\\s+[^\\s\"'<>/=]+(?:\\s*=\\s*(?:\"[^\"]*\"|'[^']*'|[^\\s\"'=<>`]+))?)*\\s*(\\/?)>/g\n\n/** The name of the single root element of `html`; throws when there is none or there are several (Livewire's rule). */\nexport function rootTag(html: string, component: string): string {\n const fail = (): never => {\n throw new LiveError(`Live only supports one HTML element per component. Multiple root elements were detected for component [${component}].`)\n }\n const source = html.replace(/<!--[\\s\\S]*?-->/g, '').trim()\n let depth = 0\n let root: string | undefined\n let rootEnd = -1\n TOKEN.lastIndex = 0\n for (let match = TOKEN.exec(source); match !== null; match = TOKEN.exec(source)) {\n const [token, closing, opening, selfClosing] = match\n if (root === undefined && match.index !== 0) fail()\n if (depth === 0 && root !== undefined) fail()\n if (opening !== undefined) {\n const tag = opening.toLowerCase()\n root ??= tag\n if (selfClosing === '/' || VOID.has(tag)) {\n if (depth === 0) rootEnd = match.index + token.length\n continue\n }\n if (RAW_TEXT.has(tag)) {\n // Search the original string: lowercasing it can change its length (U+0130), which would shift the index.\n const closer = new RegExp(`</${tag}`, 'gi')\n closer.lastIndex = TOKEN.lastIndex\n const end = closer.exec(source)\n if (end !== null) TOKEN.lastIndex = end.index\n }\n depth++\n } else if (closing !== undefined) {\n if (--depth < 0) fail()\n if (depth === 0) rootEnd = match.index + token.length\n }\n }\n if (root === undefined || depth !== 0 || source.slice(rootEnd).trim() !== '') fail()\n return root!\n}\n\n/** Adds ` name=\"value\"` pairs (values escaped) right after the root tag's name. */\nexport function insertAttributesIntoRoot(html: string, attributes: Record<string, string>): string {\n const source = html.trim()\n const match = /^((?:<!--[\\s\\S]*?-->\\s*)*<[A-Za-z][\\w:-]*)/.exec(source)\n if (match === null) throw new LiveError('Live could not find the root element of the component.')\n const rendered = Object.entries(attributes)\n .map(([name, value]) => ` ${name}=\"${escapeAttribute(value)}\"`)\n .join('')\n return match[1] + rendered + source.slice(match[1]!.length)\n}\n","import { AsyncLocalStorage } from 'node:async_hooks'\nimport { randomBytes } from 'node:crypto'\nimport {\n ClassRegistry,\n ConfigRepository,\n CurrentRoute,\n Encrypter,\n HttpRequest,\n Redirector,\n Router,\n ViewFactory,\n type Application,\n type Class,\n type Container,\n type LiveEffects,\n type LiveManager,\n type LiveSnapshot,\n type LiveUpdateRequest,\n type LiveUpdateResponse,\n type Token,\n} from '@orieljs/contracts'\nimport { currentContainer } from '@orieljs/container'\nimport { Str } from '@orieljs/support'\nimport { checksum, verifyChecksum } from './checksum'\nimport { isComponentClass, stateOf, type Component } from './Component'\nimport { LiveComponentNotFoundError, CorruptComponentPayloadError, InvalidLiveRequestError, LiveError, MethodNotCallableError, PropertyNotUpdatableError } from './errors'\nimport { escapeAttribute, insertAttributesIntoRoot, rootTag } from './html'\nimport { cachedGetter, computedOf, listenersOf } from './metadata'\nimport { defaultName } from './naming'\nimport { PERSISTENT_MIDDLEWARE, persistentMiddleware, throughMiddleware } from './persistent'\nimport { isArraySlot, isCallable, isUpdatable } from './security'\nimport { dehydrate, hydrate } from './synthesizers'\n\ntype Memo = LiveSnapshot['memo']\ntype Children = Memo['children']\ntype Call = { method: string; params: unknown[] }\n\n/** The children rendered so far by the component being rendered, and those it had before (for placeholders). */\ninterface RenderContext {\n previous: Children\n children: Children\n index: number\n}\n\n/** One component after a mount or an update: the live instance (for Live.test), its snapshot, effects and HTML. */\nexport interface ComponentResult {\n instance: Component\n snapshot: LiveSnapshot\n effects: LiveEffects\n /** The rendered HTML with o:id (and, after a mount, o:snapshot/o:effects); undefined after skipRender(). */\n html?: string\n tag?: string\n}\n\nconst renderContext = new AsyncLocalStorage<RenderContext>()\n\n/** The page an update belongs to (its memo path and method): components mounted during the update keep it. */\nconst pageRequest = new AsyncLocalStorage<{ path: string; method: string }>()\n\n/** A binding of the current container, or undefined (scoped bindings throw on the application outside a request). */\nfunction optional<T>(container: Container, token: Token<T>): T | undefined {\n if (!container.bound(token)) return undefined\n try {\n return container.make(token)\n } catch {\n return undefined\n }\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null && !Array.isArray(value)\n\n/** Sets an own enumerable property, even for a key like '__proto__' (an assignment would change the prototype). */\nfunction setOwn<T>(object: Record<string, T>, key: string, value: T): void {\n Object.defineProperty(object, key, { value, enumerable: true, writable: true, configurable: true })\n}\n\nasync function hook(instance: Component, name: string, ...args: unknown[]): Promise<void> {\n const method = (instance as unknown as Record<string, unknown>)[name]\n if (typeof method === 'function') await (method as (...values: unknown[]) => unknown).apply(instance, args)\n}\n\n/** Livewire's update request handling and first render, on Oriel's contracts. */\nexport class LiveComponentManager implements LiveManager {\n constructor(private readonly app: Application) {}\n\n /** The request scope when there is one (sessions, the current route), else the application. */\n private container(): Container {\n return currentContainer() ?? this.app\n }\n\n private registry(): ClassRegistry {\n return this.container().make(ClassRegistry)\n }\n\n /** Live.component('counter', Counter): registers a component under a name the snapshots use. */\n register(component: Class<unknown>, name?: string): void {\n if (!isComponentClass(component)) throw new LiveError(`[${component.name}] is not a Live component: it must extend Component.`)\n const resolved = name ?? defaultName(component)\n if (resolved === undefined) throw new LiveError('Anonymous component classes need a name: Live.component(name, Class).')\n this.registry().register(component, resolved)\n }\n\n /** The registered name of a component class, registering it under its kebab-case class name the first time. */\n nameOf(component: Class<Component>): string {\n const registry = this.registry()\n const existing = registry.nameOf(component)\n if (existing !== undefined) return existing\n this.register(component)\n return registry.nameOf(component)!\n }\n\n resolve(name: string): Class<Component> {\n const registry = this.registry()\n if (!registry.has(name)) throw new LiveComponentNotFoundError(name)\n const cls = registry.resolve(name)\n if (!isComponentClass(cls)) throw new LiveComponentNotFoundError(name)\n return cls\n }\n\n isLiveRequest(request: HttpRequest): boolean {\n return request.header('X-Oriel-Live') === 'true'\n }\n\n /** The first render: HTML with o:id, o:snapshot and o:effects on the root element. */\n async mount(component: string | Class<unknown>, params: Record<string, unknown> = {}, key?: string): Promise<string> {\n const context = renderContext.getStore()\n if (context === undefined) return (await this.mountComponent(component, params)).html!\n const childKey = key ?? `lw-${context.index++}`\n // Own keys only: a key taken from data ('constructor', '__proto__') must not find or change Object.prototype.\n const existing = Object.hasOwn(context.previous, childKey) ? context.previous[childKey] : undefined\n if (existing !== undefined) {\n // The child already lives in the browser: a placeholder the client keeps as it is (Livewire's behaviour).\n setOwn(context.children, childKey, existing)\n return `<${existing[0]} o:id=\"${escapeAttribute(existing[1])}\"></${existing[0]}>`\n }\n const result = await this.mountComponent(component, params)\n setOwn(context.children, childKey, [result.tag!, result.snapshot.memo.id])\n return result.html!\n }\n\n async mountComponent(component: string | Class<unknown>, params: Record<string, unknown> = {}, existing?: Component): Promise<ComponentResult> {\n const cls = typeof component === 'string' ? this.resolve(component) : (component as Class<Component>)\n if (!isComponentClass(cls)) throw new LiveError(`[${(cls as { name?: string }).name}] is not a Live component: it must extend Component.`)\n const name = this.nameOf(cls)\n const instance = existing ?? this.container().make(cls)\n const state = stateOf(instance)\n state.id = randomBytes(15).toString('base64url')\n state.name = name\n await hook(instance, 'boot')\n for (const [property, value] of Object.entries(params)) {\n if (Object.hasOwn(instance, property)) (instance as unknown as Record<string, unknown>)[property] = value\n }\n this.prepareComputed(instance)\n await hook(instance, 'mount', params)\n const request = optional(this.container(), HttpRequest)\n const page = pageRequest.getStore() ?? { path: request?.path() ?? '', method: request?.method() ?? 'GET' }\n const memo: Memo = { id: state.id, name, path: page.path, method: page.method, children: {}, errors: {} }\n const { html, tag } = await this.render(instance, memo, {})\n const effects = this.effects(instance)\n const listeners = Object.keys(listenersOf(cls))\n if (listeners.length > 0) effects.listeners = listeners\n const snapshot = await this.snapshot(instance, memo)\n const attributes: Record<string, string> = { 'o:snapshot': JSON.stringify(snapshot), 'o:effects': JSON.stringify(effects), 'o:id': state.id }\n return { instance, snapshot, effects, html: insertAttributesIntoRoot(html, attributes), tag }\n }\n\n /** Applies each component's updates and calls, re-renders it and returns its new snapshot and effects. */\n async update(request: LiveUpdateRequest): Promise<LiveUpdateResponse> {\n const components: LiveUpdateResponse['components'] = []\n for (const component of request.components) {\n const { memo } = this.verify(component.snapshot)\n const result = await pageRequest.run({ path: memo.path, method: memo.method }, () => this.updateComponent(component.snapshot, component.updates, component.calls))\n components.push({ snapshot: JSON.stringify(result.snapshot), effects: result.effects })\n }\n return { components }\n }\n\n async updateComponent(snapshotJson: string, updates: Record<string, unknown>, calls: Call[]): Promise<ComponentResult> {\n const snapshot = this.verify(snapshotJson)\n const cls = this.resolve(snapshot.memo.name)\n const instance = this.container().make(cls)\n const state = stateOf(instance)\n state.id = snapshot.memo.id\n state.name = snapshot.memo.name\n state.errors = { ...snapshot.memo.errors }\n await hook(instance, 'boot')\n const registry = this.registry()\n for (const [property, value] of Object.entries(snapshot.data)) {\n Object.defineProperty(instance, property, { value: await hydrate(value, registry), enumerable: true, writable: true, configurable: true })\n }\n this.prepareComputed(instance)\n await hook(instance, 'hydrate')\n\n const returns: unknown[] = []\n try {\n for (const [path, value] of Object.entries(updates)) await this.applyUpdate(instance, path, value)\n for (const call of calls) returns.push(await this.call(instance, call.method, call.params))\n } catch (error) {\n // A failed validate() (or any validation error) stops the remaining calls; the component re-renders with errors.\n const errors = (error as { kind?: unknown; errors?: unknown }).errors\n if ((error as { kind?: unknown }).kind !== 'Validation' || !isRecord(errors)) throw error\n state.errors = { ...(errors as Record<string, string[]>) }\n }\n\n const memo: Memo = { ...snapshot.memo, children: { ...snapshot.memo.children } }\n const effects = this.effects(instance)\n let html: string | undefined\n let tag: string | undefined\n if (!state.skipRender) {\n ;({ html, tag } = await this.render(instance, memo, snapshot.memo.children))\n html = insertAttributesIntoRoot(html, { 'o:id': state.id })\n effects.html = html\n }\n if (calls.length > 0) effects.returns = returns\n return { instance, snapshot: await this.snapshot(instance, memo), effects, html, tag }\n }\n\n /**\n * The route action of POST /oriel/live/update. Each component's update runs behind the auth middleware of the route\n * that rendered its page (Livewire's persistent middleware): a signed-out tab gets a 401, never the action. When a\n * middleware answers instead (a redirect), that is the response.\n */\n async handle(request: HttpRequest): Promise<LiveUpdateResponse | Response> {\n if (!this.isLiveRequest(request)) throw new InvalidLiveRequestError('Live update requests need the X-Oriel-Live header.')\n const container = this.container()\n const persistent = optional(container, ConfigRepository)?.get<string[]>('live.persistent_middleware', PERSISTENT_MIDDLEWARE) ?? PERSISTENT_MIDDLEWARE\n const components: LiveUpdateResponse['components'] = []\n for (const component of this.payload(request).components) {\n // The memo is trusted only after its checksum holds.\n const { memo } = this.verify(component.snapshot)\n const middleware = persistentMiddleware(container.make(Router), persistent, memo.method, memo.path)\n const result = await pageRequest.run({ path: memo.path, method: memo.method }, () =>\n throughMiddleware(container, request, middleware, () => this.updateComponent(component.snapshot, component.updates, component.calls)),\n )\n if (result instanceof Response) return result\n components.push({ snapshot: JSON.stringify(result.snapshot), effects: result.effects })\n }\n return { components }\n }\n\n /** A full-page component (Route.get('/counter', Counter)): mounted with the route parameters, inside the layout. */\n async page(component: Component): Promise<unknown> {\n const container = this.container()\n const params = { ...(optional(container, CurrentRoute)?.parameters ?? {}) }\n const cls = component.constructor as Class<Component> & { layout?: string; title?: string }\n const result = await this.mountComponent(cls, params, component)\n const redirect = result.effects.redirect\n if (redirect !== undefined) {\n return optional(container, Redirector)?.to(redirect) ?? new Response(null, { status: 302, headers: { Location: redirect } })\n }\n const layout = cls.layout ?? optional(container, ConfigRepository)?.get<string>('live.layout') ?? 'components.layouts.app'\n const html = result.html!\n const data: Record<string, unknown> = { children: { toHtml: () => html } }\n if (cls.title !== undefined) data.title = cls.title\n return container.make(ViewFactory).make(layout, data)\n }\n\n /** Parses and checks a snapshot: a bad checksum throws before anything is hydrated. */\n private verify(snapshotJson: unknown): LiveSnapshot {\n let snapshot: unknown\n try {\n snapshot = typeof snapshotJson === 'string' ? JSON.parse(snapshotJson) : undefined\n } catch {\n throw new CorruptComponentPayloadError()\n }\n if (!isRecord(snapshot) || !isRecord(snapshot.data) || !isRecord(snapshot.memo)) throw new CorruptComponentPayloadError()\n const memo = snapshot.memo as Partial<Memo>\n const name = typeof memo.name === 'string' ? memo.name : 'unknown'\n const key = this.key()\n let valid: boolean\n try {\n valid = verifyChecksum(key, { data: snapshot.data, memo: snapshot.memo }, snapshot.checksum)\n } catch {\n // A payload the checksum can't be computed over (nested too deep to walk) was never signed by this server.\n valid = false\n }\n if (!valid) throw new CorruptComponentPayloadError(name)\n return snapshot as unknown as LiveSnapshot\n }\n\n private key(): Uint8Array {\n return this.container().make(Encrypter).getKey()\n }\n\n /** The request body, read from the raw JSON when the request has it, so TrimStrings can't alter typed values. */\n private payload(request: HttpRequest): LiveUpdateRequest {\n let body: unknown\n try {\n const content = (request as { content?: () => string }).content\n body = typeof content === 'function' ? JSON.parse(content.call(request)) : request.all()\n } catch {\n throw new InvalidLiveRequestError('The Live update request body is not valid JSON.')\n }\n const components = isRecord(body) ? body.components : undefined\n const valid =\n Array.isArray(components) &&\n components.every(\n (component) =>\n isRecord(component) &&\n typeof component.snapshot === 'string' &&\n isRecord(component.updates) &&\n Array.isArray(component.calls) &&\n component.calls.every((call) => isRecord(call) && typeof call.method === 'string' && Array.isArray(call.params)),\n )\n if (!valid) throw new InvalidLiveRequestError('The Live update request body is malformed.')\n return body as unknown as LiveUpdateRequest\n }\n\n /** Makes every computed getter (static `computed` too) cache its value for the rest of the request. */\n private prepareComputed(instance: Component): void {\n for (const name of computedOf(instance.constructor)) {\n for (let proto = Object.getPrototypeOf(instance) as object | null; proto !== null; proto = Object.getPrototypeOf(proto) as object | null) {\n const getter = Object.getOwnPropertyDescriptor(proto, name)?.get\n if (getter === undefined) continue\n Object.defineProperty(instance, name, { get: cachedGetter(name, getter as (this: object) => unknown), enumerable: false, configurable: true })\n break\n }\n }\n }\n\n private async applyUpdate(instance: Component, path: string, value: unknown): Promise<void> {\n if (!isUpdatable(instance, path)) throw new PropertyNotUpdatableError(path, stateOf(instance).name)\n const [root, ...rest] = path.split('.') as [string, ...string[]]\n const key = rest.length > 0 ? rest.join('.') : undefined\n const studly = Str.studly(root)\n await hook(instance, 'updating', path, value)\n await hook(instance, `updating${studly}`, value, key)\n const target = instance as unknown as Record<string, unknown>\n if (rest.length === 0) target[root] = value\n else {\n // Arrays are checked again while writing: an updating hook may have changed one since isUpdatable(), and no write\n // (nor a container created on the way) may leave holes.\n const assertSlot = (node: object, segment: string): void => {\n if (Array.isArray(node) && !isArraySlot(node, segment)) throw new PropertyNotUpdatableError(path, stateOf(instance).name)\n }\n let node = target[root] as Record<string, unknown>\n if (!isRecord(node) && !Array.isArray(node)) target[root] = node = {}\n for (const segment of rest.slice(0, -1)) {\n assertSlot(node, segment)\n const next = node[segment]\n node = isRecord(next) || Array.isArray(next) ? (next as Record<string, unknown>) : (node[segment] = {} as Record<string, unknown>)\n }\n const last = rest.at(-1)!\n assertSlot(node, last)\n Object.defineProperty(node, last, { value, enumerable: true, writable: true, configurable: true })\n }\n await hook(instance, 'updated', path, value)\n await hook(instance, `updated${studly}`, value, key)\n }\n\n /** Runs one call from the browser: a magic action, an event, or a public method. Returns its return value. */\n private async call(instance: Component, method: string, params: unknown[]): Promise<unknown> {\n const name = stateOf(instance).name\n switch (method) {\n case '$refresh':\n return undefined\n case '$set':\n return this.applyUpdate(instance, String(params[0]), params[1])\n case '$toggle': {\n const path = String(params[0])\n const current = path.split('.').reduce<unknown>((node, segment) => (isRecord(node) || Array.isArray(node) ? (node as Record<string, unknown>)[segment] : undefined), instance)\n return this.applyUpdate(instance, path, !current)\n }\n case '__dispatch': {\n const [event, detail] = params\n // Own keys only: an event named 'constructor' or '__proto__' must not reach Object.prototype.\n const listeners = listenersOf(instance.constructor)\n for (const listener of Object.hasOwn(listeners, String(event)) ? listeners[String(event)]! : []) {\n if (!isCallable(instance, listener)) throw new MethodNotCallableError(listener, name)\n await (instance as unknown as Record<string, (params: unknown) => unknown>)[listener]!(isRecord(detail) ? detail : {})\n }\n return undefined\n }\n }\n if (!isCallable(instance, method)) throw new MethodNotCallableError(method, name)\n return (instance as unknown as Record<string, (...args: unknown[]) => unknown>)[method]!(...params)\n }\n\n /** Renders the component (rendering/rendered hooks, nested children tracked) and checks for a single root. */\n private async render(instance: Component, memo: Memo, previous: Children): Promise<{ html: string; tag: string }> {\n await hook(instance, 'rendering')\n const context: RenderContext = { previous, children: {}, index: 0 }\n const html = await renderContext.run(context, async () => {\n const output = await instance.render()\n return typeof output === 'string' ? output : this.container().make(ViewFactory).renderToString(output)\n })\n await hook(instance, 'rendered', html)\n memo.children = context.children\n return { html: html.trim(), tag: rootTag(html, memo.name) }\n }\n\n /** Dispatches, redirects: the effects every response carries. */\n private effects(instance: Component): LiveEffects {\n const state = stateOf(instance)\n const effects: LiveEffects = {}\n if (state.dispatches.length > 0) {\n effects.dispatches = state.dispatches.map(({ name, params, self, to }) => ({\n name,\n params,\n ...(self ? { self } : {}),\n ...(to === undefined ? {} : { to: typeof to === 'string' ? to : this.nameOf(to) }),\n }))\n }\n if (state.redirect !== undefined) effects.redirect = state.redirect\n if (state.redirectUsingNavigate) effects.redirectUsingNavigate = true\n return effects\n }\n\n /** dehydrate() hook, then the state as snapshot data, the error bag, and the checksum over both. */\n private async snapshot(instance: Component, memo: Memo): Promise<LiveSnapshot> {\n await hook(instance, 'dehydrate')\n const registry = this.registry()\n const data: Record<string, unknown> = {}\n for (const [property, value] of Object.entries(instance)) data[property] = dehydrate(value, registry, `${memo.name}.${property}`)\n const signed = { data, memo: { ...memo, errors: { ...stateOf(instance).errors } } }\n return { ...signed, checksum: checksum(this.key(), signed) }\n }\n}\n","import { createHmac, timingSafeEqual } from 'node:crypto'\n\n/** JSON with object keys sorted at every level, so the browser's key order can't change the checksum. */\nexport function canonicalJson(value: unknown): string {\n if (Array.isArray(value)) return `[${value.map((item) => canonicalJson(item === undefined ? null : item)).join(',')}]`\n if (typeof value === 'object' && value !== null) {\n const entries = Object.keys(value)\n .sort()\n .filter((key) => (value as Record<string, unknown>)[key] !== undefined)\n .map((key) => `${JSON.stringify(key)}:${canonicalJson((value as Record<string, unknown>)[key])}`)\n return `{${entries.join(',')}}`\n }\n return JSON.stringify(value)\n}\n\n/** HMAC-SHA256 (hex) of the snapshot's data and memo, keyed by APP_KEY. */\nexport function checksum(key: Uint8Array, payload: { data: unknown; memo: unknown }): string {\n return createHmac('sha256', key).update(canonicalJson({ data: payload.data, memo: payload.memo })).digest('hex')\n}\n\n/** Constant-time comparison of a snapshot's checksum with the expected one. */\nexport function verifyChecksum(key: Uint8Array, payload: { data: unknown; memo: unknown }, given: unknown): boolean {\n if (typeof given !== 'string') return false\n const expected = Buffer.from(checksum(key, payload), 'utf8')\n const actual = Buffer.from(given, 'utf8')\n return expected.length === actual.length && timingSafeEqual(expected, actual)\n}\n","import { existsSync, readdirSync } from 'node:fs'\nimport { join, relative, sep } from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport { Str } from '@orieljs/support'\n\n/** A component's Livewire name from its path under app/Live: Posts/CreatePost.tsx → posts.create-post. */\nexport function componentName(file: string): string {\n return file\n .replace(/\\.(tsx|ts|jsx|js|mts|mjs)$/, '')\n .split(/[\\\\/]/)\n .map((segment) => Str.kebab(segment))\n .join('.')\n}\n\n/** A class's default name when it is mounted without being registered: CreatePost → create-post. */\nexport function defaultName(cls: object): string | undefined {\n const name = (cls as { name?: unknown }).name\n return typeof name === 'string' && name !== '' ? Str.kebab(name) : undefined\n}\n\n/** Component files under `directory` (recursive), relative paths with `/`. Test and declaration files are skipped. */\nexport function componentFiles(directory: string): string[] {\n if (!existsSync(directory)) return []\n return readdirSync(directory, { recursive: true, encoding: 'utf8' })\n .filter((file) => /\\.(tsx|ts|jsx|js|mts|mjs)$/.test(file) && !/\\.(test|spec|d)\\.[^.]+$/.test(file))\n .map((file) => file.split(sep).join('/'))\n .sort()\n}\n\n/** Imports every component file under `directory` and returns [name, default export] pairs. */\nexport async function discover(directory: string): Promise<Array<[name: string, exported: unknown]>> {\n const found: Array<[string, unknown]> = []\n for (const file of componentFiles(directory)) {\n const module = (await import(/* @vite-ignore */ pathToFileURL(join(directory, file)).href)) as { default?: unknown }\n found.push([componentName(relative(directory, join(directory, file))), module.default])\n }\n return found\n}\n","import type { Container, HttpRequest, Middleware, MiddlewareClass, MiddlewareReference, Next, Route, Router } from '@orieljs/contracts'\nimport { LiveError } from './errors'\n\n/** The route middleware an update re-applies by default (config live.persistent_middleware), by alias. */\nexport const PERSISTENT_MIDDLEWARE = ['auth', 'verified', 'guest']\n\n/** A route middleware after alias and group expansion: 'auth:web' → { cls: Authenticate, parameters: ['web'] }. */\nexport interface PersistentMiddleware {\n readonly cls: MiddlewareClass\n readonly parameters: readonly string[]\n}\n\n/**\n * What persistent middleware reads from Oriel's router beyond the Router contract: the public matching and middleware\n * methods of @orieljs/routing's BaseRouter and RouteDefinition.\n */\ninterface MatchingRoute extends Route {\n readonly isFallback?: boolean\n match(path: string, patterns: Readonly<Record<string, string>>, version: number): Record<string, string | undefined> | undefined\n gatherMiddleware(): MiddlewareReference[]\n excludedMiddleware(): MiddlewareReference[]\n}\n\ninterface MatchingRouter extends Router {\n getRoutesByMatchOrder(): readonly MatchingRoute[]\n getPatterns(): Readonly<Record<string, string>>\n getPatternVersion(): number\n getMiddleware(): Readonly<Record<string, MiddlewareClass>>\n getMiddlewareGroups(): Record<string, MiddlewareReference[]>\n}\n\nfunction canMatch(router: Router): router is MatchingRouter {\n const methods = router as unknown as Record<string, unknown>\n return ['getRoutesByMatchOrder', 'getPatterns', 'getPatternVersion', 'getMiddleware', 'getMiddlewareGroups'].every((name) => typeof methods[name] === 'function')\n}\n\nfunction isMatchingRoute(route: unknown): route is MatchingRoute {\n const candidate = route as Record<string, unknown> | null\n return (\n typeof candidate === 'object' &&\n candidate !== null &&\n Array.isArray(candidate.methods) &&\n ['match', 'gatherMiddleware', 'excludedMiddleware'].every((name) => typeof candidate[name] === 'function')\n )\n}\n\n/** request.path() ('posts/1', '/') in the form routes match against ('/posts/1', ''). */\nfunction routePath(path: string): string {\n const trimmed = path.replace(/^\\/+|\\/+$/g, '').replace(/\\/{2,}/g, '/')\n return trimmed === '' ? '' : `/${trimmed}`\n}\n\n/** Expands aliases and groups like the router does; unknown names are skipped (the page request would have failed). */\nfunction expand(\n references: readonly MiddlewareReference[],\n aliases: Readonly<Record<string, MiddlewareClass>>,\n groups: Readonly<Record<string, readonly MiddlewareReference[]>>,\n out: PersistentMiddleware[] = [],\n visiting = new Set<string>(),\n): PersistentMiddleware[] {\n for (const reference of references) {\n if (typeof reference === 'function') {\n out.push({ cls: reference, parameters: [] })\n continue\n }\n const index = reference.indexOf(':')\n const name = index === -1 ? reference : reference.slice(0, index)\n if (index === -1 && Object.hasOwn(groups, name)) {\n if (visiting.has(name)) continue\n visiting.add(name)\n expand(groups[name]!, aliases, groups, out, visiting)\n visiting.delete(name)\n } else if (Object.hasOwn(aliases, name)) {\n out.push({ cls: aliases[name]!, parameters: index === -1 ? [] : reference.slice(index + 1).split(',') })\n }\n }\n return out\n}\n\n/**\n * Livewire's persistent middleware: the route that rendered the page (the component's memo path and method) is\n * matched again, and the middleware among `persistent` (aliases) that it ran are returned, to run before an update.\n * A path no route matches has none.\n */\nexport function persistentMiddleware(router: Router, persistent: readonly string[], method: string, path: string): PersistentMiddleware[] {\n if (!canMatch(router)) throw new LiveError(\"Live re-applies the page route's middleware to updates, which needs Oriel's router.\")\n const routes = router.getRoutesByMatchOrder()\n if (!Array.isArray(routes) || !routes.every(isMatchingRoute)) throw new LiveError(\"Live re-applies the page route's middleware to updates, which needs Oriel's routes.\")\n const verb = method.toUpperCase()\n const target = routePath(path)\n const patterns = router.getPatterns()\n const version = router.getPatternVersion()\n const route = routes.find((candidate) => candidate.methods.includes(verb) && candidate.match(target, patterns, version) !== undefined)\n if (route === undefined) return []\n const aliases = router.getMiddleware()\n const groups = router.getMiddlewareGroups()\n const wanted = new Set(persistent.flatMap((name) => (Object.hasOwn(aliases, name) ? [aliases[name]!] : [])))\n const excluded = new Set(expand(route.excludedMiddleware(), aliases, groups).map((entry) => entry.cls))\n const ids = new Map<MiddlewareClass, number>()\n const seen = new Set<string>()\n return expand(route.gatherMiddleware(), aliases, groups).filter((entry) => {\n if (!ids.has(entry.cls)) ids.set(entry.cls, ids.size)\n const key = `${ids.get(entry.cls)}:${entry.parameters.join(',')}`\n if (!wanted.has(entry.cls) || excluded.has(entry.cls) || seen.has(key)) return false\n seen.add(key)\n return true\n })\n}\n\n/**\n * Runs `destination` behind the middleware, built from `container` (the request scope). A middleware may answer\n * instead (a redirect) or throw (AuthenticationError): then the update never runs. Like Livewire's pipeline, the\n * `next` the middleware sees resolves to an empty Response; the update's own result is kept aside.\n */\nexport async function throughMiddleware<T>(container: Container, request: HttpRequest, middleware: readonly PersistentMiddleware[], destination: () => Promise<T>): Promise<T | Response> {\n let ran: { result: T } | undefined\n const run = async (index: number): Promise<Response> => {\n if (index === middleware.length) {\n ran = { result: await destination() }\n return new Response(null, { status: 204 })\n }\n const { cls, parameters } = middleware[index]!\n const instance: Middleware = container.make(cls)\n const next: Next = () => run(index + 1)\n return instance.handle(request, next, ...parameters)\n }\n const response = await run(0)\n return ran ? ran.result : response\n}\n","import { Collection } from '@orieljs/collections'\nimport { Component } from './Component'\nimport { computedOf, lockedOf } from './metadata'\nimport { isModel } from './synthesizers'\n\n/** Lifecycle hooks and the render method: never actions (Livewire's protected method list). */\nconst HOOKS = new Set(['constructor', 'render', 'mount', 'boot', 'booted', 'hydrate', 'dehydrate', 'updating', 'updated', 'rendering', 'rendered', 'exception'])\nconst HOOK_PREFIX = /^(updating|updated|hydrate|dehydrate)[A-Z_]/\n/** Path segments that could reach a prototype. */\nconst UNSAFE_SEGMENTS = new Set(['__proto__', 'prototype', 'constructor'])\n\n/** Component's own API (dispatch, validate, reset, __invoke, …): computed once from its prototype. */\nconst BASE_API = new Set(Object.getOwnPropertyNames(Component.prototype))\n/** A canonical array index: '0', '12'; not '01', '-1', '1.5' or 'length'. */\nconst INDEX = /^(?:0|[1-9]\\d*)$/\n\n/**\n * Whether the browser may address `segment` of `array`: an existing item or the next one (an append). Anything else\n * would add a named property to the array or leave holes in it (a huge index makes it billions of items long).\n */\nexport function isArraySlot(array: readonly unknown[], segment: string): boolean {\n return INDEX.test(segment) && Number(segment) <= array.length\n}\n\n/**\n * Whether the browser may call `method`: a public method declared on the user's classes below Component, not a hook,\n * not `_private`, not `$magic` (those are handled separately), not a getter and not @Locked.\n */\nexport function isCallable(instance: Component, method: string): boolean {\n if (method === '' || method.startsWith('_') || method.startsWith('$') || method.startsWith('#')) return false\n if (HOOKS.has(method) || HOOK_PREFIX.test(method) || BASE_API.has(method)) return false\n if (lockedOf(instance.constructor).has(method)) return false\n // Stops at Component.prototype, or at Object.prototype for a component built on another copy of Component.\n const isBase = (proto: object) => proto === Component.prototype || proto === Object.prototype\n for (let proto = Object.getPrototypeOf(instance) as object | null; proto !== null && !isBase(proto); proto = Object.getPrototypeOf(proto) as object | null) {\n const descriptor = Object.getOwnPropertyDescriptor(proto, method)\n if (descriptor !== undefined) return typeof descriptor.value === 'function'\n }\n return false\n}\n\n/**\n * Whether the browser may set `path` ('title', 'items.0.name'): the root must be an existing public field that is not\n * `_private`, @Locked or computed; models and collections can't be changed, wherever they sit in the path (nor their\n * attributes); an array is only reached by the index of an existing item or the next one; no prototype keys.\n */\nexport function isUpdatable(instance: Component, path: string): boolean {\n const segments = path.split('.')\n const root = segments[0]!\n if (root === '' || root.startsWith('_') || segments.some((segment) => segment === '' || UNSAFE_SEGMENTS.has(segment))) return false\n if (!Object.hasOwn(instance, root)) return false\n const descriptor = Object.getOwnPropertyDescriptor(instance, root)!\n if (!descriptor.enumerable || descriptor.get !== undefined) return false\n const cls = instance.constructor\n if (lockedOf(cls).has(root) || computedOf(cls).has(root)) return false\n // Walk the existing value along the path: a model or collection anywhere on the way (the root, an array item, an\n // object member, the final value) is read-only, so its attributes can't be set through a dotted path either.\n let node = descriptor.value as unknown\n for (const segment of segments.slice(1)) {\n if (isModel(node) || node instanceof Collection) return false\n if (Array.isArray(node) && !isArraySlot(node, segment)) return false\n if (typeof node !== 'object' || node === null || !Object.hasOwn(node, segment)) return true\n node = (node as Record<string, unknown>)[segment]\n }\n return !isModel(node) && !(node instanceof Collection)\n}\n","import type { Class, ClassRegistry, ModelInstance, ModelStatic } from '@orieljs/contracts'\nimport { Collection } from '@orieljs/collections'\nimport { LiveError } from './errors'\n\n/** A JSON value as it travels in a snapshot. Non-scalars are Livewire-style tuples: [value, { s: '<synth>', … }]. */\nexport type Dehydrated = null | boolean | number | string | [unknown, SynthMeta]\nexport interface SynthMeta {\n s: 'u' | 'arr' | 'obj' | 'dt' | 'mdl' | 'elcln' | 'clctn'\n class?: string\n key?: unknown\n keys?: unknown[]\n}\n\n/** The same structural model check as Queue's serialization: what the ModelInstance contract guarantees. */\nexport function isModel(value: unknown): value is ModelInstance {\n if (typeof value !== 'object' || value === null) return false\n const candidate = value as Record<string, unknown>\n return (\n typeof candidate.getKey === 'function' &&\n typeof candidate.getKeyName === 'function' &&\n typeof candidate.getTable === 'function' &&\n typeof candidate.exists === 'boolean'\n )\n}\n\nconst isPlainObject = (value: object): boolean => {\n const proto: unknown = Object.getPrototypeOf(value)\n return proto === Object.prototype || proto === null\n}\n\nconst isTuple = (value: unknown): value is [unknown, SynthMeta] =>\n Array.isArray(value) &&\n value.length === 2 &&\n typeof value[1] === 'object' &&\n value[1] !== null &&\n !Array.isArray(value[1]) &&\n typeof (value[1] as Partial<SynthMeta>).s === 'string'\n\n/** The registry name of a model class, registering it under its class name the first time (as Queue does). */\nfunction classNameOf(registry: ClassRegistry, cls: Class<unknown>): string {\n return registry.nameOf(cls) ?? registry.register(cls)\n}\n\n/**\n * Encodes one public property value for the snapshot. Only primitives, arrays, plain objects, Dates, saved models and\n * collections are allowed (spec §5.2): anything else throws a LiveError naming the property.\n */\nexport function dehydrate(value: unknown, registry: ClassRegistry, path: string, seen: Set<object> = new Set()): Dehydrated {\n switch (typeof value) {\n case 'undefined':\n return [null, { s: 'u' }]\n case 'string':\n case 'boolean':\n return value\n case 'number':\n if (!Number.isFinite(value)) throw new LiveError(`Property [${path}] is ${value}: Live state must be JSON (finite numbers only).`)\n return value\n case 'bigint':\n case 'symbol':\n case 'function':\n throw new LiveError(`Property [${path}] holds a ${typeof value}: Live state may only hold primitives, arrays, plain objects, Dates, models and collections.`)\n }\n if (value === null) return null\n const object = value as object\n if (seen.has(object)) throw new LiveError(`Property [${path}] contains a circular reference.`)\n seen.add(object)\n try {\n if (object instanceof Date) return [object.toISOString(), { s: 'dt' }]\n if (Array.isArray(object)) return [object.map((item, i) => dehydrate(item, registry, `${path}.${i}`, seen)), { s: 'arr' }]\n if (isModel(object)) {\n const name = classNameOf(registry, object.constructor as Class<unknown>)\n if (!object.exists) throw new LiveError(`Property [${path}] holds an unsaved [${name}] model: only saved models can be kept between requests.`)\n return [null, { s: 'mdl', class: name, key: object.getKey() }]\n }\n if (object instanceof Collection) {\n const items = object.all() as unknown[]\n const first = items[0]\n if (items.length > 0 && isModel(first) && items.every((item) => isModel(item) && item.constructor === first.constructor)) {\n for (const [i, item] of items.entries()) {\n if (!(item as ModelInstance).exists) throw new LiveError(`Property [${path}.${i}] holds an unsaved model.`)\n }\n const name = classNameOf(registry, first.constructor as Class<unknown>)\n return [null, { s: 'elcln', class: name, keys: items.map((item) => (item as ModelInstance).getKey()) }]\n }\n return [items.map((item, i) => dehydrate(item, registry, `${path}.${i}`, seen)), { s: 'clctn' }]\n }\n if (isPlainObject(object)) {\n const out: Record<string, Dehydrated> = {}\n for (const [key, item] of Object.entries(object)) out[key] = dehydrate(item, registry, `${path}.${key}`, seen)\n return [out, { s: 'obj' }]\n }\n const type = (object.constructor as { name?: string } | undefined)?.name || 'object'\n throw new LiveError(\n `Property [${path}] holds a [${type}] instance: Live state may only hold primitives, arrays, plain objects, Dates, models and collections.`,\n )\n } finally {\n seen.delete(object)\n }\n}\n\nfunction modelClass(registry: ClassRegistry, name: unknown): ModelStatic {\n if (typeof name !== 'string' || !registry.has(name)) throw new LiveError(`Unable to hydrate the [${String(name)}] model: it is not registered.`)\n return registry.resolve(name) as unknown as ModelStatic\n}\n\n/** Decodes one snapshot value. Models are re-fetched (a missing row throws the database's ModelNotFound error). */\nexport async function hydrate(value: unknown, registry: ClassRegistry): Promise<unknown> {\n if (!isTuple(value)) return value\n const [inner, meta] = value\n switch (meta.s) {\n case 'u':\n return undefined\n case 'dt':\n return new Date(String(inner))\n case 'arr':\n return Promise.all((inner as unknown[]).map((item) => hydrate(item, registry)))\n case 'clctn':\n return new Collection(await Promise.all((inner as unknown[]).map((item) => hydrate(item, registry))))\n case 'obj': {\n const out: Record<string, unknown> = {}\n for (const [key, item] of Object.entries(inner as Record<string, unknown>)) {\n // JSON.parse makes `__proto__` an own key: define it as data so it can't swap the prototype.\n Object.defineProperty(out, key, { value: await hydrate(item, registry), enumerable: true, writable: true, configurable: true })\n }\n return out\n }\n case 'mdl':\n return modelClass(registry, meta.class).findOrFail(meta.key)\n case 'elcln': {\n const cls = modelClass(registry, meta.class)\n const keys = meta.keys ?? []\n const keyName = new cls().getKeyName()\n const found = [...((await cls.query().whereIn(keyName, keys).get()) as Iterable<ModelInstance>)]\n const byKey = new Map(found.map((model) => [String(model.getKey()), model]))\n return new Collection(keys.map((key) => byKey.get(String(key))).filter((model) => model !== undefined))\n }\n }\n throw new LiveError(`Unknown snapshot value type [${String(meta.s)}].`)\n}\n","import { ConfigRepository, ConsoleKernel, HttpRequest, LiveManager, Router } from '@orieljs/contracts'\nimport { inject } from '@orieljs/container'\nimport { ServiceProvider } from '@orieljs/support'\nimport { registerLiveCommands } from './commands'\nimport { isComponentClass } from './Component'\nimport { LiveComponentManager } from './LiveComponentManager'\nimport { discover } from './naming'\nimport { PERSISTENT_MIDDLEWARE } from './persistent'\n\n/** The URI the client runtime posts updates to. */\nexport const UPDATE_URI = '/oriel/live/update'\n\n/**\n * Binds the LiveManager, merges the `live` config, registers POST /oriel/live/update (named `live.update`, in the `web`\n * group: sessions and CSRF apply), the make:live command, and the components under app/Live.\n */\nexport class LiveServiceProvider extends ServiceProvider {\n override register(): void {\n // persistent_middleware: the page route's middleware (aliases) every update re-applies, Livewire's persistent middleware.\n this.mergeConfigFrom({ class_path: this.app.appPath('Live'), layout: 'components.layouts.app', persistent_middleware: [...PERSISTENT_MIDDLEWARE] }, 'live')\n this.app.singleton(LiveComponentManager, () => new LiveComponentManager(this.app))\n this.app.singleton(LiveManager, (container) => container.make(LiveComponentManager))\n }\n\n override async boot(): Promise<void> {\n const manager = this.app.make(LiveComponentManager)\n if (this.app.bound(Router)) {\n this.app\n .make(Router)\n .post(UPDATE_URI, () => manager.handle(inject(HttpRequest)))\n .middleware('web')\n .name('live.update')\n }\n if (this.app.bound(ConsoleKernel)) registerLiveCommands(this.app.make(ConsoleKernel), this.app)\n const directory = this.app.make(ConfigRepository).get<string>('live.class_path', this.app.appPath('Live'))\n for (const [name, exported] of await this.app.run(() => discover(directory))) {\n if (isComponentClass(exported)) manager.register(exported, name)\n }\n }\n}\n","import { existsSync } from 'node:fs'\nimport { mkdir, writeFile } from 'node:fs/promises'\nimport { dirname, join, relative, sep } from 'node:path'\nimport { ConfigRepository, type Application, type CommandContext, type ConsoleKernel } from '@orieljs/contracts'\nimport { Str } from '@orieljs/support'\n\n/** app/Live/<Path>.tsx, written by make:live. */\nexport const COMPONENT_STUB = `import { Component } from '@orieljs/framework'\n\nexport default class {{ class }} extends Component {\n render() {\n return <div></div>\n }\n}\n`\n\n/** tests/Feature/Live/<Path>.test.ts, written by make:live --test. */\nexport const TEST_STUB = `import { Live } from '@orieljs/framework'\nimport { expect, test } from 'vitest'\nimport {{ class }} from '{{ component }}'\nimport { TestCase } from '{{ testCase }}'\n\nTestCase.boot()\n\ntest('{{ name }} renders', async () => {\n const component = await Live.test({{ class }})\n expect(component.html()).toContain('<div')\n})\n`\n\nconst CLASS_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/\n\n/** An import specifier from `from` (a file) to `to` (a file, extension dropped), always relative (./ or ../). */\nfunction importPath(from: string, to: string): string {\n const path = relative(dirname(from), to).split(sep).join('/').replace(/\\.tsx?$/, '')\n return path.startsWith('.') ? path : `./${path}`\n}\n\n/** make:live Posts/CreatePost [--test] [--force] (Livewire's make:livewire). */\nexport function registerLiveCommands(kernel: ConsoleKernel, app: Application): void {\n kernel\n .command('make:live {name : The component name, e.g. Posts/CreatePost} {--test : Also create a test} {--force : Overwrite existing files}', async function (this: CommandContext) {\n const segments = String(this.argument('name') ?? '')\n .split(/[/\\\\.]+/)\n .filter((segment) => segment !== '')\n .map((segment) => Str.studly(segment))\n if (segments.length === 0 || !segments.every((segment) => CLASS_NAME.test(segment))) {\n this.error(`Component name [${String(this.argument('name'))}] is not valid: use names like Posts/CreatePost.`)\n return 1\n }\n const className = segments.at(-1)!\n const config = app.bound(ConfigRepository) ? app.make(ConfigRepository) : undefined\n const directory = config?.get<string>('live.class_path') ?? app.appPath('Live')\n const file = join(directory, ...segments.slice(0, -1), `${className}.tsx`)\n const force = this.option('force') === true\n if (existsSync(file) && !force) {\n this.error(`Component [${relative(app.basePath(), file)}] already exists.`)\n return 1\n }\n await mkdir(dirname(file), { recursive: true })\n await writeFile(file, COMPONENT_STUB.replace('{{ class }}', () => className))\n this.info(`Component [${relative(app.basePath(), file)}] created successfully.`)\n\n if (this.option('test') === true) {\n const testFile = app.basePath(join('tests', 'Feature', 'Live', ...segments.slice(0, -1), `${className}.test.ts`))\n if (existsSync(testFile) && !force) {\n this.error(`Test [${relative(app.basePath(), testFile)}] already exists.`)\n return 1\n }\n const name = segments.map((segment) => Str.kebab(segment)).join('.')\n const test = TEST_STUB.replaceAll('{{ class }}', () => className)\n .replace('{{ component }}', () => importPath(testFile, file))\n .replace('{{ testCase }}', () => importPath(testFile, app.basePath(join('tests', 'TestCase.ts'))))\n .replace('{{ name }}', () => name)\n await mkdir(dirname(testFile), { recursive: true })\n await writeFile(testFile, test)\n this.info(`Test [${relative(app.basePath(), testFile)}] created successfully.`)\n }\n return 0\n })\n .purpose('Create a new Live component')\n}\n"],"mappings":";AAAA,SAAS,aAAa,cAAc,yBAAkE;AACtG,SAAS,cAAc;;;ACMrB,OAAiC,aAAa,uBAAO,IAAI,iBAAiB;AAE5E,IAAM,YAAY,uBAAO,IAAI,sBAAsB;AACnD,IAAM,SAAS,uBAAO,IAAI,mBAAmB;AAC7C,IAAM,WAAW,uBAAO,IAAI,qBAAqB;AAQjD,SAAS,IAAO,UAAoB,KAAa,OAAgB,MAA8B;AAC7F,MAAI,CAAC,OAAO,OAAO,UAAU,GAAG,EAAG,UAAS,GAAG,IAAI,SAAS,GAAG,MAAM,SAAY,MAAM,IAAI,KAAK,SAAS,GAAG,CAAM;AAClH,SAAO,SAAS,GAAG;AACrB;AAGO,SAAS,GAAG,OAAe;AAChC,SAAO,SAAU,SAAkB,SAA4C;AAC7E,UAAM,YAAY;AAAA,MAA8B,QAAQ;AAAA,MAAsB;AAAA,MAAW,OAAO,CAAC;AAAA,MAAI,CAAC,cACpG,OAAO,YAAY,OAAO,QAAQ,SAAS,EAAE,IAAI,CAAC,CAAC,MAAMA,QAAO,MAAM,CAAC,MAAM,CAAC,GAAGA,QAAO,CAAC,CAAC,CAAC;AAAA,IAC7F;AAEA,UAAM,UAAW,UAAU,KAAK,MAAM,CAAC;AACvC,QAAI,CAAC,QAAQ,SAAS,OAAO,QAAQ,IAAI,CAAC,EAAG,SAAQ,KAAK,OAAO,QAAQ,IAAI,CAAC;AAAA,EAChF;AACF;AAGO,SAAS,OAAO,SAAkB,SAAyE;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QAAQ,CAAC,yBAAyB;AAAA,IAChF;AACA,WAAO;AAAA,EACT,CAAC,EACA,QAAQ,6BAA6B;AAC1C;;;ADvEO,IAAM,aAAa;AAMnB,IAAM,sBAAN,cAAkC,gBAAgB;AAAA,EAC9C,WAAiB;AAExB,SAAK,gBAAgB,EAAE,YAAY,KAAK,IAAI,QAAQ,MAAM,GAAG,QAAQ,0BAA0B,uBAAuB,CAAC,GAAG,qBAAqB,EAAE,GAAG,MAAM;AAC1J,SAAK,IAAI,UAAU,sBAAsB,MAAM,IAAI,qBAAqB,KAAK,GAAG,CAAC;AACjF,SAAK,IAAI,UAAUI,cAAa,CAAC,cAAc,UAAU,KAAK,oBAAoB,CAAC;AAAA,EACrF;AAAA,EAEA,MAAe,OAAsB;AACnC,UAAM,UAAU,KAAK,IAAI,KAAK,oBAAoB;AAClD,QAAI,KAAK,IAAI,MAAMC,OAAM,GAAG;AAC1B,WAAK,IACF,KAAKA,OAAM,EACX,KAAK,YAAY,MAAM,QAAQ,OAAOC,QAAOC,YAAW,CAAC,CAAC,EAC1D,WAAW,KAAK,EAChB,KAAK,aAAa;AAAA,IACvB;AACA,QAAI,KAAK,IAAI,MAAM,aAAa,EAAG,sBAAqB,KAAK,IAAI,KAAK,aAAa,GAAG,KAAK,GAAG;AAC9F,UAAM,YAAY,KAAK,IAAI,KAAKC,iBAAgB,EAAE,IAAY,mBAAmB,KAAK,IAAI,QAAQ,MAAM,CAAC;AACzG,eAAW,CAAC,MAAM,QAAQ,KAAK,MAAM,KAAK,IAAI,IAAI,MAAM,SAAS,SAAS,CAAC,GAAG;AAC5E,UAAI,iBAAiB,QAAQ,EAAG,SAAQ,SAAS,UAAU,IAAI;AAAA,IACjE;AAAA,EACF;AACF;","names":["methods","LiveManager","inject","LiveManager","inject","fail","token","inject","LiveManager","inject","LiveManager","currentContainer","Str","Collection","Collection","token","currentContainer","Str","node","ConfigRepository","HttpRequest","LiveManager","Router","inject","existsSync","join","relative","sep","ConfigRepository","Str","LiveManager","Router","inject","HttpRequest","ConfigRepository"]}
|
|
1
|
+
{"version":3,"sources":["../Component.ts","../metadata.ts","../embed.ts","../Testable.ts","../flash.ts","../errors.ts","../html.ts","../LiveComponentManager.ts","../checksum.ts","../naming.ts","../persistent.ts","../security.ts","../synthesizers.ts","../WithPagination.ts","../LiveServiceProvider.ts","../commands.ts","../Pagination.ts"],"sourcesContent":["import { LiveManager, UrlGenerator, ValidationFactory, type Class, type MessageBag, type Rules } from '@orieljs/contracts'\nimport { inject } from '@orieljs/container'\nimport { forgetComputed } from './metadata'\n\n/** Marks Live component classes (Symbol.for, so two copies of the package agree). */\nexport const COMPONENT: unique symbol = Symbol.for('oriel:live.component') as never\n\n/** A browser event queued by dispatch(). `to` is resolved to a component name when the effects are built. */\nexport interface QueuedDispatch {\n name: string\n params: Record<string, unknown>\n self?: true\n to?: string | Class<Component>\n}\n\n/** Per-request bookkeeping of one component instance. Kept outside the instance so it never becomes state. */\nexport interface ComponentState {\n id: string\n name: string\n errors: Record<string, string[]>\n dispatches: QueuedDispatch[]\n redirect?: string\n redirectUsingNavigate?: true\n skipRender: boolean\n}\n\nconst states = new WeakMap<object, ComponentState>()\n\n/** The bookkeeping of an instance, created on first use (an instance built by the router has none yet). */\nexport function stateOf(component: object): ComponentState {\n let state = states.get(component)\n if (state === undefined) states.set(component, (state = { id: '', name: '', errors: {}, dispatches: [], skipRender: false }))\n return state\n}\n\n/** Whether `value` is a class extending Component. */\nexport function isComponentClass(value: unknown): value is Class<Component> {\n return typeof value === 'function' && (value as unknown as Record<symbol, unknown>)[COMPONENT] === true\n}\n\n/** The validation errors of a component (Laravel's MessageBag), for render(): `this.errors.first('title')`. */\nexport class ErrorBag implements MessageBag {\n constructor(private readonly messages: Record<string, string[]>) {}\n\n has(key: string): boolean {\n return (this.messages[key]?.length ?? 0) > 0\n }\n\n first(key?: string): string | undefined {\n return key === undefined ? this.all()[0] : this.messages[key]?.[0]\n }\n\n get(key: string): string[] {\n return [...(this.messages[key] ?? [])]\n }\n\n all(): string[] {\n return Object.values(this.messages).flat()\n }\n\n any(): boolean {\n return !this.isEmpty()\n }\n\n isEmpty(): boolean {\n return this.count() === 0\n }\n\n count(): number {\n return this.all().length\n }\n\n toObject(): Record<string, string[]> {\n return Object.fromEntries(Object.entries(this.messages).map(([key, messages]) => [key, [...messages]]))\n }\n}\n\n/** What dispatch() returns: `this.dispatch('saved').self()` or `.to(Sidebar)`. */\nexport class PendingEvent {\n constructor(private readonly event: QueuedDispatch) {}\n\n /** Only this component's own listeners receive the event. */\n self(): this {\n this.event.self = true\n delete this.event.to\n return this\n }\n\n /** Only components of this class (or registered name) receive the event. */\n to(component: string | Class<Component>): this {\n this.event.to = component\n delete this.event.self\n return this\n }\n}\n\n/**\n * A Live component (Livewire 3): public fields are its state, public methods are actions the browser can call, and\n * render() returns its TSX. Lifecycle hooks, all optional: `boot()`, `mount(params)`, `hydrate()`, `dehydrate()`,\n * `updating(name, value)`/`updated(name, value)` and per property `updatingTitle(value)`/`updatedTitle(value)`,\n * `rendering()`/`rendered(html)`. Fields that must not be state use `#private` syntax.\n */\nexport abstract class Component {\n static readonly [COMPONENT] = true\n\n /** The view that wraps a full-page component (default: config `live.layout`). */\n static layout?: string\n /** The page title passed to the layout as `title`. */\n static title?: string\n /** Static fallbacks for runtimes without decorators: { event: 'method' }, locked names, computed getter names. */\n static listeners?: Record<string, string>\n static locked?: string[]\n static computed?: string[]\n\n abstract render(): unknown\n\n getId(): string {\n return stateOf(this).id\n }\n\n getName(): string {\n return stateOf(this).name\n }\n\n /** Dispatches a browser event; every component listening for it (@On) runs its handler. */\n dispatch(name: string, params: Record<string, unknown> = {}): PendingEvent {\n const event: QueuedDispatch = { name, params }\n stateOf(this).dispatches.push(event)\n return new PendingEvent(event)\n }\n\n /** Sends the browser to `url` after this request; `navigate` uses o:navigate instead of a full page load. */\n redirect(url: string, options: { navigate?: boolean } = {}): void {\n const state = stateOf(this)\n state.redirect = url\n if (options.navigate === true) state.redirectUsingNavigate = true\n else delete state.redirectUsingNavigate\n }\n\n redirectRoute(name: string, parameters?: unknown, options: { navigate?: boolean } = {}): void {\n this.redirect(inject(UrlGenerator).route(name, parameters), options)\n }\n\n /**\n * Validates the public state. On success clears the error bag and returns the validated data; on failure fills the\n * error bag and throws (the rest of the action is skipped and the component re-renders with `errors`).\n */\n async validate<T = Record<string, unknown>>(rules: Rules, messages?: Record<string, string>, attributes?: Record<string, string>): Promise<T> {\n const validator = inject(ValidationFactory).make(Object.fromEntries(Object.entries(this)), rules, messages, attributes)\n try {\n const data = await validator.validated<T>()\n stateOf(this).errors = {}\n return data\n } catch (error) {\n const errors = (error as { kind?: unknown; errors?: Record<string, string[]> }).errors\n if ((error as { kind?: unknown }).kind === 'Validation' && errors !== undefined) stateOf(this).errors = { ...errors }\n throw error\n }\n }\n\n addError(key: string, message: string): void {\n ;(stateOf(this).errors[key] ??= []).push(message)\n }\n\n /** Clears every error, or only those of `keys`. */\n resetErrorBag(...keys: string[]): void {\n const state = stateOf(this)\n if (keys.length === 0) state.errors = {}\n else for (const key of keys) delete state.errors[key]\n }\n\n get errors(): ErrorBag {\n return new ErrorBag(stateOf(this).errors)\n }\n\n /** Puts public properties (all of them when none are named) back to their initial values. */\n reset(...properties: string[]): void {\n const fresh = new (this.constructor as new () => Record<string, unknown>)()\n const names = properties.length > 0 ? properties : Object.keys(this)\n for (const name of names) if (Object.hasOwn(fresh, name)) (this as unknown as Record<string, unknown>)[name] = fresh[name]\n forgetComputed(this)\n }\n\n /** Keeps the current HTML: the response carries the new state but no `html` effect. */\n skipRender(): void {\n stateOf(this).skipRender = true\n }\n\n /** A full-page component as a route action: Route.get('/counter', Counter). Route parameters go to mount(). */\n async __invoke(): Promise<unknown> {\n return inject(LiveManager).page(this)\n }\n}\n","/**\n * TC39 decorators for Live components (@On, @Locked, @Computed) and the readers that merge them with the static\n * fallbacks (`static listeners`, `static locked`, `static computed`).\n *\n * Neither Node 24 nor Bun defines Symbol.metadata, and compilers only attach decorator metadata when it exists, so it\n * is installed (as the registered symbol, which TypeScript, esbuild and Bun agree on) before any component loads.\n */\n;(Symbol as { metadata?: symbol }).metadata ??= Symbol.for('Symbol.metadata')\n\nconst LISTENERS = Symbol.for('oriel:live.listeners')\nconst LOCKED = Symbol.for('oriel:live.locked')\nconst COMPUTED = Symbol.for('oriel:live.computed')\n\ntype Metadata = Record<PropertyKey, unknown>\n\n/**\n * The subclass's metadata object inherits from its parent's through the prototype chain, so a list read from it may\n * be the parent's: copy it onto the subclass before adding to it.\n */\nfunction own<T>(metadata: Metadata, key: symbol, empty: () => T, copy: (inherited: T) => T): T {\n if (!Object.hasOwn(metadata, key)) metadata[key] = metadata[key] === undefined ? empty() : copy(metadata[key] as T)\n return metadata[key] as T\n}\n\n/** @On('post-created'): calls the method when the event is dispatched (by this or any component, or the browser). */\nexport function On(event: string) {\n return function (_method: unknown, context: ClassMethodDecoratorContext): void {\n const listeners = own<Record<string, string[]>>(context.metadata as Metadata, LISTENERS, () => ({}), (inherited) =>\n Object.fromEntries(Object.entries(inherited).map(([name, methods]) => [name, [...methods]])),\n )\n // An override decorated like the method it replaces is still one listener.\n const methods = (listeners[event] ??= [])\n if (!methods.includes(String(context.name))) methods.push(String(context.name))\n }\n}\n\n/** @Locked: a property the browser can't change, or a method the browser can't call. */\nexport function Locked(_target: unknown, context: ClassFieldDecoratorContext | ClassMethodDecoratorContext): void {\n own<string[]>(context.metadata as Metadata, LOCKED, () => [], (inherited) => [...inherited]).push(String(context.name))\n}\n\n/** Per-instance caches of @Computed getters. A component instance lives for one request, so this is per request. */\nconst computedCache = new WeakMap<object, Map<string, unknown>>()\n\n/** Runs the getter once per instance (one request) and returns the cached value afterwards. */\nexport function cachedGetter<T>(name: string, getter: (this: object) => T): (this: object) => T {\n return function (this: object): T {\n let cache = computedCache.get(this)\n if (cache === undefined) computedCache.set(this, (cache = new Map()))\n if (!cache.has(name)) cache.set(name, getter.call(this))\n return cache.get(name) as T\n }\n}\n\n/** @Computed: a getter cached for the rest of the request, never part of the component's state. */\nexport function Computed<T>(getter: (this: object) => T, context: ClassGetterDecoratorContext): (this: object) => T {\n own<string[]>(context.metadata as Metadata, COMPUTED, () => [], (inherited) => [...inherited]).push(String(context.name))\n return cachedGetter(String(context.name), getter)\n}\n\n/** Drops the cached @Computed values of one instance (after `reset()`, for example). */\nexport function forgetComputed(instance: object): void {\n computedCache.delete(instance)\n}\n\ninterface Statics {\n listeners?: Record<string, string>\n locked?: string[]\n computed?: string[]\n [key: symbol]: unknown\n}\n\nfunction metadataOf(cls: Statics): Metadata {\n return (cls[(Symbol as unknown as { metadata: symbol }).metadata] as Metadata | undefined) ?? {}\n}\n\n/**\n * The classes from the root of the chain down to `cls`. Static properties shadow along the chain instead of merging, so\n * each level's own statics are read separately and added to its parent's.\n */\nfunction chainOf(cls: object): Statics[] {\n const chain: Statics[] = []\n for (let c: object | null = cls; c !== null && c !== Function.prototype; c = Object.getPrototypeOf(c) as object | null) {\n chain.unshift(c as Statics)\n }\n return chain\n}\n\n/** The values of the own static `key` of every class in the chain, parents first. */\nfunction staticsOf<K extends 'listeners' | 'locked' | 'computed'>(cls: object, key: K): NonNullable<Statics[K]>[] {\n return chainOf(cls).flatMap((c) => (Object.hasOwn(c, key) && c[key] !== undefined ? [c[key] as NonNullable<Statics[K]>] : []))\n}\n\n/** Event name → method names, from @On and `static listeners` (of the class and its parents). */\nexport function listenersOf(cls: object): Record<string, string[]> {\n const result: Record<string, string[]> = {}\n for (const [event, methods] of Object.entries((metadataOf(cls as Statics)[LISTENERS] as Record<string, string[]> | undefined) ?? {})) {\n result[event] = [...methods]\n }\n for (const listeners of staticsOf(cls, 'listeners')) {\n for (const [event, method] of Object.entries(listeners)) {\n const methods = (result[event] ??= [])\n if (!methods.includes(method)) methods.push(method)\n }\n }\n return result\n}\n\n/** Locked property and method names, from @Locked and `static locked` (of the class and its parents). */\nexport function lockedOf(cls: object): Set<string> {\n return new Set([...((metadataOf(cls as Statics)[LOCKED] as string[] | undefined) ?? []), ...staticsOf(cls, 'locked').flat()])\n}\n\n/** Computed getter names, from @Computed and `static computed` (of the class and its parents). */\nexport function computedOf(cls: object): Set<string> {\n return new Set([...((metadataOf(cls as Statics)[COMPUTED] as string[] | undefined) ?? []), ...staticsOf(cls, 'computed').flat()])\n}\n","import { LiveManager, type Class, type Htmlable } from '@orieljs/contracts'\nimport { inject } from '@orieljs/container'\nimport type { Component } from './Component'\nimport { Testable } from './Testable'\n\n/** Props of `<Live component={Counter} count={3} o:key=\"c1\" />`: the rest become mount params. */\nexport interface LiveProps {\n component: Class<Component> | string\n /** Identifies a child inside its parent across re-renders (Livewire's :key / wire:key). */\n 'o:key'?: string | number\n [param: string]: unknown\n}\n\n/** Blade's @livewire('counter', ['count' => 3], key('c1')): the component's first render, as trusted HTML. */\nexport async function live(component: Class<Component> | string, params: Record<string, unknown> = {}, key?: string | number): Promise<Htmlable> {\n const html = await inject(LiveManager).mount(component, params, key === undefined ? undefined : String(key))\n return { toHtml: () => html }\n}\n\n/** `<Live component={Counter} />` in any view or component. */\nfunction LiveComponent({ component, 'o:key': key, children: _children, ...params }: LiveProps): Promise<Htmlable> {\n return live(component, params, key)\n}\n\n/** The `<Live />` element, and the Live facade: Live.component(name, Class), Live.test(Component). */\nexport const Live = Object.assign(LiveComponent, {\n /** Registers a component under a name (components in app/Live are registered at boot). */\n component(name: string, component: Class<Component>): void {\n inject(LiveManager).register(component, name)\n },\n /** Livewire::test(): mounts `component` for assertions. */\n test<C extends Component>(component: Class<C> | string, params: Record<string, unknown> = {}): Promise<Testable<C>> {\n return Testable.create(component, params)\n },\n})\n","import { AssertionError } from 'node:assert'\nimport { isDeepStrictEqual } from 'node:util'\nimport { LiveManager, Session, token, type Class, type LiveEffects } from '@orieljs/contracts'\nimport { Container, currentContainer, inject } from '@orieljs/container'\nimport { stateOf, type Component } from './Component'\nimport { trackFlash } from './flash'\nimport { escapeAttribute } from './html'\nimport type { ComponentResult, LiveComponentManager } from './LiveComponentManager'\n\nconst fail = (message: string, actual?: unknown, expected?: unknown): never => {\n throw new AssertionError({ message, actual, expected, operator: 'live' })\n}\n\nconst getPath = (target: unknown, path: string): unknown =>\n path.split('.').reduce<unknown>((node, segment) => (typeof node === 'object' && node !== null ? (node as Record<string, unknown>)[segment] : undefined), target)\n\n/**\n * Runs Live.test()'s mount and each update. The testing package binds one for every test, so they run in a request\n * scope like the test's HTTP requests (a request, the carried session, actingAs users) and what they change carries\n * on to the next request. Without one they run in the current scope.\n */\nexport type TestRequestScope = <T>(run: () => Promise<T>) => Promise<T>\nexport const TestRequestScope = token<TestRequestScope>('Testing.RequestScope')\n\nfunction requestScope(): TestRequestScope {\n const container = currentContainer() ?? Container.getInstance()\n return container?.bound(TestRequestScope) === true ? container.make(TestRequestScope) : (run) => run()\n}\n\n/** The session of the current scope, when one is bound and resolvable. */\nfunction currentSession(): Session | undefined {\n const container = currentContainer()\n if (container?.bound(Session) !== true) return undefined\n try {\n return container.make(Session)\n } catch {\n return undefined\n }\n}\n\n/**\n * Livewire's Livewire::test(): drives one component through the real mount → snapshot → checksum → update pipeline\n * (no HTTP), inside the test's request scope. Actions are async (`await counter.call('increment')`); assertions are\n * sync and return `this`.\n */\nexport class Testable<C extends Component = Component> {\n #snapshot: string\n #html: string\n #effects: LiveEffects\n #instance: C\n\n private constructor(\n private readonly manager: LiveComponentManager,\n private readonly scope: TestRequestScope,\n result: ComponentResult,\n ) {\n this.#snapshot = JSON.stringify(result.snapshot)\n this.#html = result.html ?? ''\n this.#effects = result.effects\n this.#instance = result.instance as C\n }\n\n /** Mounts `component` with `params`, as `<Live component={…} {...params} />` would. */\n static async create<C extends Component>(component: Class<C> | string, params: Record<string, unknown> = {}): Promise<Testable<C>> {\n const scope = requestScope()\n const manager = inject(LiveManager) as unknown as LiveComponentManager\n return new Testable<C>(manager, scope, await scope(() => manager.mountComponent(component, params)))\n }\n\n /** The component instance after the last request. */\n instance(): C {\n return this.#instance\n }\n\n /** A public property (dotted paths reach into arrays and objects). */\n get<T = unknown>(path: string): T {\n return getPath(this.#instance, path) as T\n }\n\n /** The last rendered HTML, without the o:id, o:snapshot and o:effects attributes (Livewire strips them too). */\n html(): string {\n return this.#html.replace(/ o:(id|snapshot|effects)=\"[^\"]*\"/g, '')\n }\n\n /** The effects of the last request. */\n effects(): LiveEffects {\n return this.#effects\n }\n\n async set(path: string | Record<string, unknown>, value?: unknown): Promise<this> {\n return this.#update(typeof path === 'string' ? { [path]: value } : path, [])\n }\n\n async call(method: string, ...params: unknown[]): Promise<this> {\n return this.#update({}, [{ method, params }])\n }\n\n async toggle(path: string): Promise<this> {\n return this.#update({}, [{ method: '$toggle', params: [path] }])\n }\n\n /** Dispatches an event to this component, as the browser does for its listeners. */\n async dispatch(event: string, params: Record<string, unknown> = {}): Promise<this> {\n return this.#update({}, [{ method: '__dispatch', params: [event, params] }])\n }\n\n async refresh(): Promise<this> {\n return this.#update({}, [{ method: '$refresh', params: [] }])\n }\n\n async #update(updates: Record<string, unknown>, calls: Array<{ method: string; params: unknown[] }>): Promise<this> {\n // As an update request: a status flashed by the action is gone on the next request unless it redirects. The\n // test's request scope never saves its session, so the flash is forgotten once rendered.\n const result = await this.scope(async () => {\n const flashed = trackFlash(currentSession(), { saved: false })\n const updated = await this.manager.updateComponent(this.#snapshot, updates, calls)\n flashed(updated.effects.redirect !== undefined)\n return updated\n })\n this.#snapshot = JSON.stringify(result.snapshot)\n if (result.html !== undefined) this.#html = result.html\n this.#effects = result.effects\n this.#instance = result.instance as C\n return this\n }\n\n assertSet(path: string, value: unknown): this {\n const actual = this.get(path)\n if (!isDeepStrictEqual(actual, value)) fail(`Failed asserting that property [${path}] is set to the expected value.`, actual, value)\n return this\n }\n\n assertNotSet(path: string, value: unknown): this {\n if (isDeepStrictEqual(this.get(path), value)) fail(`Failed asserting that property [${path}] is not set to the given value.`, this.get(path), value)\n return this\n }\n\n /** Each value, HTML-escaped, appears in the rendered HTML. */\n assertSee(...values: string[]): this {\n for (const value of values) if (!this.html().includes(escapeAttribute(value))) fail(`Failed asserting that [${value}] is in the rendered HTML.`, this.html(), value)\n return this\n }\n\n assertDontSee(...values: string[]): this {\n for (const value of values) if (this.html().includes(escapeAttribute(value))) fail(`Failed asserting that [${value}] is not in the rendered HTML.`, this.html(), value)\n return this\n }\n\n /** Each value appears in the rendered HTML as written (not escaped). */\n assertSeeHtml(...values: string[]): this {\n for (const value of values) if (!this.html().includes(value)) fail(`Failed asserting that [${value}] is in the rendered HTML.`, this.html(), value)\n return this\n }\n\n assertDispatched(name: string, params?: Record<string, unknown>): this {\n const dispatched = (this.#effects.dispatches ?? []).filter((event) => event.name === name)\n if (dispatched.length === 0) fail(`Failed asserting that an event [${name}] was dispatched.`, this.#effects.dispatches ?? [], name)\n if (params !== undefined && !dispatched.some((event) => isDeepStrictEqual(event.params, params))) {\n fail(`Failed asserting that event [${name}] was dispatched with the expected params.`, dispatched.map((event) => event.params), params)\n }\n return this\n }\n\n assertNotDispatched(name: string): this {\n if ((this.#effects.dispatches ?? []).some((event) => event.name === name)) fail(`Failed asserting that an event [${name}] was not dispatched.`)\n return this\n }\n\n /** The error bag has errors for every key given (or any error at all with no keys). */\n assertHasErrors(keys: string | string[] = []): this {\n const errors = stateOf(this.#instance).errors\n const wanted = [keys].flat()\n if (wanted.length === 0 && Object.keys(errors).length === 0) fail('Component has no errors.', errors)\n for (const key of wanted) if ((errors[key]?.length ?? 0) === 0) fail(`Component missing error: ${key}`, errors, key)\n return this\n }\n\n /** No errors for the keys given (or none at all with no keys). */\n assertHasNoErrors(keys: string | string[] = []): this {\n const errors = stateOf(this.#instance).errors\n const wanted = [keys].flat()\n const found = wanted.length === 0 ? Object.keys(errors).filter((key) => (errors[key]?.length ?? 0) > 0) : wanted.filter((key) => (errors[key]?.length ?? 0) > 0)\n if (found.length > 0) fail(`Component has errors: \"${found.join('\", \"')}\"`, errors)\n return this\n }\n\n assertRedirect(url?: string): this {\n const redirect = this.#effects.redirect\n if (redirect === undefined) fail('Component did not perform a redirect.')\n if (url !== undefined && redirect !== url) fail('Component redirected to an unexpected URL.', redirect, url)\n return this\n }\n\n assertNoRedirect(): this {\n if (this.#effects.redirect !== undefined) fail('Component performed a redirect.', this.#effects.redirect)\n return this\n }\n\n /** The last call returned `value`. */\n assertReturned(value: unknown): this {\n const returned = this.#effects.returns?.at(-1)\n if (!isDeepStrictEqual(returned, value)) fail('Failed asserting that the method returned the expected value.', returned, value)\n return this\n }\n}\n","import type { Session } from '@orieljs/contracts'\n\n/**\n * Flash data during a Live update. The update renders in place, so a key first flashed during it (a status after an\n * action) is moved from `_flash.new` to `_flash.old`, as session().now() stores it: it shows in this response and is\n * gone on the next request. When the update redirects or navigates, its flashes stay for the next page (flash, then\n * redirect). This follows Livewire's SupportRedirects for the keys the update flashed. Unlike Livewire, which forgets\n * every key in `_flash.new` when nothing redirects, keys flashed before the update (by a middleware) are left alone.\n *\n * Call it before the update and what it returns after, with whether the update redirects. `saved: false` is for a\n * scope whose session is never saved, so never aged (Live.test()): those keys are forgotten after the render instead.\n */\nexport function trackFlash(session: Session | undefined, { saved = true }: { saved?: boolean } = {}): (redirected: boolean) => void {\n if (session === undefined) return () => undefined\n const before = new Set(session.get<string[]>('_flash.new', []))\n return (redirected) => {\n if (redirected) return\n const flashed = session.get<string[]>('_flash.new', [])\n const fresh = flashed.filter((key) => !before.has(key))\n if (fresh.length === 0) return\n session.put('_flash.new', flashed.filter((key) => before.has(key)))\n if (!saved) return session.forget(...fresh)\n const old = session.get<string[]>('_flash.old', [])\n session.put('_flash.old', [...old, ...fresh.filter((key) => !old.includes(key))])\n }\n}\n","import type { ErrorKind, OrielError } from '@orieljs/contracts'\n\n/** A Live programming error (unsupported state, a missing root element, an unknown component): a 500. */\nexport class LiveError extends Error implements OrielError {\n override readonly name: string = 'LiveError'\n readonly kind: ErrorKind = 'Server'\n readonly status: number = 500\n}\n\n/** A snapshot whose checksum doesn't match (tampered with, or signed with another APP_KEY). Nothing is hydrated. */\nexport class CorruptComponentPayloadError extends LiveError {\n override readonly name: string = 'CorruptComponentPayloadError'\n override readonly kind: ErrorKind = 'Authorization'\n override readonly status: number = 403\n\n constructor(component = 'unknown') {\n super(`Live encountered corrupt data when trying to hydrate the [${component}] component.`)\n }\n}\n\n/** The browser asked for a method that isn't a public action of the component. */\nexport class MethodNotCallableError extends LiveError {\n override readonly name: string = 'MethodNotCallableError'\n override readonly kind: ErrorKind = 'Authorization'\n override readonly status: number = 403\n\n constructor(method: string, component: string) {\n super(`Unable to call component method. Public method [${method}] not found on component [${component}].`)\n }\n}\n\n/** The browser tried to set a property that is locked, computed, private (`_x`) or not declared. */\nexport class PropertyNotUpdatableError extends LiveError {\n override readonly name: string = 'PropertyNotUpdatableError'\n override readonly kind: ErrorKind = 'Authorization'\n override readonly status: number = 403\n\n constructor(path: string, component: string) {\n super(`Cannot update property [${path}] on component [${component}]: it is not a public, unlocked property.`)\n }\n}\n\n/** A snapshot names a component that isn't registered. */\nexport class LiveComponentNotFoundError extends LiveError {\n override readonly name: string = 'LiveComponentNotFoundError'\n override readonly kind: ErrorKind = 'Http'\n override readonly status: number = 404\n\n constructor(component: string) {\n super(`Unable to find component: [${component}].`)\n }\n}\n\n/** An update request without the X-Oriel-Live header or with a malformed body. */\nexport class InvalidLiveRequestError extends LiveError {\n override readonly name: string = 'InvalidLiveRequestError'\n override readonly kind: ErrorKind = 'Http'\n override readonly status: number = 400\n}\n","import { LiveError } from './errors'\n\nconst ESCAPES: Record<string, string> = { '&': '&', '<': '<', '>': '>', '\"': '"', \"'\": ''' }\n\n/** Laravel's e(): for attribute values (the snapshot JSON goes into an attribute). */\nexport function escapeAttribute(value: string): string {\n return value.replace(/[&<>\"']/g, (char) => ESCAPES[char]!)\n}\n\nconst VOID = new Set(['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'source', 'track', 'wbr'])\nconst RAW_TEXT = new Set(['script', 'style', 'textarea', 'title'])\n/** A closing tag, or an opening tag with its (quoted) attributes. */\nconst TOKEN = /<\\/([A-Za-z][\\w:-]*)\\s*>|<([A-Za-z][\\w:-]*)(?:\\s+[^\\s\"'<>/=]+(?:\\s*=\\s*(?:\"[^\"]*\"|'[^']*'|[^\\s\"'=<>`]+))?)*\\s*(\\/?)>/g\n\n/** The name of the single root element of `html`; throws when there is none or there are several (Livewire's rule). */\nexport function rootTag(html: string, component: string): string {\n const fail = (): never => {\n throw new LiveError(`Live only supports one HTML element per component. Multiple root elements were detected for component [${component}].`)\n }\n const source = html.replace(/<!--[\\s\\S]*?-->/g, '').trim()\n let depth = 0\n let root: string | undefined\n let rootEnd = -1\n TOKEN.lastIndex = 0\n for (let match = TOKEN.exec(source); match !== null; match = TOKEN.exec(source)) {\n const [token, closing, opening, selfClosing] = match\n if (root === undefined && match.index !== 0) fail()\n if (depth === 0 && root !== undefined) fail()\n if (opening !== undefined) {\n const tag = opening.toLowerCase()\n root ??= tag\n if (selfClosing === '/' || VOID.has(tag)) {\n if (depth === 0) rootEnd = match.index + token.length\n continue\n }\n if (RAW_TEXT.has(tag)) {\n // Search the original string: lowercasing it can change its length (U+0130), which would shift the index.\n const closer = new RegExp(`</${tag}`, 'gi')\n closer.lastIndex = TOKEN.lastIndex\n const end = closer.exec(source)\n if (end !== null) TOKEN.lastIndex = end.index\n }\n depth++\n } else if (closing !== undefined) {\n if (--depth < 0) fail()\n if (depth === 0) rootEnd = match.index + token.length\n }\n }\n if (root === undefined || depth !== 0 || source.slice(rootEnd).trim() !== '') fail()\n return root!\n}\n\n/** Adds ` name=\"value\"` pairs (values escaped) right after the root tag's name. */\nexport function insertAttributesIntoRoot(html: string, attributes: Record<string, string>): string {\n const source = html.trim()\n const match = /^((?:<!--[\\s\\S]*?-->\\s*)*<[A-Za-z][\\w:-]*)/.exec(source)\n if (match === null) throw new LiveError('Live could not find the root element of the component.')\n const rendered = Object.entries(attributes)\n .map(([name, value]) => ` ${name}=\"${escapeAttribute(value)}\"`)\n .join('')\n return match[1] + rendered + source.slice(match[1]!.length)\n}\n","import { AsyncLocalStorage } from 'node:async_hooks'\nimport { randomBytes } from 'node:crypto'\nimport {\n ClassRegistry,\n ConfigRepository,\n CurrentRoute,\n Encrypter,\n HttpRequest,\n Redirector,\n Router,\n Session,\n ViewFactory,\n type Application,\n type Class,\n type Container,\n type LiveEffects,\n type LiveManager,\n type LiveSnapshot,\n type LiveUpdateRequest,\n type LiveUpdateResponse,\n type Token,\n} from '@orieljs/contracts'\nimport { currentContainer } from '@orieljs/container'\nimport { Str } from '@orieljs/support'\nimport { checksum, verifyChecksum } from './checksum'\nimport { isComponentClass, stateOf, type Component } from './Component'\nimport { LiveComponentNotFoundError, CorruptComponentPayloadError, InvalidLiveRequestError, LiveError, MethodNotCallableError, PropertyNotUpdatableError } from './errors'\nimport { trackFlash } from './flash'\nimport { escapeAttribute, insertAttributesIntoRoot, rootTag } from './html'\nimport { cachedGetter, computedOf, listenersOf } from './metadata'\nimport { defaultName } from './naming'\nimport { PERSISTENT_MIDDLEWARE, persistentPass, throughMiddleware } from './persistent'\nimport { isArraySlot, isCallable, isUpdatable } from './security'\nimport { dehydrate, hydrate } from './synthesizers'\nimport { outsidePagination, renderPaginated } from './WithPagination'\n\ntype Memo = LiveSnapshot['memo']\ntype Children = Memo['children']\ntype Call = { method: string; params: unknown[] }\n\n/** The children rendered so far by the component being rendered, and those it had before (for placeholders). */\ninterface RenderContext {\n previous: Children\n children: Children\n index: number\n}\n\n/** One component after a mount or an update: the live instance (for Live.test), its snapshot, effects and HTML. */\nexport interface ComponentResult {\n instance: Component\n snapshot: LiveSnapshot\n effects: LiveEffects\n /** The rendered HTML with o:id (and, after a mount, o:snapshot/o:effects); undefined after skipRender(). */\n html?: string\n tag?: string\n}\n\nconst renderContext = new AsyncLocalStorage<RenderContext>()\n\n/** The page an update belongs to (its memo path and method): components mounted during the update keep it. */\nconst pageRequest = new AsyncLocalStorage<{ path: string; method: string }>()\n\n/** A binding of the current container, or undefined (scoped bindings throw on the application outside a request). */\nfunction optional<T>(container: Container, token: Token<T>): T | undefined {\n if (!container.bound(token)) return undefined\n try {\n return container.make(token)\n } catch {\n return undefined\n }\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null && !Array.isArray(value)\n\n/** Sets an own enumerable property, even for a key like '__proto__' (an assignment would change the prototype). */\nfunction setOwn<T>(object: Record<string, T>, key: string, value: T): void {\n Object.defineProperty(object, key, { value, enumerable: true, writable: true, configurable: true })\n}\n\nasync function hook(instance: Component, name: string, ...args: unknown[]): Promise<void> {\n const method = (instance as unknown as Record<string, unknown>)[name]\n if (typeof method === 'function') await (method as (...values: unknown[]) => unknown).apply(instance, args)\n}\n\n/** Livewire's update request handling and first render, on Oriel's contracts. */\nexport class LiveComponentManager implements LiveManager {\n constructor(private readonly app: Application) {}\n\n /** The request scope when there is one (sessions, the current route), else the application. */\n private container(): Container {\n return currentContainer() ?? this.app\n }\n\n private registry(): ClassRegistry {\n return this.container().make(ClassRegistry)\n }\n\n /** Live.component('counter', Counter): registers a component under a name the snapshots use. */\n register(component: Class<unknown>, name?: string): void {\n if (!isComponentClass(component)) throw new LiveError(`[${component.name}] is not a Live component: it must extend Component.`)\n const resolved = name ?? defaultName(component)\n if (resolved === undefined) throw new LiveError('Anonymous component classes need a name: Live.component(name, Class).')\n this.registry().register(component, resolved)\n }\n\n /** The registered name of a component class, registering it under its kebab-case class name the first time. */\n nameOf(component: Class<Component>): string {\n const registry = this.registry()\n const existing = registry.nameOf(component)\n if (existing !== undefined) return existing\n this.register(component)\n return registry.nameOf(component)!\n }\n\n resolve(name: string): Class<Component> {\n const registry = this.registry()\n if (!registry.has(name)) throw new LiveComponentNotFoundError(name)\n const cls = registry.resolve(name)\n if (!isComponentClass(cls)) throw new LiveComponentNotFoundError(name)\n return cls\n }\n\n isLiveRequest(request: HttpRequest): boolean {\n return request.header('X-Oriel-Live') === 'true'\n }\n\n /** The first render: HTML with o:id, o:snapshot and o:effects on the root element. */\n async mount(component: string | Class<unknown>, params: Record<string, unknown> = {}, key?: string): Promise<string> {\n const context = renderContext.getStore()\n if (context === undefined) return (await this.mountComponent(component, params)).html!\n const childKey = key ?? `lw-${context.index++}`\n // Own keys only: a key taken from data ('constructor', '__proto__') must not find or change Object.prototype.\n const existing = Object.hasOwn(context.previous, childKey) ? context.previous[childKey] : undefined\n if (existing !== undefined) {\n // The child already lives in the browser: a placeholder the client keeps as it is (Livewire's behaviour).\n setOwn(context.children, childKey, existing)\n return `<${existing[0]} o:id=\"${escapeAttribute(existing[1])}\"></${existing[0]}>`\n }\n // Outside the parent's pagination window: the child's boot() reads the request, its mount() and render() its page.\n const result = await outsidePagination(() => this.mountComponent(component, params))\n setOwn(context.children, childKey, [result.tag!, result.snapshot.memo.id])\n return result.html!\n }\n\n async mountComponent(component: string | Class<unknown>, params: Record<string, unknown> = {}, existing?: Component): Promise<ComponentResult> {\n const cls = typeof component === 'string' ? this.resolve(component) : (component as Class<Component>)\n if (!isComponentClass(cls)) throw new LiveError(`[${(cls as { name?: string }).name}] is not a Live component: it must extend Component.`)\n const name = this.nameOf(cls)\n const instance = existing ?? this.container().make(cls)\n const state = stateOf(instance)\n state.id = randomBytes(15).toString('base64url')\n state.name = name\n await hook(instance, 'boot')\n for (const [property, value] of Object.entries(params)) {\n if (Object.hasOwn(instance, property)) (instance as unknown as Record<string, unknown>)[property] = value\n }\n this.prepareComputed(instance)\n const request = optional(this.container(), HttpRequest)\n const page = pageRequest.getStore() ?? { path: request?.path() ?? '', method: request?.method() ?? 'GET' }\n // A WithPagination component's mount() paginates with its page (one given at mount counts), as its render() does.\n await renderPaginated(instance, this.pageUrl(page.path), () => hook(instance, 'mount', params))\n const memo: Memo = { id: state.id, name, path: page.path, method: page.method, children: {}, errors: {} }\n const { html, tag } = await this.render(instance, memo, {})\n const effects = this.effects(instance)\n const listeners = Object.keys(listenersOf(cls))\n if (listeners.length > 0) effects.listeners = listeners\n const snapshot = await this.snapshot(instance, memo)\n const attributes: Record<string, string> = { 'o:snapshot': JSON.stringify(snapshot), 'o:effects': JSON.stringify(effects), 'o:id': state.id }\n return { instance, snapshot, effects, html: insertAttributesIntoRoot(html, attributes), tag }\n }\n\n /** Applies each component's updates and calls, re-renders it and returns its new snapshot and effects. */\n async update(request: LiveUpdateRequest): Promise<LiveUpdateResponse> {\n const components: LiveUpdateResponse['components'] = []\n for (const component of request.components) {\n const { memo } = this.verify(component.snapshot)\n const result = await pageRequest.run({ path: memo.path, method: memo.method }, () => this.updateComponent(component.snapshot, component.updates, component.calls))\n components.push({ snapshot: JSON.stringify(result.snapshot), effects: result.effects })\n }\n return { components }\n }\n\n async updateComponent(snapshotJson: string, updates: Record<string, unknown>, calls: Call[]): Promise<ComponentResult> {\n const snapshot = this.verify(snapshotJson)\n const cls = this.resolve(snapshot.memo.name)\n const instance = this.container().make(cls)\n const state = stateOf(instance)\n state.id = snapshot.memo.id\n state.name = snapshot.memo.name\n state.errors = { ...snapshot.memo.errors }\n await hook(instance, 'boot')\n const registry = this.registry()\n for (const [property, value] of Object.entries(snapshot.data)) {\n Object.defineProperty(instance, property, { value: await hydrate(value, registry), enumerable: true, writable: true, configurable: true })\n }\n this.prepareComputed(instance)\n\n const returns: unknown[] = []\n // A WithPagination component's hydrate(), updates and actions paginate with its page, as its render() does: a\n // @Computed paginator an action reads first is cached with that page.\n await renderPaginated(instance, this.pageUrl(snapshot.memo.path), async () => {\n await hook(instance, 'hydrate')\n try {\n for (const [path, value] of Object.entries(updates)) await this.applyUpdate(instance, path, value)\n for (const call of calls) returns.push(await this.call(instance, call.method, call.params))\n } catch (error) {\n // A failed validate() (or any validation error) stops the remaining calls; the component re-renders with errors.\n const errors = (error as { kind?: unknown; errors?: unknown }).errors\n if ((error as { kind?: unknown }).kind !== 'Validation' || !isRecord(errors)) throw error\n state.errors = { ...(errors as Record<string, string[]>) }\n }\n })\n\n const memo: Memo = { ...snapshot.memo, children: { ...snapshot.memo.children } }\n const effects = this.effects(instance)\n let html: string | undefined\n let tag: string | undefined\n if (!state.skipRender) {\n ;({ html, tag } = await this.render(instance, memo, snapshot.memo.children))\n html = insertAttributesIntoRoot(html, { 'o:id': state.id })\n effects.html = html\n }\n if (calls.length > 0) effects.returns = returns\n return { instance, snapshot: await this.snapshot(instance, memo), effects, html, tag }\n }\n\n /**\n * The route action of POST /oriel/live/update. Each component's update runs behind the persistent middleware of the\n * route that rendered its page (Livewire's): `auth`, `verified`, `guest` and `can`, with the page route's parameters\n * bound again. A signed-out tab gets a 401, a revoked ability a 403 and a deleted model a 404, before the component\n * hydrates. When a middleware answers instead (a redirect), that is the response. A key first flashed during the\n * update shows in this response only, unless the update redirects.\n */\n async handle(request: HttpRequest): Promise<LiveUpdateResponse | Response> {\n if (!this.isLiveRequest(request)) throw new InvalidLiveRequestError('Live update requests need the X-Oriel-Live header.')\n const container = this.container()\n const persistent = optional(container, ConfigRepository)?.get<string[]>('live.persistent_middleware', PERSISTENT_MIDDLEWARE) ?? PERSISTENT_MIDDLEWARE\n const components: LiveUpdateResponse['components'] = []\n const flashed = trackFlash(optional(container, Session))\n for (const component of this.payload(request).components) {\n // The memo is trusted only after its checksum holds.\n const { memo } = this.verify(component.snapshot)\n const pass = persistentPass(container.make(Router), persistent, memo.method, memo.path)\n const update = () => this.updateComponent(component.snapshot, component.updates, component.calls)\n const result = await pageRequest.run({ path: memo.path, method: memo.method }, () =>\n pass === undefined || pass.middleware.length === 0 ? update() : throughMiddleware(container, request, pass, update),\n )\n if (result instanceof Response) return result\n components.push({ snapshot: JSON.stringify(result.snapshot), effects: result.effects })\n }\n // A status flashed by an action shows in this response only, unless a component sends the browser elsewhere.\n flashed(components.some((component) => component.effects.redirect !== undefined))\n return { components }\n }\n\n /** A full-page component (Route.get('/counter', Counter)): mounted with the route parameters, inside the layout. */\n async page(component: Component): Promise<unknown> {\n const container = this.container()\n const params = { ...(optional(container, CurrentRoute)?.parameters ?? {}) }\n const cls = component.constructor as Class<Component> & { layout?: string; title?: string }\n const result = await this.mountComponent(cls, params, component)\n const redirect = result.effects.redirect\n if (redirect !== undefined) {\n return optional(container, Redirector)?.to(redirect) ?? new Response(null, { status: 302, headers: { Location: redirect } })\n }\n const layout = cls.layout ?? optional(container, ConfigRepository)?.get<string>('live.layout') ?? 'components.layouts.app'\n const html = result.html!\n const data: Record<string, unknown> = { children: { toHtml: () => html } }\n if (cls.title !== undefined) data.title = cls.title\n return container.make(ViewFactory).make(layout, data)\n }\n\n /** Parses and checks a snapshot: a bad checksum throws before anything is hydrated. */\n private verify(snapshotJson: unknown): LiveSnapshot {\n let snapshot: unknown\n try {\n snapshot = typeof snapshotJson === 'string' ? JSON.parse(snapshotJson) : undefined\n } catch {\n throw new CorruptComponentPayloadError()\n }\n if (!isRecord(snapshot) || !isRecord(snapshot.data) || !isRecord(snapshot.memo)) throw new CorruptComponentPayloadError()\n const memo = snapshot.memo as Partial<Memo>\n const name = typeof memo.name === 'string' ? memo.name : 'unknown'\n const key = this.key()\n let valid: boolean\n try {\n valid = verifyChecksum(key, { data: snapshot.data, memo: snapshot.memo }, snapshot.checksum)\n } catch {\n // A payload the checksum can't be computed over (nested too deep to walk) was never signed by this server.\n valid = false\n }\n if (!valid) throw new CorruptComponentPayloadError(name)\n return snapshot as unknown as LiveSnapshot\n }\n\n private key(): Uint8Array {\n return this.container().make(Encrypter).getKey()\n }\n\n /** The request body, read from the raw JSON when the request has it, so TrimStrings can't alter typed values. */\n private payload(request: HttpRequest): LiveUpdateRequest {\n let body: unknown\n try {\n const content = (request as { content?: () => string }).content\n body = typeof content === 'function' ? JSON.parse(content.call(request)) : request.all()\n } catch {\n throw new InvalidLiveRequestError('The Live update request body is not valid JSON.')\n }\n const components = isRecord(body) ? body.components : undefined\n const valid =\n Array.isArray(components) &&\n components.every(\n (component) =>\n isRecord(component) &&\n typeof component.snapshot === 'string' &&\n isRecord(component.updates) &&\n Array.isArray(component.calls) &&\n component.calls.every((call) => isRecord(call) && typeof call.method === 'string' && Array.isArray(call.params)),\n )\n if (!valid) throw new InvalidLiveRequestError('The Live update request body is malformed.')\n return body as unknown as LiveUpdateRequest\n }\n\n /** Makes every computed getter (static `computed` too) cache its value for the rest of the request. */\n private prepareComputed(instance: Component): void {\n for (const name of computedOf(instance.constructor)) {\n for (let proto = Object.getPrototypeOf(instance) as object | null; proto !== null; proto = Object.getPrototypeOf(proto) as object | null) {\n const getter = Object.getOwnPropertyDescriptor(proto, name)?.get\n if (getter === undefined) continue\n Object.defineProperty(instance, name, { get: cachedGetter(name, getter as (this: object) => unknown), enumerable: false, configurable: true })\n break\n }\n }\n }\n\n private async applyUpdate(instance: Component, path: string, value: unknown): Promise<void> {\n if (!isUpdatable(instance, path)) throw new PropertyNotUpdatableError(path, stateOf(instance).name)\n const [root, ...rest] = path.split('.') as [string, ...string[]]\n const key = rest.length > 0 ? rest.join('.') : undefined\n const studly = Str.studly(root)\n await hook(instance, 'updating', path, value)\n await hook(instance, `updating${studly}`, value, key)\n const target = instance as unknown as Record<string, unknown>\n if (rest.length === 0) target[root] = value\n else {\n // Arrays are checked again while writing: an updating hook may have changed one since isUpdatable(), and no write\n // (nor a container created on the way) may leave holes.\n const assertSlot = (node: object, segment: string): void => {\n if (Array.isArray(node) && !isArraySlot(node, segment)) throw new PropertyNotUpdatableError(path, stateOf(instance).name)\n }\n let node = target[root] as Record<string, unknown>\n if (!isRecord(node) && !Array.isArray(node)) target[root] = node = {}\n for (const segment of rest.slice(0, -1)) {\n assertSlot(node, segment)\n const next = node[segment]\n node = isRecord(next) || Array.isArray(next) ? (next as Record<string, unknown>) : (node[segment] = {} as Record<string, unknown>)\n }\n const last = rest.at(-1)!\n assertSlot(node, last)\n Object.defineProperty(node, last, { value, enumerable: true, writable: true, configurable: true })\n }\n await hook(instance, 'updated', path, value)\n await hook(instance, `updated${studly}`, value, key)\n }\n\n /** Runs one call from the browser: a magic action, an event, or a public method. Returns its return value. */\n private async call(instance: Component, method: string, params: unknown[]): Promise<unknown> {\n const name = stateOf(instance).name\n switch (method) {\n case '$refresh':\n return undefined\n case '$set':\n return this.applyUpdate(instance, String(params[0]), params[1])\n case '$toggle': {\n const path = String(params[0])\n const current = path.split('.').reduce<unknown>((node, segment) => (isRecord(node) || Array.isArray(node) ? (node as Record<string, unknown>)[segment] : undefined), instance)\n return this.applyUpdate(instance, path, !current)\n }\n case '__dispatch': {\n const [event, detail] = params\n // Own keys only: an event named 'constructor' or '__proto__' must not reach Object.prototype.\n const listeners = listenersOf(instance.constructor)\n for (const listener of Object.hasOwn(listeners, String(event)) ? listeners[String(event)]! : []) {\n if (!isCallable(instance, listener)) throw new MethodNotCallableError(listener, name)\n await (instance as unknown as Record<string, (params: unknown) => unknown>)[listener]!(isRecord(detail) ? detail : {})\n }\n return undefined\n }\n }\n if (!isCallable(instance, method)) throw new MethodNotCallableError(method, name)\n return (instance as unknown as Record<string, (...args: unknown[]) => unknown>)[method]!(...params)\n }\n\n /**\n * Renders the component (rendering/rendered hooks, nested children tracked) and checks for a single root. A\n * WithPagination component's page and page URL are what paginate() reads while it renders, as in its mount() and in\n * its update's hooks and actions.\n */\n private async render(instance: Component, memo: Memo, previous: Children): Promise<{ html: string; tag: string }> {\n await hook(instance, 'rendering')\n const context: RenderContext = { previous, children: {}, index: 0 }\n const html = await renderContext.run(context, () =>\n renderPaginated(instance, this.pageUrl(memo.path), async () => {\n const output = await instance.render()\n return typeof output === 'string' ? output : this.container().make(ViewFactory).renderToString(output)\n }),\n )\n await hook(instance, 'rendered', html)\n memo.children = context.children\n return { html: html.trim(), tag: rootTag(html, memo.name) }\n }\n\n /** The absolute URL of the page a memo path belongs to, on the current request's origin ('/' + path without one). */\n private pageUrl(path: string): string {\n const relative = `/${path.replace(/^\\/+/, '')}`\n const url = optional(this.container(), HttpRequest)?.url()\n try {\n return url === undefined ? relative : new URL(relative, url).href\n } catch {\n return relative\n }\n }\n\n /** Dispatches, redirects: the effects every response carries. */\n private effects(instance: Component): LiveEffects {\n const state = stateOf(instance)\n const effects: LiveEffects = {}\n if (state.dispatches.length > 0) {\n effects.dispatches = state.dispatches.map(({ name, params, self, to }) => ({\n name,\n params,\n ...(self ? { self } : {}),\n ...(to === undefined ? {} : { to: typeof to === 'string' ? to : this.nameOf(to) }),\n }))\n }\n if (state.redirect !== undefined) effects.redirect = state.redirect\n if (state.redirectUsingNavigate) effects.redirectUsingNavigate = true\n return effects\n }\n\n /** dehydrate() hook, then the state as snapshot data, the error bag, and the checksum over both. */\n private async snapshot(instance: Component, memo: Memo): Promise<LiveSnapshot> {\n await hook(instance, 'dehydrate')\n const registry = this.registry()\n const data: Record<string, unknown> = {}\n for (const [property, value] of Object.entries(instance)) data[property] = dehydrate(value, registry, `${memo.name}.${property}`)\n const signed = { data, memo: { ...memo, errors: { ...stateOf(instance).errors } } }\n return { ...signed, checksum: checksum(this.key(), signed) }\n }\n}\n","import { createHmac, timingSafeEqual } from 'node:crypto'\n\n/** JSON with object keys sorted at every level, so the browser's key order can't change the checksum. */\nexport function canonicalJson(value: unknown): string {\n if (Array.isArray(value)) return `[${value.map((item) => canonicalJson(item === undefined ? null : item)).join(',')}]`\n if (typeof value === 'object' && value !== null) {\n const entries = Object.keys(value)\n .sort()\n .filter((key) => (value as Record<string, unknown>)[key] !== undefined)\n .map((key) => `${JSON.stringify(key)}:${canonicalJson((value as Record<string, unknown>)[key])}`)\n return `{${entries.join(',')}}`\n }\n return JSON.stringify(value)\n}\n\n/** HMAC-SHA256 (hex) of the snapshot's data and memo, keyed by APP_KEY. */\nexport function checksum(key: Uint8Array, payload: { data: unknown; memo: unknown }): string {\n return createHmac('sha256', key).update(canonicalJson({ data: payload.data, memo: payload.memo })).digest('hex')\n}\n\n/** Constant-time comparison of a snapshot's checksum with the expected one. */\nexport function verifyChecksum(key: Uint8Array, payload: { data: unknown; memo: unknown }, given: unknown): boolean {\n if (typeof given !== 'string') return false\n const expected = Buffer.from(checksum(key, payload), 'utf8')\n const actual = Buffer.from(given, 'utf8')\n return expected.length === actual.length && timingSafeEqual(expected, actual)\n}\n","import { existsSync, readdirSync } from 'node:fs'\nimport { join, relative, sep } from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport { Str } from '@orieljs/support'\n\n/** A component's Livewire name from its path under app/Live: Posts/CreatePost.tsx → posts.create-post. */\nexport function componentName(file: string): string {\n return file\n .replace(/\\.(tsx|ts|jsx|js|mts|mjs)$/, '')\n .split(/[\\\\/]/)\n .map((segment) => Str.kebab(segment))\n .join('.')\n}\n\n/** A class's default name when it is mounted without being registered: CreatePost → create-post. */\nexport function defaultName(cls: object): string | undefined {\n const name = (cls as { name?: unknown }).name\n return typeof name === 'string' && name !== '' ? Str.kebab(name) : undefined\n}\n\n/** Component files under `directory` (recursive), relative paths with `/`. Test and declaration files are skipped. */\nexport function componentFiles(directory: string): string[] {\n if (!existsSync(directory)) return []\n return readdirSync(directory, { recursive: true, encoding: 'utf8' })\n .filter((file) => /\\.(tsx|ts|jsx|js|mts|mjs)$/.test(file) && !/\\.(test|spec|d)\\.[^.]+$/.test(file))\n .map((file) => file.split(sep).join('/'))\n .sort()\n}\n\n/** Imports every component file under `directory` and returns [name, default export] pairs. */\nexport async function discover(directory: string): Promise<Array<[name: string, exported: unknown]>> {\n const found: Array<[string, unknown]> = []\n for (const file of componentFiles(directory)) {\n const module = (await import(/* @vite-ignore */ pathToFileURL(join(directory, file)).href)) as { default?: unknown }\n found.push([componentName(relative(directory, join(directory, file))), module.default])\n }\n return found\n}\n","import { CurrentRoute, type Container, type HttpRequest, type Middleware, type MiddlewareClass, type MiddlewareReference, type Next, type Route, type Router } from '@orieljs/contracts'\nimport { LiveError } from './errors'\n\n/** The route middleware an update re-applies by default (config live.persistent_middleware), by alias. */\nexport const PERSISTENT_MIDDLEWARE = ['auth', 'verified', 'guest', 'can']\n\n/** A route middleware after alias and group expansion: 'auth:web' → { cls: Authenticate, parameters: ['web'] }. */\nexport interface PersistentMiddleware {\n readonly cls: MiddlewareClass\n readonly parameters: readonly string[]\n}\n\ntype Values = Record<string, string | undefined>\n\n/**\n * What persistent middleware reads from Oriel's router beyond the Router contract: the public matching, middleware\n * and binding methods of @orieljs/routing's BaseRouter and RouteDefinition.\n */\ninterface MatchingRoute extends Route {\n readonly isFallback?: boolean\n match(path: string, patterns: Readonly<Record<string, string>>, version: number): Values | undefined\n gatherMiddleware(): MiddlewareReference[]\n excludedMiddleware(): MiddlewareReference[]\n}\n\ninterface MatchingRouter extends Router {\n getRoutesByMatchOrder(): readonly MatchingRoute[]\n getPatterns(): Readonly<Record<string, string>>\n getPatternVersion(): number\n getMiddleware(): Readonly<Record<string, MiddlewareClass>>\n getMiddlewareGroups(): Record<string, MiddlewareReference[]>\n substituteBindings(route: MatchingRoute, values: Readonly<Values>, container: Container): Promise<Record<string, unknown>>\n}\n\nconst ROUTER_METHODS = ['getRoutesByMatchOrder', 'getPatterns', 'getPatternVersion', 'getMiddleware', 'getMiddlewareGroups', 'substituteBindings']\n\nfunction canMatch(router: Router): router is MatchingRouter {\n const methods = router as unknown as Record<string, unknown>\n return ROUTER_METHODS.every((name) => typeof methods[name] === 'function')\n}\n\nfunction isMatchingRoute(route: unknown): route is MatchingRoute {\n const candidate = route as Record<string, unknown> | null\n return (\n typeof candidate === 'object' &&\n candidate !== null &&\n Array.isArray(candidate.methods) &&\n ['match', 'gatherMiddleware', 'excludedMiddleware'].every((name) => typeof candidate[name] === 'function')\n )\n}\n\n/** request.path() ('posts/1', '/') in the form routes match against ('/posts/1', ''). */\nfunction routePath(path: string): string {\n const trimmed = path.replace(/^\\/+|\\/+$/g, '').replace(/\\/{2,}/g, '/')\n return trimmed === '' ? '' : `/${trimmed}`\n}\n\n/** Expands aliases and groups like the router does; unknown names are skipped (the page request would have failed). */\nfunction expand(\n references: readonly MiddlewareReference[],\n aliases: Readonly<Record<string, MiddlewareClass>>,\n groups: Readonly<Record<string, readonly MiddlewareReference[]>>,\n out: PersistentMiddleware[] = [],\n visiting = new Set<string>(),\n): PersistentMiddleware[] {\n for (const reference of references) {\n if (typeof reference === 'function') {\n out.push({ cls: reference, parameters: [] })\n continue\n }\n const index = reference.indexOf(':')\n const name = index === -1 ? reference : reference.slice(0, index)\n if (index === -1 && Object.hasOwn(groups, name)) {\n if (visiting.has(name)) continue\n visiting.add(name)\n expand(groups[name]!, aliases, groups, out, visiting)\n visiting.delete(name)\n } else if (Object.hasOwn(aliases, name)) {\n out.push({ cls: aliases[name]!, parameters: index === -1 ? [] : reference.slice(index + 1).split(',') })\n }\n }\n return out\n}\n\n/**\n * The page route of an update, as Live re-checks it: the matched route and its raw parameter values, its persistent\n * middleware in the order Routing runs them, and `at`, where the route's parameters are bound (after the `auth` and\n * `guest` middleware and the `web`/`api` group's, before `verified`, `can` and the rest).\n */\nexport interface PersistentPass {\n readonly router: MatchingRouter\n readonly route: MatchingRoute\n readonly values: Readonly<Values>\n readonly middleware: readonly PersistentMiddleware[]\n readonly at: number\n}\n\n/**\n * Matches the page route again (the component's memo method and path) and picks the middleware among `persistent`\n * (aliases) that it ran. Undefined when no route matches: that path runs no persistent middleware (Livewire's rule).\n */\nexport function persistentPass(router: Router, persistent: readonly string[], method: string, path: string): PersistentPass | undefined {\n if (!canMatch(router)) throw new LiveError(\"Live re-applies the page route's middleware to updates, which needs Oriel's router.\")\n const routes = router.getRoutesByMatchOrder()\n if (!Array.isArray(routes) || !routes.every(isMatchingRoute)) throw new LiveError(\"Live re-applies the page route's middleware to updates, which needs Oriel's routes.\")\n const verb = method.toUpperCase()\n const target = routePath(path)\n const patterns = router.getPatterns()\n const version = router.getPatternVersion()\n let matched: { route: MatchingRoute; values: Values } | undefined\n for (const candidate of routes) {\n const values = candidate.methods.includes(verb) ? candidate.match(target, patterns, version) : undefined\n if (values !== undefined) {\n matched = { route: candidate, values }\n break\n }\n }\n if (matched === undefined) return undefined\n const { route, values } = matched\n const aliases = router.getMiddleware()\n const groups = router.getMiddlewareGroups()\n const wanted = new Set(persistent.flatMap((name) => (Object.hasOwn(aliases, name) ? [aliases[name]!] : [])))\n const excluded = new Set(expand(route.excludedMiddleware(), aliases, groups).map((entry) => entry.cls))\n const ids = new Map<MiddlewareClass, number>()\n const seen = new Set<string>()\n const middleware = expand(route.gatherMiddleware(), aliases, groups).filter((entry) => {\n if (!ids.has(entry.cls)) ids.set(entry.cls, ids.size)\n const key = `${ids.get(entry.cls)}:${entry.parameters.join(',')}`\n if (!wanted.has(entry.cls) || excluded.has(entry.cls) || seen.has(key)) return false\n seen.add(key)\n return true\n })\n // Routing's order around binding (orderForBindings): auth, guest and the web/api group's middleware first.\n const early = new Set<MiddlewareClass>(expand(['web', 'api'], aliases, groups).map((entry) => entry.cls))\n for (const name of ['auth', 'guest']) if (Object.hasOwn(aliases, name)) early.add(aliases[name]!)\n const before = middleware.filter((entry) => early.has(entry.cls))\n const after = middleware.filter((entry) => !early.has(entry.cls))\n return { router, route, values, middleware: [...before, ...after], at: before.length }\n}\n\n/**\n * Livewire's persistent middleware: the middleware among `persistent` (aliases) that the page route (the component's\n * memo path and method) ran, in the order an update runs them. A path no route matches has none.\n */\nexport function persistentMiddleware(router: Router, persistent: readonly string[], method: string, path: string): PersistentMiddleware[] {\n return [...(persistentPass(router, persistent, method, path)?.middleware ?? [])]\n}\n\n/** The current route of `container`, or undefined. */\nfunction currentRoute(container: Container): CurrentRoute | undefined {\n if (!container.bound(CurrentRoute)) return undefined\n try {\n return container.make(CurrentRoute)\n } catch {\n return undefined\n }\n}\n\n/**\n * Runs `destination` behind the pass's middleware, built from `container` (the request scope), with the page route\n * bound between them as Routing binds it. While they run, the scope's CurrentRoute is the page route with its\n * parameters (raw, then bound), so `request.route('post')` gives `can:update,post` the model. The update's own\n * CurrentRoute is back before `destination` runs, and after a middleware throws. A middleware may answer instead (a\n * redirect) or throw (401, 403, a missing model's 404): then the update never runs. Like Livewire's pipeline, the\n * `next` the middleware sees resolves to an empty Response; the update's own result is kept aside.\n */\nexport async function throughMiddleware<T>(container: Container, request: HttpRequest, pass: PersistentPass, destination: () => Promise<T>): Promise<T | Response> {\n const original = currentRoute(container)\n const page: CurrentRoute = { route: pass.route, parameters: { ...pass.values }, middleware: [] }\n let swapped = false\n const show = () => {\n container.instance(CurrentRoute, page)\n swapped = true\n }\n const restore = () => {\n if (!swapped) return\n if (original === undefined) container.forgetInstance(CurrentRoute)\n else container.instance(CurrentRoute, original)\n swapped = false\n }\n let ran: { result: T } | undefined\n const run = async (index: number): Promise<Response> => {\n if (index === pass.at) Object.assign(page.parameters, await pass.router.substituteBindings(pass.route, pass.values, container))\n if (index === pass.middleware.length) {\n restore()\n ran = { result: await destination() }\n return new Response(null, { status: 204 })\n }\n const { cls, parameters } = pass.middleware[index]!\n const instance: Middleware = container.make(cls)\n const next: Next = () => run(index + 1)\n return instance.handle(request, next, ...parameters)\n }\n show()\n try {\n const response = await run(0)\n return ran ? ran.result : response\n } finally {\n restore()\n }\n}\n","import { Collection } from '@orieljs/collections'\nimport { Component } from './Component'\nimport { computedOf, lockedOf } from './metadata'\nimport { isModel } from './synthesizers'\n\n/** Lifecycle hooks and the render method: never actions (Livewire's protected method list). */\nconst HOOKS = new Set(['constructor', 'render', 'mount', 'boot', 'booted', 'hydrate', 'dehydrate', 'updating', 'updated', 'rendering', 'rendered', 'exception'])\nconst HOOK_PREFIX = /^(updating|updated|hydrate|dehydrate)[A-Z_]/\n/** Path segments that could reach a prototype. */\nconst UNSAFE_SEGMENTS = new Set(['__proto__', 'prototype', 'constructor'])\n\n/** Component's own API (dispatch, validate, reset, __invoke, …): computed once from its prototype. */\nconst BASE_API = new Set(Object.getOwnPropertyNames(Component.prototype))\n/** A canonical array index: '0', '12'; not '01', '-1', '1.5' or 'length'. */\nconst INDEX = /^(?:0|[1-9]\\d*)$/\n\n/**\n * Whether the browser may address `segment` of `array`: an existing item or the next one (an append). Anything else\n * would add a named property to the array or leave holes in it (a huge index makes it billions of items long).\n */\nexport function isArraySlot(array: readonly unknown[], segment: string): boolean {\n return INDEX.test(segment) && Number(segment) <= array.length\n}\n\n/**\n * Whether the browser may call `method`: a public method declared on the user's classes below Component, not a hook,\n * not `_private`, not `$magic` (those are handled separately), not a getter and not @Locked.\n */\nexport function isCallable(instance: Component, method: string): boolean {\n if (method === '' || method.startsWith('_') || method.startsWith('$') || method.startsWith('#')) return false\n if (HOOKS.has(method) || HOOK_PREFIX.test(method) || BASE_API.has(method)) return false\n if (lockedOf(instance.constructor).has(method)) return false\n // Stops at Component.prototype, or at Object.prototype for a component built on another copy of Component.\n const isBase = (proto: object) => proto === Component.prototype || proto === Object.prototype\n for (let proto = Object.getPrototypeOf(instance) as object | null; proto !== null && !isBase(proto); proto = Object.getPrototypeOf(proto) as object | null) {\n const descriptor = Object.getOwnPropertyDescriptor(proto, method)\n if (descriptor !== undefined) return typeof descriptor.value === 'function'\n }\n return false\n}\n\n/**\n * Whether the browser may set `path` ('title', 'items.0.name'): the root must be an existing public field that is not\n * `_private`, @Locked or computed; models and collections can't be changed, wherever they sit in the path (nor their\n * attributes); an array is only reached by the index of an existing item or the next one; no prototype keys.\n */\nexport function isUpdatable(instance: Component, path: string): boolean {\n const segments = path.split('.')\n const root = segments[0]!\n if (root === '' || root.startsWith('_') || segments.some((segment) => segment === '' || UNSAFE_SEGMENTS.has(segment))) return false\n if (!Object.hasOwn(instance, root)) return false\n const descriptor = Object.getOwnPropertyDescriptor(instance, root)!\n if (!descriptor.enumerable || descriptor.get !== undefined) return false\n const cls = instance.constructor\n if (lockedOf(cls).has(root) || computedOf(cls).has(root)) return false\n // Walk the existing value along the path: a model or collection anywhere on the way (the root, an array item, an\n // object member, the final value) is read-only, so its attributes can't be set through a dotted path either.\n let node = descriptor.value as unknown\n for (const segment of segments.slice(1)) {\n if (isModel(node) || node instanceof Collection) return false\n if (Array.isArray(node) && !isArraySlot(node, segment)) return false\n if (typeof node !== 'object' || node === null || !Object.hasOwn(node, segment)) return true\n node = (node as Record<string, unknown>)[segment]\n }\n return !isModel(node) && !(node instanceof Collection)\n}\n","import type { Class, ClassRegistry, ModelInstance, ModelStatic } from '@orieljs/contracts'\nimport { Collection } from '@orieljs/collections'\nimport { LiveError } from './errors'\n\n/** A JSON value as it travels in a snapshot. Non-scalars are Livewire-style tuples: [value, { s: '<synth>', … }]. */\nexport type Dehydrated = null | boolean | number | string | [unknown, SynthMeta]\nexport interface SynthMeta {\n s: 'u' | 'arr' | 'obj' | 'dt' | 'mdl' | 'elcln' | 'clctn'\n class?: string\n key?: unknown\n keys?: unknown[]\n}\n\n/** The same structural model check as Queue's serialization: what the ModelInstance contract guarantees. */\nexport function isModel(value: unknown): value is ModelInstance {\n if (typeof value !== 'object' || value === null) return false\n const candidate = value as Record<string, unknown>\n return (\n typeof candidate.getKey === 'function' &&\n typeof candidate.getKeyName === 'function' &&\n typeof candidate.getTable === 'function' &&\n typeof candidate.exists === 'boolean'\n )\n}\n\nconst isPlainObject = (value: object): boolean => {\n const proto: unknown = Object.getPrototypeOf(value)\n return proto === Object.prototype || proto === null\n}\n\nconst isTuple = (value: unknown): value is [unknown, SynthMeta] =>\n Array.isArray(value) &&\n value.length === 2 &&\n typeof value[1] === 'object' &&\n value[1] !== null &&\n !Array.isArray(value[1]) &&\n typeof (value[1] as Partial<SynthMeta>).s === 'string'\n\n/** The registry name of a model class, registering it under its class name the first time (as Queue does). */\nfunction classNameOf(registry: ClassRegistry, cls: Class<unknown>): string {\n return registry.nameOf(cls) ?? registry.register(cls)\n}\n\n/**\n * Encodes one public property value for the snapshot. Only primitives, arrays, plain objects, Dates, saved models and\n * collections are allowed (spec §5.2): anything else throws a LiveError naming the property.\n */\nexport function dehydrate(value: unknown, registry: ClassRegistry, path: string, seen: Set<object> = new Set()): Dehydrated {\n switch (typeof value) {\n case 'undefined':\n return [null, { s: 'u' }]\n case 'string':\n case 'boolean':\n return value\n case 'number':\n if (!Number.isFinite(value)) throw new LiveError(`Property [${path}] is ${value}: Live state must be JSON (finite numbers only).`)\n return value\n case 'bigint':\n case 'symbol':\n case 'function':\n throw new LiveError(`Property [${path}] holds a ${typeof value}: Live state may only hold primitives, arrays, plain objects, Dates, models and collections.`)\n }\n if (value === null) return null\n const object = value as object\n if (seen.has(object)) throw new LiveError(`Property [${path}] contains a circular reference.`)\n seen.add(object)\n try {\n if (object instanceof Date) return [object.toISOString(), { s: 'dt' }]\n if (Array.isArray(object)) return [object.map((item, i) => dehydrate(item, registry, `${path}.${i}`, seen)), { s: 'arr' }]\n if (isModel(object)) {\n const name = classNameOf(registry, object.constructor as Class<unknown>)\n if (!object.exists) throw new LiveError(`Property [${path}] holds an unsaved [${name}] model: only saved models can be kept between requests.`)\n return [null, { s: 'mdl', class: name, key: object.getKey() }]\n }\n if (object instanceof Collection) {\n const items = object.all() as unknown[]\n const first = items[0]\n if (items.length > 0 && isModel(first) && items.every((item) => isModel(item) && item.constructor === first.constructor)) {\n for (const [i, item] of items.entries()) {\n if (!(item as ModelInstance).exists) throw new LiveError(`Property [${path}.${i}] holds an unsaved model.`)\n }\n const name = classNameOf(registry, first.constructor as Class<unknown>)\n return [null, { s: 'elcln', class: name, keys: items.map((item) => (item as ModelInstance).getKey()) }]\n }\n return [items.map((item, i) => dehydrate(item, registry, `${path}.${i}`, seen)), { s: 'clctn' }]\n }\n if (isPlainObject(object)) {\n const out: Record<string, Dehydrated> = {}\n for (const [key, item] of Object.entries(object)) out[key] = dehydrate(item, registry, `${path}.${key}`, seen)\n return [out, { s: 'obj' }]\n }\n const type = (object.constructor as { name?: string } | undefined)?.name || 'object'\n throw new LiveError(\n `Property [${path}] holds a [${type}] instance: Live state may only hold primitives, arrays, plain objects, Dates, models and collections.`,\n )\n } finally {\n seen.delete(object)\n }\n}\n\nfunction modelClass(registry: ClassRegistry, name: unknown): ModelStatic {\n if (typeof name !== 'string' || !registry.has(name)) throw new LiveError(`Unable to hydrate the [${String(name)}] model: it is not registered.`)\n return registry.resolve(name) as unknown as ModelStatic\n}\n\n/** Decodes one snapshot value. Models are re-fetched (a missing row throws the database's ModelNotFound error). */\nexport async function hydrate(value: unknown, registry: ClassRegistry): Promise<unknown> {\n if (!isTuple(value)) return value\n const [inner, meta] = value\n switch (meta.s) {\n case 'u':\n return undefined\n case 'dt':\n return new Date(String(inner))\n case 'arr':\n return Promise.all((inner as unknown[]).map((item) => hydrate(item, registry)))\n case 'clctn':\n return new Collection(await Promise.all((inner as unknown[]).map((item) => hydrate(item, registry))))\n case 'obj': {\n const out: Record<string, unknown> = {}\n for (const [key, item] of Object.entries(inner as Record<string, unknown>)) {\n // JSON.parse makes `__proto__` an own key: define it as data so it can't swap the prototype.\n Object.defineProperty(out, key, { value: await hydrate(item, registry), enumerable: true, writable: true, configurable: true })\n }\n return out\n }\n case 'mdl':\n return modelClass(registry, meta.class).findOrFail(meta.key)\n case 'elcln': {\n const cls = modelClass(registry, meta.class)\n const keys = meta.keys ?? []\n const keyName = new cls().getKeyName()\n const found = [...((await cls.query().whereIn(keyName, keys).get()) as Iterable<ModelInstance>)]\n const byKey = new Map(found.map((model) => [String(model.getKey()), model]))\n return new Collection(keys.map((key) => byKey.get(String(key))).filter((model) => model !== undefined))\n }\n }\n throw new LiveError(`Unknown snapshot value type [${String(meta.s)}].`)\n}\n","import { AsyncLocalStorage } from 'node:async_hooks'\nimport type { PaginationState } from '@orieljs/contracts'\nimport type { Component } from './Component'\n\n/** Marks the prototypes WithPagination() creates (Symbol.for, so two copies of the package agree). */\nconst PAGINATED = Symbol.for('oriel:live.pagination')\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type ComponentConstructor = abstract new (...args: any[]) => Component\n\n/** What WithPagination() adds to a component: its page and the actions that move it. */\nexport interface Paginated {\n /** The current page. The browser may set it; Live reads it as a page number. */\n page: number\n nextPage(): Promise<void>\n previousPage(): Promise<void>\n gotoPage(page: number | string): Promise<void>\n resetPage(): Promise<void>\n setPage(page: number | string): Promise<void>\n}\n\n/** A page number from the browser: a whole number of at least 1 (decimals rounded down), anything else page 1. */\nexport function toPage(value: unknown): number {\n const page = typeof value === 'number' ? value : typeof value === 'string' && value.trim() !== '' ? Number(value) : Number.NaN\n return Number.isFinite(page) && page >= 1 ? Math.min(Math.floor(page), Number.MAX_SAFE_INTEGER) : 1\n}\n\nasync function hook(instance: object, name: string, ...args: unknown[]): Promise<void> {\n const method = (instance as Record<string, unknown>)[name]\n if (typeof method === 'function') await (method as (...values: unknown[]) => unknown).apply(instance, args)\n}\n\n/**\n * Livewire's WithPagination: `class Posts extends WithPagination(Component)`. The public `page` (1 to start; there\n * is no address-bar sync) is what `paginate()` shows in the component (in `render()`, `mount()`, `hydrate()`, the\n * update hooks and actions, or in a `@Computed` getter any of them reads), and its page links are built on the\n * page's URL. The actions move it: `o:click=\"nextPage\"`, `previousPage`, `gotoPage(3)`, `setPage(3)`,\n * `resetPage` (call it from `updatedSearch()` so a new search starts on page 1). `updatingPage(page)` and\n * `updatedPage(page)` run around every change. One paginator per component: other page names read the request.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function WithPagination<TBase extends ComponentConstructor>(Base: TBase): TBase & (abstract new (...args: any[]) => Paginated) {\n abstract class WithPaginationMixin extends Base implements Paginated {\n page = 1\n\n nextPage(): Promise<void> {\n return this.setPage(toPage(this.page) + 1)\n }\n\n previousPage(): Promise<void> {\n return this.setPage(Math.max(toPage(this.page) - 1, 1))\n }\n\n gotoPage(page: number | string): Promise<void> {\n return this.setPage(page)\n }\n\n resetPage(): Promise<void> {\n return this.setPage(1)\n }\n\n async setPage(page: number | string): Promise<void> {\n const next = toPage(page)\n await hook(this, 'updatingPage', next)\n this.page = next\n await hook(this, 'updatedPage', next)\n }\n }\n Object.defineProperty(WithPaginationMixin.prototype, PAGINATED, { value: true })\n return WithPaginationMixin\n}\n\nfunction isPaginated(component: Component): component is Component & { page: unknown } {\n return (component as unknown as Record<symbol, unknown>)[PAGINATED] === true\n}\n\n/** The WithPagination component whose mount(), update or render() is running, and its page's URL; else undefined. */\nconst rendering = new AsyncLocalStorage<{ component: Component & { page: unknown }; url: string } | undefined>()\n\n/**\n * Runs `run` (a component's mount(), its update's hooks and actions, or its render()) with `component` as the one\n * PaginationState answers for: its page and `url` when it uses WithPagination, nothing (so the request decides) when\n * it doesn't. Nested components each run their own.\n */\nexport function renderPaginated<T>(component: Component, url: string, run: () => T): T {\n return rendering.run(isPaginated(component) ? { component, url } : undefined, run)\n}\n\n/** Runs `run` outside any WithPagination component's window, so the request decides (a nested child's mount). */\nexport function outsidePagination<T>(run: () => T): T {\n return rendering.run(undefined, run)\n}\n\n/**\n * The PaginationState Live binds: while a WithPagination component's mount(), update or render() runs, its page\n * (written back as a page number) for the default page name, and its page's URL as the links' path. Otherwise\n * undefined: the request decides.\n */\nexport const livePaginationState: PaginationState = {\n currentPage(pageName) {\n const current = rendering.getStore()\n if (current === undefined || pageName !== 'page') return undefined\n const page = toPage(current.component.page)\n current.component.page = page\n return page\n },\n currentPath() {\n return rendering.getStore()?.url\n },\n}\n","import { ConfigRepository, ConsoleKernel, HttpRequest, LiveManager, PaginationState, Router } from '@orieljs/contracts'\nimport { inject } from '@orieljs/container'\nimport { ServiceProvider } from '@orieljs/support'\nimport { registerLiveCommands } from './commands'\nimport { isComponentClass } from './Component'\nimport { LiveComponentManager } from './LiveComponentManager'\nimport { discover } from './naming'\nimport { PERSISTENT_MIDDLEWARE } from './persistent'\nimport { livePaginationState } from './WithPagination'\n\n/** The URI the client runtime posts updates to. */\nexport const UPDATE_URI = '/oriel/live/update'\n\n/**\n * Binds the LiveManager and the PaginationState that WithPagination components answer, merges the `live` config,\n * registers POST /oriel/live/update (named `live.update`, in the `web` group: sessions and CSRF apply), the make:live\n * command, and the components under app/Live.\n */\nexport class LiveServiceProvider extends ServiceProvider {\n override register(): void {\n // persistent_middleware: the page route's middleware (aliases) every update re-applies, with the route's parameters\n // bound again for can: (Livewire's persistent middleware).\n this.mergeConfigFrom({ class_path: this.app.appPath('Live'), layout: 'components.layouts.app', persistent_middleware: [...PERSISTENT_MIDDLEWARE] }, 'live')\n this.app.singleton(LiveComponentManager, () => new LiveComponentManager(this.app))\n this.app.singleton(LiveManager, (container) => container.make(LiveComponentManager))\n // paginate() in a WithPagination component's mount(), update or render() shows its page (Database asks this first).\n this.app.singleton(PaginationState, () => livePaginationState)\n }\n\n override async boot(): Promise<void> {\n const manager = this.app.make(LiveComponentManager)\n if (this.app.bound(Router)) {\n this.app\n .make(Router)\n .post(UPDATE_URI, () => manager.handle(inject(HttpRequest)))\n .middleware('web')\n .name('live.update')\n }\n if (this.app.bound(ConsoleKernel)) registerLiveCommands(this.app.make(ConsoleKernel), this.app)\n const directory = this.app.make(ConfigRepository).get<string>('live.class_path', this.app.appPath('Live'))\n for (const [name, exported] of await this.app.run(() => discover(directory))) {\n if (isComponentClass(exported)) manager.register(exported, name)\n }\n }\n}\n","import { existsSync } from 'node:fs'\nimport { mkdir, writeFile } from 'node:fs/promises'\nimport { dirname, join, relative, sep } from 'node:path'\nimport { ConfigRepository, type Application, type CommandContext, type ConsoleKernel } from '@orieljs/contracts'\nimport { Str } from '@orieljs/support'\n\n/** app/Live/<Path>.tsx, written by make:live. */\nexport const COMPONENT_STUB = `import { Component } from '@orieljs/framework'\n\nexport default class {{ class }} extends Component {\n render() {\n return <div></div>\n }\n}\n`\n\n/** tests/Feature/Live/<Path>.test.ts, written by make:live --test. */\nexport const TEST_STUB = `import { Live } from '@orieljs/framework'\nimport { expect, test } from 'vitest'\nimport {{ class }} from '{{ component }}'\nimport { TestCase } from '{{ testCase }}'\n\nTestCase.boot()\n\ntest('{{ name }} renders', async () => {\n const component = await Live.test({{ class }})\n expect(component.html()).toContain('<div')\n})\n`\n\nconst CLASS_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/\n\n/** An import specifier from `from` (a file) to `to` (a file, extension dropped), always relative (./ or ../). */\nfunction importPath(from: string, to: string): string {\n const path = relative(dirname(from), to).split(sep).join('/').replace(/\\.tsx?$/, '')\n return path.startsWith('.') ? path : `./${path}`\n}\n\n/** make:live Posts/CreatePost [--test] [--force] (Livewire's make:livewire). */\nexport function registerLiveCommands(kernel: ConsoleKernel, app: Application): void {\n kernel\n .command('make:live {name : The component name, e.g. Posts/CreatePost} {--test : Also create a test} {--force : Overwrite existing files}', async function (this: CommandContext) {\n const segments = String(this.argument('name') ?? '')\n .split(/[/\\\\.]+/)\n .filter((segment) => segment !== '')\n .map((segment) => Str.studly(segment))\n if (segments.length === 0 || !segments.every((segment) => CLASS_NAME.test(segment))) {\n this.error(`Component name [${String(this.argument('name'))}] is not valid: use names like Posts/CreatePost.`)\n return 1\n }\n const className = segments.at(-1)!\n const config = app.bound(ConfigRepository) ? app.make(ConfigRepository) : undefined\n const directory = config?.get<string>('live.class_path') ?? app.appPath('Live')\n const file = join(directory, ...segments.slice(0, -1), `${className}.tsx`)\n const force = this.option('force') === true\n if (existsSync(file) && !force) {\n this.error(`Component [${relative(app.basePath(), file)}] already exists.`)\n return 1\n }\n await mkdir(dirname(file), { recursive: true })\n await writeFile(file, COMPONENT_STUB.replace('{{ class }}', () => className))\n this.info(`Component [${relative(app.basePath(), file)}] created successfully.`)\n\n if (this.option('test') === true) {\n const testFile = app.basePath(join('tests', 'Feature', 'Live', ...segments.slice(0, -1), `${className}.test.ts`))\n if (existsSync(testFile) && !force) {\n this.error(`Test [${relative(app.basePath(), testFile)}] already exists.`)\n return 1\n }\n const name = segments.map((segment) => Str.kebab(segment)).join('.')\n const test = TEST_STUB.replaceAll('{{ class }}', () => className)\n .replace('{{ component }}', () => importPath(testFile, file))\n .replace('{{ testCase }}', () => importPath(testFile, app.basePath(join('tests', 'TestCase.ts'))))\n .replace('{{ name }}', () => name)\n await mkdir(dirname(testFile), { recursive: true })\n await writeFile(testFile, test)\n this.info(`Test [${relative(app.basePath(), testFile)}] created successfully.`)\n }\n return 0\n })\n .purpose('Create a new Live component')\n}\n","import type { Htmlable } from '@orieljs/contracts'\nimport { LiveError } from './errors'\nimport { escapeAttribute } from './html'\n\n/**\n * What <Pagination> reads from a paginator. Structural, since Live can't import Database: paginate()'s\n * LengthAwarePaginator (with lastPage(), so page buttons) and simplePaginate()'s Paginator (Previous and Next only).\n */\nexport interface PaginationSource {\n currentPage(): number\n lastPage?(): number\n hasMorePages(): boolean\n onFirstPage(): boolean\n /** Page buttons on each side of the current one (the paginator's onEachSide(), 3 by default). */\n readonly onEachSideCount?: number\n /** Not cursorPaginate(): its pages are cursors, which a component's page number can't follow. */\n readonly nextCursor?: never\n}\n\nexport interface PaginationProps {\n paginator: PaginationSource\n /** Classes for the <nav>, such as its layout (\"flex gap-2\"); in your file, so Tailwind generates them. */\n class?: string\n}\n\ntype WindowItem = number | '...'\n\n/** Laravel's UrlWindow: the first pages, the slider around the current page and the last pages, with gaps. */\nfunction urlWindow(current: number, last: number, onEachSide: number): WindowItem[] {\n const range = (from: number, to: number) => Array.from({ length: Math.max(to - from + 1, 0) }, (_, index) => from + index)\n if (last < onEachSide * 2 + 8) return range(1, last)\n const size = onEachSide + 4\n if (current <= size) return [...range(1, size + onEachSide), '...', ...range(last - 1, last)]\n if (current > last - size) return [...range(1, 2), '...', ...range(last - (size + (onEachSide - 1)), last)]\n return [...range(1, 2), '...', ...range(current - onEachSide, current + onEachSide), '...', ...range(last - 1, last)]\n}\n\nfunction button(label: string, action: string | undefined, attributes = ''): string {\n const live = action === undefined ? ' disabled' : ` o:click=\"${escapeAttribute(action)}\"`\n return `<button type=\"button\" class=\"btn btn-secondary\"${attributes}${live}>${escapeAttribute(label)}</button>`\n}\n\n/**\n * Livewire's pagination links for a WithPagination component: `<Pagination paginator={posts} />` in render(). A\n * <nav aria-label=\"Pagination\"> with « Previous, the page buttons and Next » as Live actions (previousPage,\n * gotoPage(n), nextPage), the current page marked aria-current=\"page\", the ends disabled, the kits' theme classes\n * (btn, btn-secondary). Nothing when everything fits on one page. The address bar is left alone.\n */\nexport function Pagination({ paginator, class: className }: PaginationProps): Htmlable {\n if (typeof (paginator as { nextCursor?: unknown }).nextCursor === 'function') {\n throw new LiveError('<Pagination> needs paginate() or simplePaginate(): a cursor paginator has no page numbers.')\n }\n const current = paginator.currentPage()\n const onFirst = paginator.onFirstPage()\n const hasMore = paginator.hasMorePages()\n if (onFirst && !hasMore) return { toHtml: () => '' }\n const parts = [button('« Previous', onFirst ? undefined : 'previousPage')]\n if (typeof paginator.lastPage === 'function') {\n const onEachSide = Number.isInteger(paginator.onEachSideCount) && paginator.onEachSideCount! >= 0 ? paginator.onEachSideCount! : 3\n for (const page of urlWindow(current, paginator.lastPage(), onEachSide)) {\n if (page === '...') parts.push('<span aria-hidden=\"true\">...</span>')\n else if (page === current) parts.push(`<button type=\"button\" class=\"btn\" aria-current=\"page\" disabled>${page}</button>`)\n else parts.push(button(String(page), `gotoPage(${page})`, ` aria-label=\"Go to page ${page}\"`))\n }\n }\n parts.push(button('Next »', hasMore ? 'nextPage' : undefined))\n const classes = className === undefined || className === '' ? '' : ` class=\"${escapeAttribute(className)}\"`\n const html = `<nav aria-label=\"Pagination\"${classes}>${parts.join('')}</nav>`\n return { toHtml: () => html }\n}\n"],"mappings":";AAAA,SAAS,aAAa,cAAc,yBAAkE;AACtG,SAAS,cAAc;;;ACMrB,OAAiC,aAAa,uBAAO,IAAI,iBAAiB;AAE5E,IAAM,YAAY,uBAAO,IAAI,sBAAsB;AACnD,IAAM,SAAS,uBAAO,IAAI,mBAAmB;AAC7C,IAAM,WAAW,uBAAO,IAAI,qBAAqB;AAQjD,SAAS,IAAO,UAAoB,KAAa,OAAgB,MAA8B;AAC7F,MAAI,CAAC,OAAO,OAAO,UAAU,GAAG,EAAG,UAAS,GAAG,IAAI,SAAS,GAAG,MAAM,SAAY,MAAM,IAAI,KAAK,SAAS,GAAG,CAAM;AAClH,SAAO,SAAS,GAAG;AACrB;AAGO,SAAS,GAAG,OAAe;AAChC,SAAO,SAAU,SAAkB,SAA4C;AAC7E,UAAM,YAAY;AAAA,MAA8B,QAAQ;AAAA,MAAsB;AAAA,MAAW,OAAO,CAAC;AAAA,MAAI,CAAC,cACpG,OAAO,YAAY,OAAO,QAAQ,SAAS,EAAE,IAAI,CAAC,CAAC,MAAMA,QAAO,MAAM,CAAC,MAAM,CAAC,GAAGA,QAAO,CAAC,CAAC,CAAC;AAAA,IAC7F;AAEA,UAAM,UAAW,UAAU,KAAK,MAAM,CAAC;AACv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AACtC,QAAM,UAAU,UAAU,aAAa;AACvC,MAAI,WAAW,CAAC,QAAS,QAAO,EAAE,QAAQ,MAAM,GAAG;AACnD,QAAM,QAAQ,CAAC,OAAO,iBAAc,UAAU,SAAY,cAAc,CAAC;AACzE,MAAI,OAAO,UAAU,aAAa,YAAY;AAC5C,UAAM,aAAa,OAAO,UAAU,UAAU,eAAe,KAAK,UAAU,mBAAoB,IAAI,UAAU,kBAAmB;AACjI,eAAW,QAAQ,UAAU,SAAS,UAAU,SAAS,GAAG,UAAU,GAAG;AACvE,UAAI,SAAS,MAAO,OAAM,KAAK,qCAAqC;AAAA,eAC3D,SAAS,QAAS,OAAM,KAAK,kEAAkE,IAAI,WAAW;AAAA,UAClH,OAAM,KAAK,OAAO,OAAO,IAAI,GAAG,YAAY,IAAI,KAAK,2BAA2B,IAAI,GAAG,CAAC;AAAA,IAC/F;AAAA,EACF;AACA,QAAM,KAAK,OAAO,aAAU,UAAU,aAAa,MAAS,CAAC;AAC7D,QAAM,UAAU,cAAc,UAAa,cAAc,KAAK,KAAK,WAAW,gBAAgB,SAAS,CAAC;AACxG,QAAM,OAAO,+BAA+B,OAAO,IAAI,MAAM,KAAK,EAAE,CAAC;AACrE,SAAO,EAAE,QAAQ,MAAM,KAAK;AAC9B;","names":["methods","LiveManager","inject","LiveManager","inject","fail","token","inject","LiveManager","inject","LiveManager","AsyncLocalStorage","CurrentRoute","Session","currentContainer","Str","values","Collection","Collection","AsyncLocalStorage","token","hook","currentContainer","Session","CurrentRoute","Str","node","relative","ConfigRepository","HttpRequest","LiveManager","Router","inject","existsSync","join","relative","sep","ConfigRepository","Str","LiveManager","Router","inject","HttpRequest","ConfigRepository","live"]}
|