@orieljs/live 0.1.0-alpha.7 → 0.1.0-alpha.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -292,6 +292,17 @@ declare class LiveServiceProvider extends ServiceProvider {
292
292
 
293
293
  /** A component's Livewire name from its path under app/Live: Posts/CreatePost.tsx → posts.create-post. */
294
294
  declare function componentName(file: string): string;
295
+ /** Component files under `directory` (recursive), relative paths with `/`. Test and declaration files are skipped. */
296
+ declare function componentFiles(directory: string): string[];
297
+
298
+ /**
299
+ * What the browser may do with a component class, for editors (`oriel ide:info`): the actions it may call and the
300
+ * properties it may set, each sorted. The instance is built as mounting builds one, and none of its hooks run.
301
+ */
302
+ declare function describeComponent(cls: new () => Component): {
303
+ actions: string[];
304
+ properties: string[];
305
+ };
295
306
 
296
307
  /** A Live programming error (unsupported state, a missing root element, an unknown component): a 500. */
297
308
  declare class LiveError extends Error implements OrielError {
@@ -505,4 +516,4 @@ interface PaginationProps {
505
516
  */
506
517
  declare function Pagination({ paginator, class: className }: PaginationProps): Htmlable;
507
518
 
508
- export { Component, type ComponentResult, Computed, CorruptComponentPayloadError, ErrorBag, FileNotPreviewableError, InvalidLiveRequestError, InvalidUploadSignatureError, Live, LiveComponentManager, LiveComponentNotFoundError, LiveError, type LiveProps, LiveServiceProvider, Locked, MethodNotCallableError, On, PERSISTENT_MIDDLEWARE, PREVIEW_URI, type Paginated, Pagination, type PaginationProps, type PaginationSource, PendingEvent, type PersistentMiddleware, PropertyNotUpdatableError, TEMPORARY_UPLOAD_DEFAULTS, type TemporaryFileData, TemporaryFileNotFoundError, TemporaryUploadedFile, TestRequestScope, Testable, UPDATE_URI, UPLOAD_URI, UploadValidationError, WithFileUploads, WithPagination, componentName, live, persistentMiddleware };
519
+ export { Component, type ComponentResult, Computed, CorruptComponentPayloadError, ErrorBag, FileNotPreviewableError, InvalidLiveRequestError, InvalidUploadSignatureError, Live, LiveComponentManager, LiveComponentNotFoundError, LiveError, type LiveProps, LiveServiceProvider, Locked, MethodNotCallableError, On, PERSISTENT_MIDDLEWARE, PREVIEW_URI, type Paginated, Pagination, type PaginationProps, type PaginationSource, PendingEvent, type PersistentMiddleware, PropertyNotUpdatableError, TEMPORARY_UPLOAD_DEFAULTS, type TemporaryFileData, TemporaryFileNotFoundError, TemporaryUploadedFile, TestRequestScope, Testable, UPDATE_URI, UPLOAD_URI, UploadValidationError, WithFileUploads, WithPagination, componentFiles, componentName, describeComponent, live, persistentMiddleware };
package/dist/index.js CHANGED
@@ -1900,6 +1900,22 @@ var LiveServiceProvider = class extends ServiceProvider {
1900
1900
  }
1901
1901
  };
1902
1902
 
1903
+ // describe.ts
1904
+ import { currentContainer as currentContainer4 } from "@orieljs/container";
1905
+ function describeComponent(cls) {
1906
+ const container2 = currentContainer4();
1907
+ const instance = container2 ? container2.make(cls) : new cls();
1908
+ const methods = /* @__PURE__ */ new Set();
1909
+ const isBase = (proto) => proto === Component.prototype || proto === Object.prototype;
1910
+ for (let proto = Object.getPrototypeOf(instance); proto !== null && !isBase(proto); proto = Object.getPrototypeOf(proto)) {
1911
+ for (const name of Object.getOwnPropertyNames(proto)) methods.add(name);
1912
+ }
1913
+ return {
1914
+ actions: [...methods].filter((name) => isCallable(instance, name)).sort(),
1915
+ properties: Object.keys(instance).filter((name) => isUpdatable(instance, name)).sort()
1916
+ };
1917
+ }
1918
+
1903
1919
  // Pagination.ts
1904
1920
  function urlWindow(current, last, onEachSide) {
1905
1921
  const range = (from, to) => Array.from({ length: Math.max(to - from + 1, 0) }, (_, index) => from + index);
@@ -1966,7 +1982,9 @@ export {
1966
1982
  UploadValidationError,
1967
1983
  WithFileUploads,
1968
1984
  WithPagination,
1985
+ componentFiles,
1969
1986
  componentName,
1987
+ describeComponent,
1970
1988
  live,
1971
1989
  persistentMiddleware
1972
1990
  };
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../Component.ts","../errors.ts","../metadata.ts","../security.ts","../synthesizers.ts","../TemporaryUploadedFile.ts","../embed.ts","../Testable.ts","../flash.ts","../html.ts","../uploads.ts","../checksum.ts","../WithFileUploads.ts","../LiveComponentManager.ts","../lazy.ts","../naming.ts","../persistent.ts","../WithPagination.ts","../LiveServiceProvider.ts","../commands.ts","../Pagination.ts"],"sourcesContent":["import {\n LiveManager,\n UrlGenerator,\n ValidationFactory,\n type Class,\n type InferValidatedType,\n type MessageBag,\n type RouteArguments,\n type RouteName,\n type Rules,\n} from '@orieljs/contracts'\nimport { inject } from '@orieljs/container'\nimport { LiveError } from './errors'\nimport { forgetComputed } from './metadata'\nimport { isCallable } from './security'\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 /** The field's own messages: a field named `constructor` or `toString` doesn't reach Object's. */\n #own(key: string): string[] | undefined {\n return Object.hasOwn(this.messages, key) ? this.messages[key] : undefined\n }\n\n /** Adds to the component's errors, as addError() does. */\n add(key: string, message: string): void {\n const messages = this.#own(key)\n if (messages !== undefined) messages.push(message)\n else Object.defineProperty(this.messages, key, { value: [message], enumerable: true, writable: true, configurable: true })\n }\n\n has(key: string): boolean {\n return (this.#own(key)?.length ?? 0) > 0\n }\n\n first(key?: string): string | undefined {\n return key === undefined ? this.all()[0] : this.#own(key)?.[0]\n }\n\n get(key: string): string[] {\n return [...(this.#own(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 /**\n * Livewire's #[Lazy]: every embed (and the full page) renders the placeholder first and mounts once the browser shows\n * it. `<Live component={…} lazy={false} />` mounts one at once. The placeholder is the component's\n * `placeholder(params)` method (TSX), else the `live.lazy_placeholder` view, else an empty `<div>`: give it the root\n * element the component renders.\n */\n static lazy?: boolean\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 /**\n * redirect() to a named route: `this.redirectRoute('posts.show', post, { navigate: true })`. Once `oriel\n * route:types` has run, the name and the route's parameters are checked, as route()'s are.\n */\n redirectRoute<N extends RouteName>(name: N, ...args: RouteArguments<N, [options?: { navigate?: boolean }]>): void {\n const [parameters, options = {}] = args as [parameters?: unknown, options?: { navigate?: boolean }]\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, typed from the rules\n * (`await this.validate({ title: 'required|string' })` is `{ title: string }`); on failure fills the error bag and\n * throws (the rest of the action is skipped and the component re-renders with `errors`).\n */\n async validate<const R extends Rules>(rules: R, messages?: Record<string, string>, attributes?: Record<string, string>): Promise<InferValidatedType<R>> {\n const validator = inject(ValidationFactory).make(Object.fromEntries(Object.entries(this)), rules, messages, attributes)\n try {\n const data = await validator.validated<InferValidatedType<R>>()\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 this.errors.add(key, 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 /**\n * An action for an `o:` directive, typed against its method: `o:click={this.$action(this.delete, tag.id)}` writes\n * `delete(5)`, and a string where `delete` takes a number is a type error. The arguments are written as JSON, the\n * trailing `undefined` ones left out so the method's defaults apply. The method must be one of this component's\n * actions (a public method of its class, not a hook and not @Locked); anything else throws while rendering.\n */\n $action<P extends unknown[]>(method: (...params: P) => unknown, ...params: NoInfer<P>): string {\n const name = typeof method === 'function' ? method.name : ''\n if (name === '' || (this as unknown as Record<string, unknown>)[name] !== method || !isCallable(this, name)) {\n throw new LiveError(\n `[${name === '' ? 'anonymous function' : name}] is not an action of [${this.getName() || this.constructor.name}]: pass one of its public methods, as in this.$action(this.save).`,\n )\n }\n let count = params.length\n while (count > 0 && params[count - 1] === undefined) count--\n return count === 0 ? name : `${name}(${params.slice(0, count).map((param) => JSON.stringify(param) ?? 'null').join(', ')})`\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","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\n/** An upload or preview URL whose signature is missing, wrong or expired (Livewire's 401). Nothing is read or stored. */\nexport class InvalidUploadSignatureError extends LiveError {\n override readonly name: string = 'InvalidUploadSignatureError'\n override readonly kind: ErrorKind = 'Http'\n override readonly status: number = 401\n\n constructor() {\n super('')\n }\n}\n\n/** A preview of a temporary upload that is no longer on the disk (cleaned up, or stored and deleted). */\nexport class TemporaryFileNotFoundError extends LiveError {\n override readonly name: string = 'TemporaryFileNotFoundError'\n override readonly kind: ErrorKind = 'Http'\n override readonly status: number = 404\n\n constructor(filename: string) {\n super(`Unable to find the temporary upload [${filename}].`)\n }\n}\n\n/** temporaryUrl() on an upload whose type has no preview (live.temporary_file_upload.preview_mimes). */\nexport class FileNotPreviewableError extends LiveError {\n override readonly name: string = 'FileNotPreviewableError'\n\n constructor(extension: string) {\n super(`File with extension \"${extension}\" is not previewable. See the live.temporary_file_upload.preview_mimes config.`)\n }\n}\n\n/** The errors an upload came back with (`_uploadErrored`): the component re-renders with them on the property. */\nexport class UploadValidationError extends LiveError {\n override readonly name: string = 'UploadValidationError'\n override readonly kind: ErrorKind = 'Validation'\n override readonly status: number = 422\n readonly errorBag: string = 'default'\n\n constructor(readonly errors: Record<string, string[]>) {\n super('The upload failed.')\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 { 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', 'placeholder', '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/**\n * Component's own API (dispatch, validate, reset, $action, __invoke, …), read from its prototype once, on first use:\n * Component.ts imports this module, so Component may not be initialized yet while this one loads.\n */\nlet baseApi: Set<string> | undefined\nconst isBaseApi = (name: string) => (baseApi ??= new Set(Object.getOwnPropertyNames(Component.prototype))).has(name)\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) || isBaseApi(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'\nimport { isTemporaryFileData, TemporaryUploadedFile } from './TemporaryUploadedFile'\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' | 'fil'\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,\n * collections and temporary uploads 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 (object instanceof TemporaryUploadedFile) return [object.toData(), { s: 'fil' }]\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 // A subclass (an empty Eloquent collection, an app's own) keeps its class, so it comes back as itself.\n const meta: SynthMeta = object.constructor === Collection ? { s: 'clctn' } : { s: 'clctn', class: classNameOf(registry, object.constructor as Class<unknown>) }\n return [items.map((item, i) => dehydrate(item, registry, `${path}.${i}`, seen)), meta]\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\nfunction collectionClass(registry: ClassRegistry, name: string): new (items: unknown[]) => Collection<unknown> {\n const cls = registry.has(name) ? registry.resolve(name) : undefined\n if (typeof cls !== 'function' || !(cls.prototype instanceof Collection)) throw new LiveError(`Unable to hydrate the [${name}] collection: it is not registered.`)\n return cls as unknown as new (items: unknown[]) => Collection<unknown>\n}\n\n/** A model that makes the collection its queries return (Database's newCollection(): the Eloquent collection). */\ntype CollectingModel = ModelInstance & { newCollection?(models: ModelInstance[]): Collection<ModelInstance> }\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 const items = await Promise.all((inner as unknown[]).map((item) => hydrate(item, registry)))\n return meta.class === undefined ? new Collection(items) : new (collectionClass(registry, meta.class))(items)\n }\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 'fil':\n if (!isTemporaryFileData(inner)) throw new LiveError('Unable to hydrate a temporary upload: its data is incomplete.')\n return new TemporaryUploadedFile(inner)\n case 'elcln': {\n const cls = modelClass(registry, meta.class)\n const keys = meta.keys ?? []\n const model = new cls() as CollectingModel\n const keyName = model.getKeyName()\n const found = [...((await cls.query().whereIn(keyName, keys).get()) as Iterable<ModelInstance>)]\n const byKey = new Map(found.map((item) => [String(item.getKey()), item]))\n const models = keys.map((key) => byKey.get(String(key))).filter((item) => item !== undefined)\n return model.newCollection ? model.newCollection(models) : new Collection(models)\n }\n }\n throw new LiveError(`Unknown snapshot value type [${String(meta.s)}].`)\n}\n","import { ConfigRepository, FilesystemManager, UrlGenerator, type Filesystem, type UploadedFile } from '@orieljs/contracts'\nimport { currentContainer } from '@orieljs/container'\nimport { Str } from '@orieljs/support'\nimport { FileNotPreviewableError, LiveError } from './errors'\n\n/**\n * Livewire's `temporary_file_upload` settings, read from config `live.temporary_file_upload.*` (each one falls back on\n * its own): the disk (the default filesystem disk), the directory on it, the rules every upload must pass, the upload\n * route's middleware, the types a preview is served for, how long an upload URL lasts (minutes), and whether a finished\n * upload removes the temporary files older than a day.\n */\nexport const TEMPORARY_UPLOAD_DEFAULTS = {\n disk: null as string | null,\n directory: 'live-tmp',\n rules: ['required', 'file', 'max:12288'] as string | string[],\n middleware: 'throttle:60,1' as string | string[],\n preview_mimes: ['png', 'gif', 'bmp', 'svg', 'wav', 'mp4', 'mov', 'avi', 'wmv', 'mp3', 'm4a', 'jpg', 'jpeg', 'mpga', 'webp', 'wma'],\n max_upload_time: 5,\n cleanup: true,\n}\n\ntype UploadSettings = typeof TEMPORARY_UPLOAD_DEFAULTS\n\nfunction container() {\n const current = currentContainer()\n if (current === undefined) throw new LiveError('Live uploads need the application: use them inside a request, a command or a test.')\n return current\n}\n\n/** One `live.temporary_file_upload` setting; null or a missing key gives Livewire's default. */\nexport function uploadSetting<K extends keyof UploadSettings>(name: K): UploadSettings[K] {\n const config = container().bound(ConfigRepository) ? container().make(ConfigRepository) : undefined\n return config?.get<UploadSettings[K] | null>(`live.temporary_file_upload.${name}`, null) ?? TEMPORARY_UPLOAD_DEFAULTS[name]\n}\n\n/** The disk temporary uploads live on (the default disk unless `live.temporary_file_upload.disk` names one). */\nexport function temporaryDisk(): Filesystem {\n return container().make(FilesystemManager).disk(uploadSetting('disk') ?? undefined)\n}\n\n/** The directory on that disk, without leading or trailing slashes. */\nexport function temporaryDirectory(): string {\n return uploadSetting('directory').replace(/^\\/+|\\/+$/g, '')\n}\n\n/** What a temporary upload is: its stored name on the temporary disk and what the browser sent (signed with it). */\nexport interface TemporaryFileData {\n /** A random 40-character name with the extension its bytes showed: `live-tmp/<filename>` on the temporary disk. */\n filename: string\n /** The name the browser gave the file. */\n name: string\n size: number\n /** The MIME type the browser claimed. */\n type: string\n /** The extension of the upload's own type (its bytes, else a plain claimed extension), or ''. */\n extension: string\n}\n\nconst FILENAME = /^[A-Za-z0-9]{40}(?:\\.[a-z0-9]+)?$/\n\n/** Whether `value` is the data of a temporary upload whose stored name can't leave the temporary directory. */\nexport function isTemporaryFileData(value: unknown): value is TemporaryFileData {\n if (typeof value !== 'object' || value === null) return false\n const data = value as Record<string, unknown>\n return (\n typeof data.filename === 'string' &&\n FILENAME.test(data.filename) &&\n typeof data.name === 'string' &&\n typeof data.size === 'number' &&\n Number.isSafeInteger(data.size) &&\n data.size >= 0 &&\n typeof data.type === 'string' &&\n typeof data.extension === 'string' &&\n /^[a-z0-9]*$/.test(data.extension)\n )\n}\n\nconst HOUR = 3600_000\n\n/**\n * Livewire's TemporaryUploadedFile: a file the browser uploaded to the temporary directory before an action stores\n * it. A WithFileUploads component's property holds one (or an array of them) once `o:model` on a file input has\n * uploaded it: validate it like any upload (`'photo' => 'image|max:1024'`), preview it with `temporaryUrl()`, then\n * `store()` it. It travels in the component's snapshot as its data, signed with the rest.\n */\nexport class TemporaryUploadedFile implements UploadedFile {\n readonly filename: string\n readonly clientName: string\n readonly mimeType: string\n readonly size: number\n readonly #extension: string\n\n constructor(data: TemporaryFileData) {\n if (!isTemporaryFileData(data)) throw new LiveError('A temporary upload needs a stored name, a name, a size, a type and an extension.')\n this.filename = data.filename\n this.clientName = data.name\n this.mimeType = data.type\n this.size = data.size\n this.#extension = data.extension\n }\n\n /** What the snapshot carries. */\n toData(): TemporaryFileData {\n return { filename: this.filename, name: this.clientName, size: this.size, type: this.mimeType, extension: this.#extension }\n }\n\n /** The file's path on the temporary disk. */\n get path(): string {\n const directory = temporaryDirectory()\n return directory === '' ? this.filename : `${directory}/${this.filename}`\n }\n\n /** The extension of the upload's own type, as FormUploadedFile's extension(): what putFile() names a stored copy by. */\n extension(): string {\n return this.#extension\n }\n\n /** The extension of the name the browser gave the file, lower-cased ('' without one). */\n clientExtension(): string {\n const dot = this.clientName.lastIndexOf('.')\n return dot === -1 ? '' : this.clientName.slice(dot + 1).toLowerCase()\n }\n\n /** A random 40-character name with extension(), as FormUploadedFile's. */\n hashName(): string {\n const extension = this.extension()\n return extension === '' ? Str.random(40) : `${Str.random(40)}.${extension}`\n }\n\n async arrayBuffer(): Promise<ArrayBuffer> {\n const bytes = await temporaryDisk().getBytes(this.path)\n return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer\n }\n\n async text(): Promise<string> {\n return new TextDecoder().decode(await temporaryDisk().getBytes(this.path))\n }\n\n /** The file's bytes from the temporary disk, opened on the first read. */\n stream(): ReadableStream<Uint8Array> {\n let reader: ReadableStreamDefaultReader<Uint8Array> | undefined\n return new ReadableStream<Uint8Array>({\n pull: async (controller) => {\n reader ??= (await temporaryDisk().readStream(this.path)).getReader()\n const { done, value } = await reader.read()\n if (done) controller.close()\n else controller.enqueue(value)\n },\n cancel: async (reason) => {\n await reader?.cancel(reason)\n },\n })\n }\n\n /** Stores a copy under a random name in `directory`, on `disk` (by default the temporary disk, as Livewire's). */\n store(directory: string, disk?: string): Promise<string> {\n return container()\n .make(FilesystemManager)\n .disk(disk ?? uploadSetting('disk') ?? undefined)\n .putFile(directory, this)\n }\n\n storeAs(directory: string, name: string, disk?: string): Promise<string> {\n return container()\n .make(FilesystemManager)\n .disk(disk ?? uploadSetting('disk') ?? undefined)\n .putFileAs(directory, this, name)\n }\n\n exists(): Promise<boolean> {\n return temporaryDisk().exists(this.path)\n }\n\n /** Removes the temporary file (a stored copy stays). */\n delete(): Promise<boolean> {\n return temporaryDisk().delete(this.path)\n }\n\n /** Whether temporaryUrl() serves this file: its type is in `live.temporary_file_upload.preview_mimes`. */\n isPreviewable(): boolean {\n return uploadSetting('preview_mimes').includes(this.#extension)\n }\n\n /**\n * A signed link to the file for `<img src>` or `<video src>` before it is stored. It lasts until the end of the hour\n * at least 30 minutes away (Livewire's), so a re-render keeps the same link and the browser doesn't reload it.\n */\n temporaryUrl(): string {\n if (!this.isPreviewable()) throw new FileNotPreviewableError(this.#extension)\n const expires = new Date((Math.floor((Date.now() + 30 * 60_000) / HOUR) + 1) * HOUR - 1000)\n return container().make(UrlGenerator).temporarySignedRoute('live.preview-file', expires, { filename: this.filename }, false)\n }\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 /**\n * Renders the placeholder and mounts the component once it scrolls into view (`'on-load'`: once the page starts);\n * `false` mounts a `static lazy` component at once.\n */\n lazy?: boolean | 'on-load'\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, stripTags } from './html'\nimport type { ComponentResult, LiveComponentManager } from './LiveComponentManager'\nimport { uploadedFileFrom } from './uploads'\nimport { uploadForTest } from './WithFileUploads'\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 /**\n * Mounts `component` with `params`, as `<Live component={…} {...params} />` would. A lazy component mounts at once\n * (Livewire's withoutLazyLoading()); `{ lazy: true }` renders its placeholder, and `call('__lazyLoad', …)` loads it.\n */\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, { lazy: false, ...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 /**\n * Sets public properties through an update. A file (a FakeFile) or an array of files is uploaded as `o:model` on a\n * file input does it: the upload rules, the temporary disk, then a TemporaryUploadedFile (or an array) in the\n * property, or the upload's errors on it (Livewire's).\n */\n async set(path: string | Record<string, unknown>, value?: unknown): Promise<this> {\n const files = [value].flat()\n if (typeof path === 'string' && files.length > 0 && files.every((file) => file instanceof Blob)) return this.upload(path, files as Blob[], Array.isArray(value))\n return this.#update(typeof path === 'string' ? { [path]: value } : path, [])\n }\n\n /** Uploads `files` into the property `name` (an array when `multiple`), as the browser's upload calls do. */\n async upload(name: string, files: readonly Blob[], multiple = false): Promise<this> {\n const info = files.map((file) => ({ name: (file as { name?: string }).name ?? '', size: file.size, type: file.type }))\n await this.#update({}, [{ method: '_startUpload', params: [name, info, multiple] }])\n const outcome = await this.scope(async () => uploadForTest(await Promise.all(files.map((file) => uploadedFileFrom(file)))))\n if ('errors' in outcome) return this.#update({}, [{ method: '_uploadErrored', params: [name, outcome.errors, multiple] }])\n return this.#update({}, [{ method: '_finishUpload', params: [name, outcome.references, multiple] }])\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 /** Each value, HTML-escaped, appears in the rendered text: the HTML with its tags stripped (Livewire's assertSeeText). */\n assertSeeText(...values: string[]): this {\n const text = stripTags(this.html())\n for (const value of values) if (!text.includes(escapeAttribute(value))) fail(`Failed asserting that [${value}] is in the rendered text.`, text, value)\n return this\n }\n\n assertDontSeeText(...values: string[]): this {\n const text = stripTags(this.html())\n for (const value of values) if (text.includes(escapeAttribute(value))) fail(`Failed asserting that [${value}] is not in the rendered text.`, text, 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 { LiveError } from './errors'\n\nconst ESCAPES: Record<string, string> = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '\"': '&quot;', \"'\": '&#039;' }\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\n/** The text of rendered HTML for assertSeeText(): every tag removed, attributes with it (PHP's strip_tags, roughly). */\nexport function stripTags(html: string): string {\n return html.replace(/<[^>]*>/g, '')\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 { ConfigRepository, Encrypter, UrlGenerator, ValidationFactory, type HttpRequest, type UploadedFile } from '@orieljs/contracts'\nimport { inject } from '@orieljs/container'\nimport { FileType, Str } from '@orieljs/support'\nimport { signValue, verifiedValue } from './checksum'\nimport { CorruptComponentPayloadError, InvalidUploadSignatureError, TemporaryFileNotFoundError } from './errors'\nimport { isTemporaryFileData, temporaryDirectory, temporaryDisk, TemporaryUploadedFile, uploadSetting } from './TemporaryUploadedFile'\n\n/** Where the browser POSTs a WithFileUploads component's files (Livewire's /livewire/upload-file), named live.upload-file. */\nexport const UPLOAD_URI = '/oriel/live/upload-file'\n/** Where temporaryUrl() links lead (Livewire's /livewire/preview-file/{filename}), named live.preview-file. */\nexport const PREVIEW_URI = '/oriel/live/preview-file'\n\n/** The purpose a temporary upload's reference is signed for. */\nconst REFERENCE = 'live.upload'\nconst DAY = 24 * 3600_000\n\n/** The types previews are served as, by extension (the default preview_mimes; anything else is a download). */\nconst PREVIEW_TYPES: Record<string, string> = {\n png: 'image/png',\n gif: 'image/gif',\n bmp: 'image/bmp',\n svg: 'image/svg+xml',\n jpg: 'image/jpeg',\n jpeg: 'image/jpeg',\n webp: 'image/webp',\n avif: 'image/avif',\n wav: 'audio/wav',\n mp3: 'audio/mpeg',\n mpga: 'audio/mpeg',\n m4a: 'audio/mp4',\n wma: 'audio/x-ms-wma',\n mp4: 'video/mp4',\n mov: 'video/quicktime',\n avi: 'video/x-msvideo',\n wmv: 'video/x-ms-wmv',\n}\n\nconst key = () => inject(Encrypter).getKey()\n\n/** The signed reference the upload route answers for a stored file; _finishUpload() takes it back. */\nexport function temporaryFileReference(file: TemporaryUploadedFile): string {\n return signValue(key(), REFERENCE, file.toData())\n}\n\n/**\n * The temporary upload a reference names. Only references this app signed are accepted (a 403 otherwise), so a\n * browser can't point a component at another file of the disk.\n */\nexport function temporaryFileFromReference(reference: unknown, component?: string): TemporaryUploadedFile {\n const data = verifiedValue(key(), REFERENCE, reference)\n if (!isTemporaryFileData(data)) throw new CorruptComponentPayloadError(component)\n return new TemporaryUploadedFile(data)\n}\n\n/** The rules every uploaded file must pass before it is stored (`live.temporary_file_upload.rules`). */\nexport function uploadRules(): string[] {\n const rules = uploadSetting('rules')\n return Array.isArray(rules) ? [...rules] : rules.split('|')\n}\n\n/** The upload route's middleware: `web` first (sessions, CSRF), then `live.temporary_file_upload.middleware`. */\nexport function uploadMiddleware(): string[] {\n const configured = [uploadSetting('middleware')].flat()\n return configured.includes('web') ? configured : ['web', ...configured]\n}\n\n/** Stores each upload in the temporary directory under a random name with the extension its bytes showed. */\nexport async function storeTemporaryFiles(files: readonly UploadedFile[]): Promise<TemporaryUploadedFile[]> {\n const disk = temporaryDisk()\n const directory = temporaryDirectory()\n return Promise.all(\n files.map(async (file) => {\n const extension = file.extension()\n const filename = extension === '' ? Str.random(40) : `${Str.random(40)}.${extension}`\n await disk.putFileAs(directory, file, filename)\n return new TemporaryUploadedFile({ filename, name: file.clientName, size: file.size, type: file.mimeType, extension })\n }),\n )\n}\n\n/**\n * A File (a test's FakeFile, a Blob) as the upload the route would have received: its extension is the type its\n * bytes show, else its name's plain extension, as a request upload's is.\n */\nexport async function uploadedFileFrom(file: Blob & { readonly name?: string }): Promise<UploadedFile> {\n const detected = FileType.detectFileType(new Uint8Array(await file.slice(0, FileType.SNIFF_BYTES).arrayBuffer()))\n const name = file.name ?? ''\n const claimed = name.includes('.') ? name.slice(name.lastIndexOf('.') + 1).toLowerCase() : ''\n const recognised = new Set(FileType.BINARY_AND_MARKUP_TYPES.flatMap(({ extensions }) => extensions))\n const extension =\n detected !== FileType.TEXT && detected.extensions.length > 0\n ? detected.extensions[0]!\n : /^[a-z0-9]+$/.test(claimed) && !recognised.has(claimed)\n ? claimed\n : detected === FileType.TEXT\n ? 'txt'\n : ''\n return {\n clientName: name,\n mimeType: file.type === '' ? 'application/octet-stream' : file.type,\n size: file.size,\n extension: () => extension,\n clientExtension: () => claimed,\n hashName: () => (extension === '' ? Str.random(40) : `${Str.random(40)}.${extension}`),\n arrayBuffer: () => file.arrayBuffer(),\n text: () => file.text(),\n stream: () => file.stream() as ReadableStream<Uint8Array>,\n store: () => Promise.reject(new Error('Store the temporary upload instead.')),\n storeAs: () => Promise.reject(new Error('Store the temporary upload instead.')),\n }\n}\n\n/** The files of an upload request: `files[]`, as an array whatever the form encoding made of it. */\nfunction filesOf(request: HttpRequest): unknown[] {\n const files = request.all().files\n if (files === undefined || files === null) return []\n if (Array.isArray(files)) return files\n return typeof files === 'object' && Object.getPrototypeOf(files) === Object.prototype ? Object.values(files) : [files]\n}\n\n/**\n * POST /oriel/live/upload-file (Livewire's FileUploadController): a URL _startUpload() signed, then every file checked\n * against the upload rules (a 422 with `files.N` errors) and stored in the temporary directory. Answers\n * `{ paths: [reference, …] }`, in the order of the files.\n */\nexport async function handleUpload(request: HttpRequest): Promise<{ paths: string[] }> {\n if (!inject(UrlGenerator).hasValidSignature(request, false)) throw new InvalidUploadSignatureError()\n const files = filesOf(request)\n await inject(ValidationFactory).make({ files }, { 'files.*': uploadRules() }).validated()\n const stored = await storeTemporaryFiles(files as UploadedFile[])\n return { paths: stored.map(temporaryFileReference) }\n}\n\n/**\n * GET /oriel/live/preview-file/{filename} (Livewire's FilePreviewController): a temporaryUrl() link, the file served\n * as an attachment in a sandbox (an image or a video still shows in the page; opened on its own, nothing in it runs).\n */\nexport async function handlePreview(request: HttpRequest, filename: string): Promise<Response> {\n if (!inject(UrlGenerator).hasValidSignature(request, false)) throw new InvalidUploadSignatureError()\n const data = { filename, name: '', size: 0, type: '', extension: filename.includes('.') ? filename.slice(filename.lastIndexOf('.') + 1) : '' }\n if (!isTemporaryFileData(data)) throw new TemporaryFileNotFoundError(filename)\n const file = new TemporaryUploadedFile(data)\n const disk = temporaryDisk()\n if (!(await disk.exists(file.path))) throw new TemporaryFileNotFoundError(filename)\n const bytes = await disk.getBytes(file.path)\n return new Response(bytes as Uint8Array<ArrayBuffer>, {\n headers: {\n 'Content-Type': PREVIEW_TYPES[data.extension] ?? 'application/octet-stream',\n 'Content-Length': String(bytes.byteLength),\n 'Content-Disposition': `attachment; filename=\"${filename}\"`,\n 'Content-Security-Policy': \"sandbox; default-src 'none'\",\n 'X-Content-Type-Options': 'nosniff',\n 'Cache-Control': 'private, max-age=3600',\n },\n })\n}\n\n/**\n * Removes the temporary uploads older than a day (Livewire's cleanupOldUploads(), run by each finished upload). Not on\n * an S3 disk, where listing the directory on every upload is slow: give the bucket a lifecycle rule for it instead.\n */\nexport async function cleanupOldUploads(): Promise<void> {\n if (uploadSetting('cleanup') === false) return\n const config = inject(ConfigRepository)\n const disk = uploadSetting('disk') ?? config.get<string>('filesystems.default', 'local')\n if (config.get<string | undefined>(`filesystems.disks.${disk}.driver`, undefined) === 's3') return\n const storage = temporaryDisk()\n const cutoff = Date.now() - DAY\n for (const path of await storage.files(temporaryDirectory())) {\n try {\n if ((await storage.lastModified(path)).getTime() < cutoff) await storage.delete(path)\n } catch {\n // Another request removed it meanwhile.\n }\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\n/** The HMAC of a signed value: its purpose and its payload, so a value signed for one use can't stand in for another. */\nfunction signatureOf(key: Uint8Array, purpose: string, payload: string): string {\n return createHmac('sha256', key).update(`${purpose}|${payload}`).digest('base64url')\n}\n\n/**\n * `value` as a token the browser can hold and send back: base64url(JSON), a dot, and its HMAC-SHA256 keyed by\n * APP_KEY for `purpose`. verifiedValue() gives the value back only when the token is untouched.\n */\nexport function signValue(key: Uint8Array, purpose: string, value: unknown): string {\n const payload = Buffer.from(JSON.stringify(value), 'utf8').toString('base64url')\n return `${payload}.${signatureOf(key, purpose, payload)}`\n}\n\n/** The value of a token signValue() made for `purpose`, or undefined when it is anything else. */\nexport function verifiedValue(key: Uint8Array, purpose: string, token: unknown): unknown {\n if (typeof token !== 'string') return undefined\n const dot = token.lastIndexOf('.')\n if (dot <= 0) return undefined\n const payload = token.slice(0, dot)\n const expected = Buffer.from(signatureOf(key, purpose, payload), 'utf8')\n const given = Buffer.from(token.slice(dot + 1), 'utf8')\n if (expected.length !== given.length || !timingSafeEqual(expected, given)) return undefined\n try {\n return JSON.parse(Buffer.from(payload, 'base64url').toString('utf8')) as unknown\n } catch {\n return undefined\n }\n}\n","import { UrlGenerator, ValidationFactory, type UploadedFile } from '@orieljs/contracts'\nimport { inject } from '@orieljs/container'\nimport { stateOf, type Component } from './Component'\nimport { LiveError, UploadValidationError } from './errors'\nimport { TemporaryUploadedFile, uploadSetting } from './TemporaryUploadedFile'\nimport { cleanupOldUploads, storeTemporaryFiles, temporaryFileFromReference, temporaryFileReference, uploadRules } from './uploads'\nimport type { ComponentConstructor } from './WithPagination'\n\n/** Marks the prototypes WithFileUploads() creates (Symbol.for, so two copies of the package agree). */\nconst UPLOADS = Symbol.for('oriel:live.uploads')\n\n/** The calls the client makes for `o:model` on a file input (Livewire's), handled only for WithFileUploads components. */\nexport const UPLOAD_CALLS: ReadonlySet<string> = new Set(['_startUpload', '_finishUpload', '_uploadErrored', '_removeUpload'])\n\n/**\n * Livewire's WithFileUploads: `class Profile extends WithFileUploads(Component)`. A file input with `o:model=\"photo\"`\n * uploads the file to the temporary directory as soon as it is picked, then sets `photo` to a TemporaryUploadedFile\n * (`<input type=\"file\" multiple>` sets an array), through `updatingPhoto()`/`updatedPhoto()` like any update. Validate\n * it with the file rules, preview it with `temporaryUrl()`, store it with `store()`.\n */\nexport function WithFileUploads<TBase extends ComponentConstructor>(Base: TBase): TBase {\n abstract class WithFileUploadsMixin extends Base {}\n Object.defineProperty(WithFileUploadsMixin.prototype, UPLOADS, { value: true })\n return WithFileUploadsMixin\n}\n\n/** Whether a component class was built with WithFileUploads(). */\nexport function usesFileUploads(component: Component): boolean {\n return (component as unknown as Record<symbol, unknown>)[UPLOADS] === true\n}\n\n/** Sets a property the way an update does: its checks and its updating/updated hooks (the manager's applyUpdate). */\nexport type ApplyUpdate = (path: string, value: unknown) => Promise<void>\n\nconst isRecord = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null && !Array.isArray(value)\n\nconst read = (component: Component, path: string): unknown =>\n path.split('.').reduce<unknown>((node, segment) => (isRecord(node) || Array.isArray(node) ? (node as Record<string, unknown>)[segment] : undefined), component)\n\n/** The upload's errors as the error bag holds them; anything malformed is Livewire's \"failed to upload\". */\nfunction uploadErrors(name: string, errors: unknown, multiple: boolean): Record<string, string[]> {\n if (typeof errors === 'string') {\n try {\n const replaced = errors.replace(multiple ? /files/gi : /files\\.0/gi, name)\n const bag = (JSON.parse(replaced) as { errors?: unknown }).errors\n if (isRecord(bag) && Object.values(bag).every((messages) => Array.isArray(messages) && messages.every((message) => typeof message === 'string'))) {\n return bag as Record<string, string[]>\n }\n } catch {\n // Not the upload route's JSON: the generic message below.\n }\n }\n return { [name]: [`The ${name} failed to upload.`] }\n}\n\n/**\n * Runs one of UPLOAD_CALLS on `component` and returns what the client receives: the signed upload URL\n * (`_startUpload`), the stored names (`_finishUpload`, `_removeUpload`). `_uploadErrored` throws the upload's\n * validation errors, which the component re-renders with.\n */\nexport async function runUploadCall(component: Component, method: string, params: unknown[], update: ApplyUpdate): Promise<unknown> {\n if (!usesFileUploads(component)) {\n throw new LiveError(`Cannot handle file upload without [WithFileUploads] on the [${stateOf(component).name}] component class.`)\n }\n const [name, value, multiple] = [String(params[0] ?? ''), params[1], params[2] === true]\n switch (method) {\n case '_startUpload':\n component.skipRender()\n return inject(UrlGenerator).temporarySignedRoute('live.upload-file', uploadSetting('max_upload_time') * 60, undefined, false)\n case '_finishUpload': {\n await cleanupOldUploads()\n const files = (Array.isArray(value) ? value : []).map((reference) => temporaryFileFromReference(reference, stateOf(component).name))\n const current = read(component, name)\n // A single upload into an array property adds to it (Livewire's).\n const next = multiple ? files : Array.isArray(current) ? [...(current as unknown[]), ...files] : (files[0] ?? null)\n await update(name, next)\n return files.map((file) => file.filename)\n }\n case '_uploadErrored':\n throw new UploadValidationError(uploadErrors(name, value, multiple))\n case '_removeUpload': {\n const filename = String(value ?? '')\n const current = read(component, name)\n if (Array.isArray(current)) {\n const removed = current.filter((file) => file instanceof TemporaryUploadedFile && file.filename === filename) as TemporaryUploadedFile[]\n for (const file of removed) await file.delete()\n await update(\n name,\n current.filter((file) => !removed.includes(file as TemporaryUploadedFile)),\n )\n } else if (current instanceof TemporaryUploadedFile && current.filename === filename) {\n await current.delete()\n await update(name, null)\n }\n return filename\n }\n }\n throw new LiveError(`Unknown upload call [${method}].`)\n}\n\n/**\n * What Live.test()'s set() does with files: what the browser and the upload route do, run directly. Checks them\n * against the upload rules and stores them; returns their references, or the route's 422 body when a rule fails.\n */\nexport async function uploadForTest(files: readonly UploadedFile[]): Promise<{ references: string[] } | { errors: string }> {\n try {\n await inject(ValidationFactory).make({ files: [...files] }, { 'files.*': uploadRules() }).validated()\n } catch (error) {\n const errors = (error as { kind?: unknown; errors?: unknown }).errors\n if ((error as { kind?: unknown }).kind !== 'Validation' || !isRecord(errors)) throw error\n return { errors: JSON.stringify({ errors }) }\n }\n return { references: (await storeTemporaryFiles(files)).map(temporaryFileReference) }\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 { assertSameRoot, lazyLoadOf, lazyMode, lazyPayload, placeholderHtml } from './lazy'\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 { runUploadCall, UPLOAD_CALLS } from './WithFileUploads'\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 root tag of the placeholder a component is loading from (set by its __lazyLoad call, checked by its render). */\nconst loading = new WeakMap<Component, string>()\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 /**\n * Mounts a component: boot(), the params into its properties, mount(params), then its first render. A lazy one\n * (`lazy` in the params, or `static lazy`) renders its placeholder instead and mounts when the browser loads it.\n */\n async mountComponent(component: string | Class<unknown>, embedParams: 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 const { lazy: _lazy, ...params } = embedParams\n const lazy = lazyMode(cls as { lazy?: boolean }, embedParams)\n await hook(instance, 'boot')\n if (lazy !== undefined) return this.mountPlaceholder(instance, params, lazy)\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 /**\n * A lazy component's first render (Livewire's): its placeholder, with the state it has before mount() and the mount\n * params signed for the `__lazyLoad` call the browser makes when it shows it (`o:lazy`, or `o:lazy-on-load`).\n */\n private async mountPlaceholder(instance: Component, params: Record<string, unknown>, lazy: 'intersect' | 'on-load'): Promise<ComponentResult> {\n const state = stateOf(instance)\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: state.name, path: page.path, method: page.method, children: {}, errors: {} }\n const html = await placeholderHtml(this.container(), instance, params)\n const tag = rootTag(html, state.name)\n const effects = this.effects(instance)\n const listeners = Object.keys(listenersOf(instance.constructor))\n if (listeners.length > 0) effects.listeners = listeners\n const snapshot = await this.snapshot(instance, memo)\n const payload = lazyPayload(this.key(), this.registry(), { id: state.id, name: state.name, tag, params })\n const attributes: Record<string, string> = {\n 'o:snapshot': JSON.stringify(snapshot),\n 'o:effects': JSON.stringify(effects),\n 'o:id': state.id,\n [lazy === 'on-load' ? 'o:lazy-on-load' : 'o:lazy']: payload,\n }\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 // A lazy component's load is checked before anything boots, hydrates or updates.\n const load = await this.lazyLoad(snapshot.memo, updates, calls)\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 // A lazy component's load mounts it: there is nothing to hydrate yet (Livewire skips hydrate() too).\n if (load === undefined) await hook(instance, 'hydrate')\n try {\n if (load !== undefined) {\n // The placeholder's signed mount params: into the properties, then mount(), as a first mount does.\n for (const [property, value] of Object.entries(load.params)) {\n if (Object.hasOwn(instance, property)) (instance as unknown as Record<string, unknown>)[property] = value\n }\n loading.set(instance, load.tag)\n await hook(instance, 'mount', load.params)\n returns.push(undefined)\n }\n for (const [path, value] of Object.entries(updates)) await this.applyUpdate(instance, path, value)\n for (const call of load === undefined ? 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 const placeholder = loading.get(instance)\n if (placeholder !== undefined) assertSameRoot(state.name, placeholder, tag)\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 mount params and placeholder tag of a `__lazyLoad` request, or undefined for any other update. The load comes\n * alone (no updates, no other call: the browser sends it in a request of its own) and its payload must be the one\n * signed for this component: anything else is refused as corrupt (a 403) before the component boots.\n */\n private async lazyLoad(memo: Memo, updates: Record<string, unknown>, calls: Call[]): Promise<{ params: Record<string, unknown>; tag: string } | undefined> {\n if (!calls.some((call) => call.method === '__lazyLoad')) return undefined\n if (calls.length !== 1 || Object.keys(updates).length > 0) throw new CorruptComponentPayloadError(memo.name)\n return lazyLoadOf(this.key(), this.registry(), calls[0]!.params[0], { id: memo.id, name: memo.name })\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, an upload call, 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 // o:model on a file input: _startUpload, _finishUpload, _uploadErrored, _removeUpload (WithFileUploads only).\n if (UPLOAD_CALLS.has(method)) return runUploadCall(instance, method, params, (path, value) => this.applyUpdate(instance, path, value))\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 { ConfigRepository, ViewFactory, type ClassRegistry, type Container } from '@orieljs/contracts'\nimport { signValue, verifiedValue } from './checksum'\nimport type { Component } from './Component'\nimport { CorruptComponentPayloadError, LiveError } from './errors'\nimport { dehydrate, hydrate } from './synthesizers'\n\n/** The purpose a lazy component's mount params are signed for. */\nconst PURPOSE = 'live.lazy'\n\n/** When a lazy component loads: once its placeholder scrolls into view, or as soon as the page starts. */\nexport type LazyMode = 'intersect' | 'on-load'\n\n/**\n * Livewire's lazy loading: `<Live component={Revenue} lazy />` (or `lazy=\"on-load\"`), or `static lazy = true` on the\n * class, which `lazy={false}` turns off for one embed. `lazy` itself is never a mount param.\n */\nexport function lazyMode(cls: { lazy?: boolean }, params: Record<string, unknown>): LazyMode | undefined {\n const { lazy } = params\n if (lazy === 'on-load') return 'on-load'\n if (lazy === true || (lazy === undefined && cls.lazy === true)) return 'intersect'\n return undefined\n}\n\n/**\n * The placeholder of a lazy component: its `placeholder(params)` (TSX or HTML), else the `live.lazy_placeholder`\n * view, else an empty `<div>`.\n */\nexport async function placeholderHtml(container: Container, instance: Component, params: Record<string, unknown>): Promise<string> {\n const method = (instance as unknown as { placeholder?: (params: Record<string, unknown>) => unknown }).placeholder\n const views = container.make(ViewFactory)\n let output = typeof method === 'function' ? await method.call(instance, params) : undefined\n if (output === undefined) {\n const view = container.bound(ConfigRepository) ? container.make(ConfigRepository).get<string | null>('live.lazy_placeholder', null) : null\n output = view === null || view === undefined ? '<div></div>' : views.make(view, params)\n }\n return (typeof output === 'string' ? output : await views.renderToString(output)).trim()\n}\n\n/** What a placeholder hands back with __lazyLoad: the component it belongs to, its root tag and the mount params. */\ninterface LazyLoad {\n id: string\n name: string\n tag: string\n params: Record<string, unknown>\n}\n\n/** The mount params signed for one placeholder (models and dates encoded as in state, so they survive the trip). */\nexport function lazyPayload(key: Uint8Array, registry: ClassRegistry, load: LazyLoad): string {\n const params = Object.fromEntries(Object.entries(load.params).map(([name, value]) => [name, dehydrate(value, registry, `${load.name}.${name}`)]))\n return signValue(key, PURPOSE, { ...load, params })\n}\n\n/**\n * The mount params of a __lazyLoad call and its placeholder's root tag. A payload that was changed, or that another\n * placeholder signed, is refused as corrupt (a 403), before anything mounts.\n */\nexport async function lazyLoadOf(key: Uint8Array, registry: ClassRegistry, payload: unknown, component: { id: string; name: string }): Promise<{ params: Record<string, unknown>; tag: string }> {\n const load = verifiedValue(key, PURPOSE, payload) as Partial<LazyLoad> | undefined\n if (load === undefined || load.id !== component.id || load.name !== component.name || typeof load.tag !== 'string' || typeof load.params !== 'object' || load.params === null) {\n throw new CorruptComponentPayloadError(component.name)\n }\n return { params: (await hydrate([load.params, { s: 'obj' }], registry)) as Record<string, unknown>, tag: load.tag }\n}\n\n/** A lazy component must keep its placeholder's root element: its parent re-renders it as a placeholder of that tag. */\nexport function assertSameRoot(name: string, placeholder: string, rendered: string): void {\n if (placeholder !== rendered) {\n throw new LiveError(`The lazy component [${name}] renders a <${rendered}> where its placeholder has a <${placeholder}>: give both the same root element.`)\n }\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 { 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 { handlePreview, handleUpload, PREVIEW_URI, UPLOAD_URI, uploadMiddleware } from './uploads'\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 upload and\n * preview routes of WithFileUploads (`live.upload-file`, `live.preview-file`), the make:live command, and the\n * 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 const router = this.app.make(Router)\n router\n .post(UPDATE_URI, () => manager.handle(inject(HttpRequest)))\n .middleware('web')\n .name('live.update')\n // WithFileUploads: the signed upload URL _startUpload() hands out, and the temporaryUrl() previews.\n router\n .post(UPLOAD_URI, () => handleUpload(inject(HttpRequest)))\n .middleware(uploadMiddleware())\n .name('live.upload-file')\n router\n .get(`${PREVIEW_URI}/{filename}`, (filename: string) => handlePreview(inject(HttpRequest), filename))\n .middleware('web')\n .name('live.preview-file')\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;AAAA,EACE;AAAA,EACA,gBAAAA;AAAA,EACA;AAAA,OAOK;AACP,SAAS,cAAc;;;ACRhB,IAAM,YAAN,cAAwB,MAA4B;AAAA,EACvC,OAAe;AAAA,EACxB,OAAkB;AAAA,EAClB,SAAiB;A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AAU,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":["UrlGenerator","key","methods","Collection","key","Collection","key","UrlGenerator","LiveManager","inject","LiveManager","currentContainer","inject","key","fail","token","ConfigRepository","UrlGenerator","ValidationFactory","inject","Str","key","token","inject","Str","UrlGenerator","ValidationFactory","ConfigRepository","UrlGenerator","ValidationFactory","inject","inject","UrlGenerator","ValidationFactory","container","currentContainer","inject","LiveManager","key","key","inject","LiveManager","AsyncLocalStorage","ConfigRepository","CurrentRoute","Encrypter","Session","ViewFactory","currentContainer","Str","ConfigRepository","container","ConfigRepository","key","Str","values","key","container","AsyncLocalStorage","container","token","isRecord","key","hook","currentContainer","ConfigRepository","Session","CurrentRoute","ViewFactory","Encrypter","Str","node","relative","ConfigRepository","HttpRequest","LiveManager","Router","inject","existsSync","join","relative","sep","ConfigRepository","Str","LiveManager","container","Router","inject","HttpRequest","ConfigRepository","live"]}
1
+ {"version":3,"sources":["../Component.ts","../errors.ts","../metadata.ts","../security.ts","../synthesizers.ts","../TemporaryUploadedFile.ts","../embed.ts","../Testable.ts","../flash.ts","../html.ts","../uploads.ts","../checksum.ts","../WithFileUploads.ts","../LiveComponentManager.ts","../lazy.ts","../naming.ts","../persistent.ts","../WithPagination.ts","../LiveServiceProvider.ts","../commands.ts","../describe.ts","../Pagination.ts"],"sourcesContent":["import {\n LiveManager,\n UrlGenerator,\n ValidationFactory,\n type Class,\n type InferValidatedType,\n type MessageBag,\n type RouteArguments,\n type RouteName,\n type Rules,\n} from '@orieljs/contracts'\nimport { inject } from '@orieljs/container'\nimport { LiveError } from './errors'\nimport { forgetComputed } from './metadata'\nimport { isCallable } from './security'\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 /** The field's own messages: a field named `constructor` or `toString` doesn't reach Object's. */\n #own(key: string): string[] | undefined {\n return Object.hasOwn(this.messages, key) ? this.messages[key] : undefined\n }\n\n /** Adds to the component's errors, as addError() does. */\n add(key: string, message: string): void {\n const messages = this.#own(key)\n if (messages !== undefined) messages.push(message)\n else Object.defineProperty(this.messages, key, { value: [message], enumerable: true, writable: true, configurable: true })\n }\n\n has(key: string): boolean {\n return (this.#own(key)?.length ?? 0) > 0\n }\n\n first(key?: string): string | undefined {\n return key === undefined ? this.all()[0] : this.#own(key)?.[0]\n }\n\n get(key: string): string[] {\n return [...(this.#own(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 /**\n * Livewire's #[Lazy]: every embed (and the full page) renders the placeholder first and mounts once the browser shows\n * it. `<Live component={…} lazy={false} />` mounts one at once. The placeholder is the component's\n * `placeholder(params)` method (TSX), else the `live.lazy_placeholder` view, else an empty `<div>`: give it the root\n * element the component renders.\n */\n static lazy?: boolean\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 /**\n * redirect() to a named route: `this.redirectRoute('posts.show', post, { navigate: true })`. Once `oriel\n * route:types` has run, the name and the route's parameters are checked, as route()'s are.\n */\n redirectRoute<N extends RouteName>(name: N, ...args: RouteArguments<N, [options?: { navigate?: boolean }]>): void {\n const [parameters, options = {}] = args as [parameters?: unknown, options?: { navigate?: boolean }]\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, typed from the rules\n * (`await this.validate({ title: 'required|string' })` is `{ title: string }`); on failure fills the error bag and\n * throws (the rest of the action is skipped and the component re-renders with `errors`).\n */\n async validate<const R extends Rules>(rules: R, messages?: Record<string, string>, attributes?: Record<string, string>): Promise<InferValidatedType<R>> {\n const validator = inject(ValidationFactory).make(Object.fromEntries(Object.entries(this)), rules, messages, attributes)\n try {\n const data = await validator.validated<InferValidatedType<R>>()\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 this.errors.add(key, 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 /**\n * An action for an `o:` directive, typed against its method: `o:click={this.$action(this.delete, tag.id)}` writes\n * `delete(5)`, and a string where `delete` takes a number is a type error. The arguments are written as JSON, the\n * trailing `undefined` ones left out so the method's defaults apply. The method must be one of this component's\n * actions (a public method of its class, not a hook and not @Locked); anything else throws while rendering.\n */\n $action<P extends unknown[]>(method: (...params: P) => unknown, ...params: NoInfer<P>): string {\n const name = typeof method === 'function' ? method.name : ''\n if (name === '' || (this as unknown as Record<string, unknown>)[name] !== method || !isCallable(this, name)) {\n throw new LiveError(\n `[${name === '' ? 'anonymous function' : name}] is not an action of [${this.getName() || this.constructor.name}]: pass one of its public methods, as in this.$action(this.save).`,\n )\n }\n let count = params.length\n while (count > 0 && params[count - 1] === undefined) count--\n return count === 0 ? name : `${name}(${params.slice(0, count).map((param) => JSON.stringify(param) ?? 'null').join(', ')})`\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","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\n/** An upload or preview URL whose signature is missing, wrong or expired (Livewire's 401). Nothing is read or stored. */\nexport class InvalidUploadSignatureError extends LiveError {\n override readonly name: string = 'InvalidUploadSignatureError'\n override readonly kind: ErrorKind = 'Http'\n override readonly status: number = 401\n\n constructor() {\n super('')\n }\n}\n\n/** A preview of a temporary upload that is no longer on the disk (cleaned up, or stored and deleted). */\nexport class TemporaryFileNotFoundError extends LiveError {\n override readonly name: string = 'TemporaryFileNotFoundError'\n override readonly kind: ErrorKind = 'Http'\n override readonly status: number = 404\n\n constructor(filename: string) {\n super(`Unable to find the temporary upload [${filename}].`)\n }\n}\n\n/** temporaryUrl() on an upload whose type has no preview (live.temporary_file_upload.preview_mimes). */\nexport class FileNotPreviewableError extends LiveError {\n override readonly name: string = 'FileNotPreviewableError'\n\n constructor(extension: string) {\n super(`File with extension \"${extension}\" is not previewable. See the live.temporary_file_upload.preview_mimes config.`)\n }\n}\n\n/** The errors an upload came back with (`_uploadErrored`): the component re-renders with them on the property. */\nexport class UploadValidationError extends LiveError {\n override readonly name: string = 'UploadValidationError'\n override readonly kind: ErrorKind = 'Validation'\n override readonly status: number = 422\n readonly errorBag: string = 'default'\n\n constructor(readonly errors: Record<string, string[]>) {\n super('The upload failed.')\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 { 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', 'placeholder', '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/**\n * Component's own API (dispatch, validate, reset, $action, __invoke, …), read from its prototype once, on first use:\n * Component.ts imports this module, so Component may not be initialized yet while this one loads.\n */\nlet baseApi: Set<string> | undefined\nconst isBaseApi = (name: string) => (baseApi ??= new Set(Object.getOwnPropertyNames(Component.prototype))).has(name)\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) || isBaseApi(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'\nimport { isTemporaryFileData, TemporaryUploadedFile } from './TemporaryUploadedFile'\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' | 'fil'\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,\n * collections and temporary uploads 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 (object instanceof TemporaryUploadedFile) return [object.toData(), { s: 'fil' }]\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 // A subclass (an empty Eloquent collection, an app's own) keeps its class, so it comes back as itself.\n const meta: SynthMeta = object.constructor === Collection ? { s: 'clctn' } : { s: 'clctn', class: classNameOf(registry, object.constructor as Class<unknown>) }\n return [items.map((item, i) => dehydrate(item, registry, `${path}.${i}`, seen)), meta]\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\nfunction collectionClass(registry: ClassRegistry, name: string): new (items: unknown[]) => Collection<unknown> {\n const cls = registry.has(name) ? registry.resolve(name) : undefined\n if (typeof cls !== 'function' || !(cls.prototype instanceof Collection)) throw new LiveError(`Unable to hydrate the [${name}] collection: it is not registered.`)\n return cls as unknown as new (items: unknown[]) => Collection<unknown>\n}\n\n/** A model that makes the collection its queries return (Database's newCollection(): the Eloquent collection). */\ntype CollectingModel = ModelInstance & { newCollection?(models: ModelInstance[]): Collection<ModelInstance> }\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 const items = await Promise.all((inner as unknown[]).map((item) => hydrate(item, registry)))\n return meta.class === undefined ? new Collection(items) : new (collectionClass(registry, meta.class))(items)\n }\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 'fil':\n if (!isTemporaryFileData(inner)) throw new LiveError('Unable to hydrate a temporary upload: its data is incomplete.')\n return new TemporaryUploadedFile(inner)\n case 'elcln': {\n const cls = modelClass(registry, meta.class)\n const keys = meta.keys ?? []\n const model = new cls() as CollectingModel\n const keyName = model.getKeyName()\n const found = [...((await cls.query().whereIn(keyName, keys).get()) as Iterable<ModelInstance>)]\n const byKey = new Map(found.map((item) => [String(item.getKey()), item]))\n const models = keys.map((key) => byKey.get(String(key))).filter((item) => item !== undefined)\n return model.newCollection ? model.newCollection(models) : new Collection(models)\n }\n }\n throw new LiveError(`Unknown snapshot value type [${String(meta.s)}].`)\n}\n","import { ConfigRepository, FilesystemManager, UrlGenerator, type Filesystem, type UploadedFile } from '@orieljs/contracts'\nimport { currentContainer } from '@orieljs/container'\nimport { Str } from '@orieljs/support'\nimport { FileNotPreviewableError, LiveError } from './errors'\n\n/**\n * Livewire's `temporary_file_upload` settings, read from config `live.temporary_file_upload.*` (each one falls back on\n * its own): the disk (the default filesystem disk), the directory on it, the rules every upload must pass, the upload\n * route's middleware, the types a preview is served for, how long an upload URL lasts (minutes), and whether a finished\n * upload removes the temporary files older than a day.\n */\nexport const TEMPORARY_UPLOAD_DEFAULTS = {\n disk: null as string | null,\n directory: 'live-tmp',\n rules: ['required', 'file', 'max:12288'] as string | string[],\n middleware: 'throttle:60,1' as string | string[],\n preview_mimes: ['png', 'gif', 'bmp', 'svg', 'wav', 'mp4', 'mov', 'avi', 'wmv', 'mp3', 'm4a', 'jpg', 'jpeg', 'mpga', 'webp', 'wma'],\n max_upload_time: 5,\n cleanup: true,\n}\n\ntype UploadSettings = typeof TEMPORARY_UPLOAD_DEFAULTS\n\nfunction container() {\n const current = currentContainer()\n if (current === undefined) throw new LiveError('Live uploads need the application: use them inside a request, a command or a test.')\n return current\n}\n\n/** One `live.temporary_file_upload` setting; null or a missing key gives Livewire's default. */\nexport function uploadSetting<K extends keyof UploadSettings>(name: K): UploadSettings[K] {\n const config = container().bound(ConfigRepository) ? container().make(ConfigRepository) : undefined\n return config?.get<UploadSettings[K] | null>(`live.temporary_file_upload.${name}`, null) ?? TEMPORARY_UPLOAD_DEFAULTS[name]\n}\n\n/** The disk temporary uploads live on (the default disk unless `live.temporary_file_upload.disk` names one). */\nexport function temporaryDisk(): Filesystem {\n return container().make(FilesystemManager).disk(uploadSetting('disk') ?? undefined)\n}\n\n/** The directory on that disk, without leading or trailing slashes. */\nexport function temporaryDirectory(): string {\n return uploadSetting('directory').replace(/^\\/+|\\/+$/g, '')\n}\n\n/** What a temporary upload is: its stored name on the temporary disk and what the browser sent (signed with it). */\nexport interface TemporaryFileData {\n /** A random 40-character name with the extension its bytes showed: `live-tmp/<filename>` on the temporary disk. */\n filename: string\n /** The name the browser gave the file. */\n name: string\n size: number\n /** The MIME type the browser claimed. */\n type: string\n /** The extension of the upload's own type (its bytes, else a plain claimed extension), or ''. */\n extension: string\n}\n\nconst FILENAME = /^[A-Za-z0-9]{40}(?:\\.[a-z0-9]+)?$/\n\n/** Whether `value` is the data of a temporary upload whose stored name can't leave the temporary directory. */\nexport function isTemporaryFileData(value: unknown): value is TemporaryFileData {\n if (typeof value !== 'object' || value === null) return false\n const data = value as Record<string, unknown>\n return (\n typeof data.filename === 'string' &&\n FILENAME.test(data.filename) &&\n typeof data.name === 'string' &&\n typeof data.size === 'number' &&\n Number.isSafeInteger(data.size) &&\n data.size >= 0 &&\n typeof data.type === 'string' &&\n typeof data.extension === 'string' &&\n /^[a-z0-9]*$/.test(data.extension)\n )\n}\n\nconst HOUR = 3600_000\n\n/**\n * Livewire's TemporaryUploadedFile: a file the browser uploaded to the temporary directory before an action stores\n * it. A WithFileUploads component's property holds one (or an array of them) once `o:model` on a file input has\n * uploaded it: validate it like any upload (`'photo' => 'image|max:1024'`), preview it with `temporaryUrl()`, then\n * `store()` it. It travels in the component's snapshot as its data, signed with the rest.\n */\nexport class TemporaryUploadedFile implements UploadedFile {\n readonly filename: string\n readonly clientName: string\n readonly mimeType: string\n readonly size: number\n readonly #extension: string\n\n constructor(data: TemporaryFileData) {\n if (!isTemporaryFileData(data)) throw new LiveError('A temporary upload needs a stored name, a name, a size, a type and an extension.')\n this.filename = data.filename\n this.clientName = data.name\n this.mimeType = data.type\n this.size = data.size\n this.#extension = data.extension\n }\n\n /** What the snapshot carries. */\n toData(): TemporaryFileData {\n return { filename: this.filename, name: this.clientName, size: this.size, type: this.mimeType, extension: this.#extension }\n }\n\n /** The file's path on the temporary disk. */\n get path(): string {\n const directory = temporaryDirectory()\n return directory === '' ? this.filename : `${directory}/${this.filename}`\n }\n\n /** The extension of the upload's own type, as FormUploadedFile's extension(): what putFile() names a stored copy by. */\n extension(): string {\n return this.#extension\n }\n\n /** The extension of the name the browser gave the file, lower-cased ('' without one). */\n clientExtension(): string {\n const dot = this.clientName.lastIndexOf('.')\n return dot === -1 ? '' : this.clientName.slice(dot + 1).toLowerCase()\n }\n\n /** A random 40-character name with extension(), as FormUploadedFile's. */\n hashName(): string {\n const extension = this.extension()\n return extension === '' ? Str.random(40) : `${Str.random(40)}.${extension}`\n }\n\n async arrayBuffer(): Promise<ArrayBuffer> {\n const bytes = await temporaryDisk().getBytes(this.path)\n return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer\n }\n\n async text(): Promise<string> {\n return new TextDecoder().decode(await temporaryDisk().getBytes(this.path))\n }\n\n /** The file's bytes from the temporary disk, opened on the first read. */\n stream(): ReadableStream<Uint8Array> {\n let reader: ReadableStreamDefaultReader<Uint8Array> | undefined\n return new ReadableStream<Uint8Array>({\n pull: async (controller) => {\n reader ??= (await temporaryDisk().readStream(this.path)).getReader()\n const { done, value } = await reader.read()\n if (done) controller.close()\n else controller.enqueue(value)\n },\n cancel: async (reason) => {\n await reader?.cancel(reason)\n },\n })\n }\n\n /** Stores a copy under a random name in `directory`, on `disk` (by default the temporary disk, as Livewire's). */\n store(directory: string, disk?: string): Promise<string> {\n return container()\n .make(FilesystemManager)\n .disk(disk ?? uploadSetting('disk') ?? undefined)\n .putFile(directory, this)\n }\n\n storeAs(directory: string, name: string, disk?: string): Promise<string> {\n return container()\n .make(FilesystemManager)\n .disk(disk ?? uploadSetting('disk') ?? undefined)\n .putFileAs(directory, this, name)\n }\n\n exists(): Promise<boolean> {\n return temporaryDisk().exists(this.path)\n }\n\n /** Removes the temporary file (a stored copy stays). */\n delete(): Promise<boolean> {\n return temporaryDisk().delete(this.path)\n }\n\n /** Whether temporaryUrl() serves this file: its type is in `live.temporary_file_upload.preview_mimes`. */\n isPreviewable(): boolean {\n return uploadSetting('preview_mimes').includes(this.#extension)\n }\n\n /**\n * A signed link to the file for `<img src>` or `<video src>` before it is stored. It lasts until the end of the hour\n * at least 30 minutes away (Livewire's), so a re-render keeps the same link and the browser doesn't reload it.\n */\n temporaryUrl(): string {\n if (!this.isPreviewable()) throw new FileNotPreviewableError(this.#extension)\n const expires = new Date((Math.floor((Date.now() + 30 * 60_000) / HOUR) + 1) * HOUR - 1000)\n return container().make(UrlGenerator).temporarySignedRoute('live.preview-file', expires, { filename: this.filename }, false)\n }\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 /**\n * Renders the placeholder and mounts the component once it scrolls into view (`'on-load'`: once the page starts);\n * `false` mounts a `static lazy` component at once.\n */\n lazy?: boolean | 'on-load'\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, stripTags } from './html'\nimport type { ComponentResult, LiveComponentManager } from './LiveComponentManager'\nimport { uploadedFileFrom } from './uploads'\nimport { uploadForTest } from './WithFileUploads'\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 /**\n * Mounts `component` with `params`, as `<Live component={…} {...params} />` would. A lazy component mounts at once\n * (Livewire's withoutLazyLoading()); `{ lazy: true }` renders its placeholder, and `call('__lazyLoad', …)` loads it.\n */\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, { lazy: false, ...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 /**\n * Sets public properties through an update. A file (a FakeFile) or an array of files is uploaded as `o:model` on a\n * file input does it: the upload rules, the temporary disk, then a TemporaryUploadedFile (or an array) in the\n * property, or the upload's errors on it (Livewire's).\n */\n async set(path: string | Record<string, unknown>, value?: unknown): Promise<this> {\n const files = [value].flat()\n if (typeof path === 'string' && files.length > 0 && files.every((file) => file instanceof Blob)) return this.upload(path, files as Blob[], Array.isArray(value))\n return this.#update(typeof path === 'string' ? { [path]: value } : path, [])\n }\n\n /** Uploads `files` into the property `name` (an array when `multiple`), as the browser's upload calls do. */\n async upload(name: string, files: readonly Blob[], multiple = false): Promise<this> {\n const info = files.map((file) => ({ name: (file as { name?: string }).name ?? '', size: file.size, type: file.type }))\n await this.#update({}, [{ method: '_startUpload', params: [name, info, multiple] }])\n const outcome = await this.scope(async () => uploadForTest(await Promise.all(files.map((file) => uploadedFileFrom(file)))))\n if ('errors' in outcome) return this.#update({}, [{ method: '_uploadErrored', params: [name, outcome.errors, multiple] }])\n return this.#update({}, [{ method: '_finishUpload', params: [name, outcome.references, multiple] }])\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 /** Each value, HTML-escaped, appears in the rendered text: the HTML with its tags stripped (Livewire's assertSeeText). */\n assertSeeText(...values: string[]): this {\n const text = stripTags(this.html())\n for (const value of values) if (!text.includes(escapeAttribute(value))) fail(`Failed asserting that [${value}] is in the rendered text.`, text, value)\n return this\n }\n\n assertDontSeeText(...values: string[]): this {\n const text = stripTags(this.html())\n for (const value of values) if (text.includes(escapeAttribute(value))) fail(`Failed asserting that [${value}] is not in the rendered text.`, text, 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 { LiveError } from './errors'\n\nconst ESCAPES: Record<string, string> = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '\"': '&quot;', \"'\": '&#039;' }\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\n/** The text of rendered HTML for assertSeeText(): every tag removed, attributes with it (PHP's strip_tags, roughly). */\nexport function stripTags(html: string): string {\n return html.replace(/<[^>]*>/g, '')\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 { ConfigRepository, Encrypter, UrlGenerator, ValidationFactory, type HttpRequest, type UploadedFile } from '@orieljs/contracts'\nimport { inject } from '@orieljs/container'\nimport { FileType, Str } from '@orieljs/support'\nimport { signValue, verifiedValue } from './checksum'\nimport { CorruptComponentPayloadError, InvalidUploadSignatureError, TemporaryFileNotFoundError } from './errors'\nimport { isTemporaryFileData, temporaryDirectory, temporaryDisk, TemporaryUploadedFile, uploadSetting } from './TemporaryUploadedFile'\n\n/** Where the browser POSTs a WithFileUploads component's files (Livewire's /livewire/upload-file), named live.upload-file. */\nexport const UPLOAD_URI = '/oriel/live/upload-file'\n/** Where temporaryUrl() links lead (Livewire's /livewire/preview-file/{filename}), named live.preview-file. */\nexport const PREVIEW_URI = '/oriel/live/preview-file'\n\n/** The purpose a temporary upload's reference is signed for. */\nconst REFERENCE = 'live.upload'\nconst DAY = 24 * 3600_000\n\n/** The types previews are served as, by extension (the default preview_mimes; anything else is a download). */\nconst PREVIEW_TYPES: Record<string, string> = {\n png: 'image/png',\n gif: 'image/gif',\n bmp: 'image/bmp',\n svg: 'image/svg+xml',\n jpg: 'image/jpeg',\n jpeg: 'image/jpeg',\n webp: 'image/webp',\n avif: 'image/avif',\n wav: 'audio/wav',\n mp3: 'audio/mpeg',\n mpga: 'audio/mpeg',\n m4a: 'audio/mp4',\n wma: 'audio/x-ms-wma',\n mp4: 'video/mp4',\n mov: 'video/quicktime',\n avi: 'video/x-msvideo',\n wmv: 'video/x-ms-wmv',\n}\n\nconst key = () => inject(Encrypter).getKey()\n\n/** The signed reference the upload route answers for a stored file; _finishUpload() takes it back. */\nexport function temporaryFileReference(file: TemporaryUploadedFile): string {\n return signValue(key(), REFERENCE, file.toData())\n}\n\n/**\n * The temporary upload a reference names. Only references this app signed are accepted (a 403 otherwise), so a\n * browser can't point a component at another file of the disk.\n */\nexport function temporaryFileFromReference(reference: unknown, component?: string): TemporaryUploadedFile {\n const data = verifiedValue(key(), REFERENCE, reference)\n if (!isTemporaryFileData(data)) throw new CorruptComponentPayloadError(component)\n return new TemporaryUploadedFile(data)\n}\n\n/** The rules every uploaded file must pass before it is stored (`live.temporary_file_upload.rules`). */\nexport function uploadRules(): string[] {\n const rules = uploadSetting('rules')\n return Array.isArray(rules) ? [...rules] : rules.split('|')\n}\n\n/** The upload route's middleware: `web` first (sessions, CSRF), then `live.temporary_file_upload.middleware`. */\nexport function uploadMiddleware(): string[] {\n const configured = [uploadSetting('middleware')].flat()\n return configured.includes('web') ? configured : ['web', ...configured]\n}\n\n/** Stores each upload in the temporary directory under a random name with the extension its bytes showed. */\nexport async function storeTemporaryFiles(files: readonly UploadedFile[]): Promise<TemporaryUploadedFile[]> {\n const disk = temporaryDisk()\n const directory = temporaryDirectory()\n return Promise.all(\n files.map(async (file) => {\n const extension = file.extension()\n const filename = extension === '' ? Str.random(40) : `${Str.random(40)}.${extension}`\n await disk.putFileAs(directory, file, filename)\n return new TemporaryUploadedFile({ filename, name: file.clientName, size: file.size, type: file.mimeType, extension })\n }),\n )\n}\n\n/**\n * A File (a test's FakeFile, a Blob) as the upload the route would have received: its extension is the type its\n * bytes show, else its name's plain extension, as a request upload's is.\n */\nexport async function uploadedFileFrom(file: Blob & { readonly name?: string }): Promise<UploadedFile> {\n const detected = FileType.detectFileType(new Uint8Array(await file.slice(0, FileType.SNIFF_BYTES).arrayBuffer()))\n const name = file.name ?? ''\n const claimed = name.includes('.') ? name.slice(name.lastIndexOf('.') + 1).toLowerCase() : ''\n const recognised = new Set(FileType.BINARY_AND_MARKUP_TYPES.flatMap(({ extensions }) => extensions))\n const extension =\n detected !== FileType.TEXT && detected.extensions.length > 0\n ? detected.extensions[0]!\n : /^[a-z0-9]+$/.test(claimed) && !recognised.has(claimed)\n ? claimed\n : detected === FileType.TEXT\n ? 'txt'\n : ''\n return {\n clientName: name,\n mimeType: file.type === '' ? 'application/octet-stream' : file.type,\n size: file.size,\n extension: () => extension,\n clientExtension: () => claimed,\n hashName: () => (extension === '' ? Str.random(40) : `${Str.random(40)}.${extension}`),\n arrayBuffer: () => file.arrayBuffer(),\n text: () => file.text(),\n stream: () => file.stream() as ReadableStream<Uint8Array>,\n store: () => Promise.reject(new Error('Store the temporary upload instead.')),\n storeAs: () => Promise.reject(new Error('Store the temporary upload instead.')),\n }\n}\n\n/** The files of an upload request: `files[]`, as an array whatever the form encoding made of it. */\nfunction filesOf(request: HttpRequest): unknown[] {\n const files = request.all().files\n if (files === undefined || files === null) return []\n if (Array.isArray(files)) return files\n return typeof files === 'object' && Object.getPrototypeOf(files) === Object.prototype ? Object.values(files) : [files]\n}\n\n/**\n * POST /oriel/live/upload-file (Livewire's FileUploadController): a URL _startUpload() signed, then every file checked\n * against the upload rules (a 422 with `files.N` errors) and stored in the temporary directory. Answers\n * `{ paths: [reference, …] }`, in the order of the files.\n */\nexport async function handleUpload(request: HttpRequest): Promise<{ paths: string[] }> {\n if (!inject(UrlGenerator).hasValidSignature(request, false)) throw new InvalidUploadSignatureError()\n const files = filesOf(request)\n await inject(ValidationFactory).make({ files }, { 'files.*': uploadRules() }).validated()\n const stored = await storeTemporaryFiles(files as UploadedFile[])\n return { paths: stored.map(temporaryFileReference) }\n}\n\n/**\n * GET /oriel/live/preview-file/{filename} (Livewire's FilePreviewController): a temporaryUrl() link, the file served\n * as an attachment in a sandbox (an image or a video still shows in the page; opened on its own, nothing in it runs).\n */\nexport async function handlePreview(request: HttpRequest, filename: string): Promise<Response> {\n if (!inject(UrlGenerator).hasValidSignature(request, false)) throw new InvalidUploadSignatureError()\n const data = { filename, name: '', size: 0, type: '', extension: filename.includes('.') ? filename.slice(filename.lastIndexOf('.') + 1) : '' }\n if (!isTemporaryFileData(data)) throw new TemporaryFileNotFoundError(filename)\n const file = new TemporaryUploadedFile(data)\n const disk = temporaryDisk()\n if (!(await disk.exists(file.path))) throw new TemporaryFileNotFoundError(filename)\n const bytes = await disk.getBytes(file.path)\n return new Response(bytes as Uint8Array<ArrayBuffer>, {\n headers: {\n 'Content-Type': PREVIEW_TYPES[data.extension] ?? 'application/octet-stream',\n 'Content-Length': String(bytes.byteLength),\n 'Content-Disposition': `attachment; filename=\"${filename}\"`,\n 'Content-Security-Policy': \"sandbox; default-src 'none'\",\n 'X-Content-Type-Options': 'nosniff',\n 'Cache-Control': 'private, max-age=3600',\n },\n })\n}\n\n/**\n * Removes the temporary uploads older than a day (Livewire's cleanupOldUploads(), run by each finished upload). Not on\n * an S3 disk, where listing the directory on every upload is slow: give the bucket a lifecycle rule for it instead.\n */\nexport async function cleanupOldUploads(): Promise<void> {\n if (uploadSetting('cleanup') === false) return\n const config = inject(ConfigRepository)\n const disk = uploadSetting('disk') ?? config.get<string>('filesystems.default', 'local')\n if (config.get<string | undefined>(`filesystems.disks.${disk}.driver`, undefined) === 's3') return\n const storage = temporaryDisk()\n const cutoff = Date.now() - DAY\n for (const path of await storage.files(temporaryDirectory())) {\n try {\n if ((await storage.lastModified(path)).getTime() < cutoff) await storage.delete(path)\n } catch {\n // Another request removed it meanwhile.\n }\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\n/** The HMAC of a signed value: its purpose and its payload, so a value signed for one use can't stand in for another. */\nfunction signatureOf(key: Uint8Array, purpose: string, payload: string): string {\n return createHmac('sha256', key).update(`${purpose}|${payload}`).digest('base64url')\n}\n\n/**\n * `value` as a token the browser can hold and send back: base64url(JSON), a dot, and its HMAC-SHA256 keyed by\n * APP_KEY for `purpose`. verifiedValue() gives the value back only when the token is untouched.\n */\nexport function signValue(key: Uint8Array, purpose: string, value: unknown): string {\n const payload = Buffer.from(JSON.stringify(value), 'utf8').toString('base64url')\n return `${payload}.${signatureOf(key, purpose, payload)}`\n}\n\n/** The value of a token signValue() made for `purpose`, or undefined when it is anything else. */\nexport function verifiedValue(key: Uint8Array, purpose: string, token: unknown): unknown {\n if (typeof token !== 'string') return undefined\n const dot = token.lastIndexOf('.')\n if (dot <= 0) return undefined\n const payload = token.slice(0, dot)\n const expected = Buffer.from(signatureOf(key, purpose, payload), 'utf8')\n const given = Buffer.from(token.slice(dot + 1), 'utf8')\n if (expected.length !== given.length || !timingSafeEqual(expected, given)) return undefined\n try {\n return JSON.parse(Buffer.from(payload, 'base64url').toString('utf8')) as unknown\n } catch {\n return undefined\n }\n}\n","import { UrlGenerator, ValidationFactory, type UploadedFile } from '@orieljs/contracts'\nimport { inject } from '@orieljs/container'\nimport { stateOf, type Component } from './Component'\nimport { LiveError, UploadValidationError } from './errors'\nimport { TemporaryUploadedFile, uploadSetting } from './TemporaryUploadedFile'\nimport { cleanupOldUploads, storeTemporaryFiles, temporaryFileFromReference, temporaryFileReference, uploadRules } from './uploads'\nimport type { ComponentConstructor } from './WithPagination'\n\n/** Marks the prototypes WithFileUploads() creates (Symbol.for, so two copies of the package agree). */\nconst UPLOADS = Symbol.for('oriel:live.uploads')\n\n/** The calls the client makes for `o:model` on a file input (Livewire's), handled only for WithFileUploads components. */\nexport const UPLOAD_CALLS: ReadonlySet<string> = new Set(['_startUpload', '_finishUpload', '_uploadErrored', '_removeUpload'])\n\n/**\n * Livewire's WithFileUploads: `class Profile extends WithFileUploads(Component)`. A file input with `o:model=\"photo\"`\n * uploads the file to the temporary directory as soon as it is picked, then sets `photo` to a TemporaryUploadedFile\n * (`<input type=\"file\" multiple>` sets an array), through `updatingPhoto()`/`updatedPhoto()` like any update. Validate\n * it with the file rules, preview it with `temporaryUrl()`, store it with `store()`.\n */\nexport function WithFileUploads<TBase extends ComponentConstructor>(Base: TBase): TBase {\n abstract class WithFileUploadsMixin extends Base {}\n Object.defineProperty(WithFileUploadsMixin.prototype, UPLOADS, { value: true })\n return WithFileUploadsMixin\n}\n\n/** Whether a component class was built with WithFileUploads(). */\nexport function usesFileUploads(component: Component): boolean {\n return (component as unknown as Record<symbol, unknown>)[UPLOADS] === true\n}\n\n/** Sets a property the way an update does: its checks and its updating/updated hooks (the manager's applyUpdate). */\nexport type ApplyUpdate = (path: string, value: unknown) => Promise<void>\n\nconst isRecord = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null && !Array.isArray(value)\n\nconst read = (component: Component, path: string): unknown =>\n path.split('.').reduce<unknown>((node, segment) => (isRecord(node) || Array.isArray(node) ? (node as Record<string, unknown>)[segment] : undefined), component)\n\n/** The upload's errors as the error bag holds them; anything malformed is Livewire's \"failed to upload\". */\nfunction uploadErrors(name: string, errors: unknown, multiple: boolean): Record<string, string[]> {\n if (typeof errors === 'string') {\n try {\n const replaced = errors.replace(multiple ? /files/gi : /files\\.0/gi, name)\n const bag = (JSON.parse(replaced) as { errors?: unknown }).errors\n if (isRecord(bag) && Object.values(bag).every((messages) => Array.isArray(messages) && messages.every((message) => typeof message === 'string'))) {\n return bag as Record<string, string[]>\n }\n } catch {\n // Not the upload route's JSON: the generic message below.\n }\n }\n return { [name]: [`The ${name} failed to upload.`] }\n}\n\n/**\n * Runs one of UPLOAD_CALLS on `component` and returns what the client receives: the signed upload URL\n * (`_startUpload`), the stored names (`_finishUpload`, `_removeUpload`). `_uploadErrored` throws the upload's\n * validation errors, which the component re-renders with.\n */\nexport async function runUploadCall(component: Component, method: string, params: unknown[], update: ApplyUpdate): Promise<unknown> {\n if (!usesFileUploads(component)) {\n throw new LiveError(`Cannot handle file upload without [WithFileUploads] on the [${stateOf(component).name}] component class.`)\n }\n const [name, value, multiple] = [String(params[0] ?? ''), params[1], params[2] === true]\n switch (method) {\n case '_startUpload':\n component.skipRender()\n return inject(UrlGenerator).temporarySignedRoute('live.upload-file', uploadSetting('max_upload_time') * 60, undefined, false)\n case '_finishUpload': {\n await cleanupOldUploads()\n const files = (Array.isArray(value) ? value : []).map((reference) => temporaryFileFromReference(reference, stateOf(component).name))\n const current = read(component, name)\n // A single upload into an array property adds to it (Livewire's).\n const next = multiple ? files : Array.isArray(current) ? [...(current as unknown[]), ...files] : (files[0] ?? null)\n await update(name, next)\n return files.map((file) => file.filename)\n }\n case '_uploadErrored':\n throw new UploadValidationError(uploadErrors(name, value, multiple))\n case '_removeUpload': {\n const filename = String(value ?? '')\n const current = read(component, name)\n if (Array.isArray(current)) {\n const removed = current.filter((file) => file instanceof TemporaryUploadedFile && file.filename === filename) as TemporaryUploadedFile[]\n for (const file of removed) await file.delete()\n await update(\n name,\n current.filter((file) => !removed.includes(file as TemporaryUploadedFile)),\n )\n } else if (current instanceof TemporaryUploadedFile && current.filename === filename) {\n await current.delete()\n await update(name, null)\n }\n return filename\n }\n }\n throw new LiveError(`Unknown upload call [${method}].`)\n}\n\n/**\n * What Live.test()'s set() does with files: what the browser and the upload route do, run directly. Checks them\n * against the upload rules and stores them; returns their references, or the route's 422 body when a rule fails.\n */\nexport async function uploadForTest(files: readonly UploadedFile[]): Promise<{ references: string[] } | { errors: string }> {\n try {\n await inject(ValidationFactory).make({ files: [...files] }, { 'files.*': uploadRules() }).validated()\n } catch (error) {\n const errors = (error as { kind?: unknown; errors?: unknown }).errors\n if ((error as { kind?: unknown }).kind !== 'Validation' || !isRecord(errors)) throw error\n return { errors: JSON.stringify({ errors }) }\n }\n return { references: (await storeTemporaryFiles(files)).map(temporaryFileReference) }\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 { assertSameRoot, lazyLoadOf, lazyMode, lazyPayload, placeholderHtml } from './lazy'\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 { runUploadCall, UPLOAD_CALLS } from './WithFileUploads'\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 root tag of the placeholder a component is loading from (set by its __lazyLoad call, checked by its render). */\nconst loading = new WeakMap<Component, string>()\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 /**\n * Mounts a component: boot(), the params into its properties, mount(params), then its first render. A lazy one\n * (`lazy` in the params, or `static lazy`) renders its placeholder instead and mounts when the browser loads it.\n */\n async mountComponent(component: string | Class<unknown>, embedParams: 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 const { lazy: _lazy, ...params } = embedParams\n const lazy = lazyMode(cls as { lazy?: boolean }, embedParams)\n await hook(instance, 'boot')\n if (lazy !== undefined) return this.mountPlaceholder(instance, params, lazy)\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 /**\n * A lazy component's first render (Livewire's): its placeholder, with the state it has before mount() and the mount\n * params signed for the `__lazyLoad` call the browser makes when it shows it (`o:lazy`, or `o:lazy-on-load`).\n */\n private async mountPlaceholder(instance: Component, params: Record<string, unknown>, lazy: 'intersect' | 'on-load'): Promise<ComponentResult> {\n const state = stateOf(instance)\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: state.name, path: page.path, method: page.method, children: {}, errors: {} }\n const html = await placeholderHtml(this.container(), instance, params)\n const tag = rootTag(html, state.name)\n const effects = this.effects(instance)\n const listeners = Object.keys(listenersOf(instance.constructor))\n if (listeners.length > 0) effects.listeners = listeners\n const snapshot = await this.snapshot(instance, memo)\n const payload = lazyPayload(this.key(), this.registry(), { id: state.id, name: state.name, tag, params })\n const attributes: Record<string, string> = {\n 'o:snapshot': JSON.stringify(snapshot),\n 'o:effects': JSON.stringify(effects),\n 'o:id': state.id,\n [lazy === 'on-load' ? 'o:lazy-on-load' : 'o:lazy']: payload,\n }\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 // A lazy component's load is checked before anything boots, hydrates or updates.\n const load = await this.lazyLoad(snapshot.memo, updates, calls)\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 // A lazy component's load mounts it: there is nothing to hydrate yet (Livewire skips hydrate() too).\n if (load === undefined) await hook(instance, 'hydrate')\n try {\n if (load !== undefined) {\n // The placeholder's signed mount params: into the properties, then mount(), as a first mount does.\n for (const [property, value] of Object.entries(load.params)) {\n if (Object.hasOwn(instance, property)) (instance as unknown as Record<string, unknown>)[property] = value\n }\n loading.set(instance, load.tag)\n await hook(instance, 'mount', load.params)\n returns.push(undefined)\n }\n for (const [path, value] of Object.entries(updates)) await this.applyUpdate(instance, path, value)\n for (const call of load === undefined ? 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 const placeholder = loading.get(instance)\n if (placeholder !== undefined) assertSameRoot(state.name, placeholder, tag)\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 mount params and placeholder tag of a `__lazyLoad` request, or undefined for any other update. The load comes\n * alone (no updates, no other call: the browser sends it in a request of its own) and its payload must be the one\n * signed for this component: anything else is refused as corrupt (a 403) before the component boots.\n */\n private async lazyLoad(memo: Memo, updates: Record<string, unknown>, calls: Call[]): Promise<{ params: Record<string, unknown>; tag: string } | undefined> {\n if (!calls.some((call) => call.method === '__lazyLoad')) return undefined\n if (calls.length !== 1 || Object.keys(updates).length > 0) throw new CorruptComponentPayloadError(memo.name)\n return lazyLoadOf(this.key(), this.registry(), calls[0]!.params[0], { id: memo.id, name: memo.name })\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, an upload call, 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 // o:model on a file input: _startUpload, _finishUpload, _uploadErrored, _removeUpload (WithFileUploads only).\n if (UPLOAD_CALLS.has(method)) return runUploadCall(instance, method, params, (path, value) => this.applyUpdate(instance, path, value))\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 { ConfigRepository, ViewFactory, type ClassRegistry, type Container } from '@orieljs/contracts'\nimport { signValue, verifiedValue } from './checksum'\nimport type { Component } from './Component'\nimport { CorruptComponentPayloadError, LiveError } from './errors'\nimport { dehydrate, hydrate } from './synthesizers'\n\n/** The purpose a lazy component's mount params are signed for. */\nconst PURPOSE = 'live.lazy'\n\n/** When a lazy component loads: once its placeholder scrolls into view, or as soon as the page starts. */\nexport type LazyMode = 'intersect' | 'on-load'\n\n/**\n * Livewire's lazy loading: `<Live component={Revenue} lazy />` (or `lazy=\"on-load\"`), or `static lazy = true` on the\n * class, which `lazy={false}` turns off for one embed. `lazy` itself is never a mount param.\n */\nexport function lazyMode(cls: { lazy?: boolean }, params: Record<string, unknown>): LazyMode | undefined {\n const { lazy } = params\n if (lazy === 'on-load') return 'on-load'\n if (lazy === true || (lazy === undefined && cls.lazy === true)) return 'intersect'\n return undefined\n}\n\n/**\n * The placeholder of a lazy component: its `placeholder(params)` (TSX or HTML), else the `live.lazy_placeholder`\n * view, else an empty `<div>`.\n */\nexport async function placeholderHtml(container: Container, instance: Component, params: Record<string, unknown>): Promise<string> {\n const method = (instance as unknown as { placeholder?: (params: Record<string, unknown>) => unknown }).placeholder\n const views = container.make(ViewFactory)\n let output = typeof method === 'function' ? await method.call(instance, params) : undefined\n if (output === undefined) {\n const view = container.bound(ConfigRepository) ? container.make(ConfigRepository).get<string | null>('live.lazy_placeholder', null) : null\n output = view === null || view === undefined ? '<div></div>' : views.make(view, params)\n }\n return (typeof output === 'string' ? output : await views.renderToString(output)).trim()\n}\n\n/** What a placeholder hands back with __lazyLoad: the component it belongs to, its root tag and the mount params. */\ninterface LazyLoad {\n id: string\n name: string\n tag: string\n params: Record<string, unknown>\n}\n\n/** The mount params signed for one placeholder (models and dates encoded as in state, so they survive the trip). */\nexport function lazyPayload(key: Uint8Array, registry: ClassRegistry, load: LazyLoad): string {\n const params = Object.fromEntries(Object.entries(load.params).map(([name, value]) => [name, dehydrate(value, registry, `${load.name}.${name}`)]))\n return signValue(key, PURPOSE, { ...load, params })\n}\n\n/**\n * The mount params of a __lazyLoad call and its placeholder's root tag. A payload that was changed, or that another\n * placeholder signed, is refused as corrupt (a 403), before anything mounts.\n */\nexport async function lazyLoadOf(key: Uint8Array, registry: ClassRegistry, payload: unknown, component: { id: string; name: string }): Promise<{ params: Record<string, unknown>; tag: string }> {\n const load = verifiedValue(key, PURPOSE, payload) as Partial<LazyLoad> | undefined\n if (load === undefined || load.id !== component.id || load.name !== component.name || typeof load.tag !== 'string' || typeof load.params !== 'object' || load.params === null) {\n throw new CorruptComponentPayloadError(component.name)\n }\n return { params: (await hydrate([load.params, { s: 'obj' }], registry)) as Record<string, unknown>, tag: load.tag }\n}\n\n/** A lazy component must keep its placeholder's root element: its parent re-renders it as a placeholder of that tag. */\nexport function assertSameRoot(name: string, placeholder: string, rendered: string): void {\n if (placeholder !== rendered) {\n throw new LiveError(`The lazy component [${name}] renders a <${rendered}> where its placeholder has a <${placeholder}>: give both the same root element.`)\n }\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 { 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 { handlePreview, handleUpload, PREVIEW_URI, UPLOAD_URI, uploadMiddleware } from './uploads'\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 upload and\n * preview routes of WithFileUploads (`live.upload-file`, `live.preview-file`), the make:live command, and the\n * 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 const router = this.app.make(Router)\n router\n .post(UPDATE_URI, () => manager.handle(inject(HttpRequest)))\n .middleware('web')\n .name('live.update')\n // WithFileUploads: the signed upload URL _startUpload() hands out, and the temporaryUrl() previews.\n router\n .post(UPLOAD_URI, () => handleUpload(inject(HttpRequest)))\n .middleware(uploadMiddleware())\n .name('live.upload-file')\n router\n .get(`${PREVIEW_URI}/{filename}`, (filename: string) => handlePreview(inject(HttpRequest), filename))\n .middleware('web')\n .name('live.preview-file')\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 { currentContainer } from '@orieljs/container'\nimport { Component } from './Component'\nimport { isCallable, isUpdatable } from './security'\n\n/**\n * What the browser may do with a component class, for editors (`oriel ide:info`): the actions it may call and the\n * properties it may set, each sorted. The instance is built as mounting builds one, and none of its hooks run.\n */\nexport function describeComponent(cls: new () => Component): { actions: string[]; properties: string[] } {\n const container = currentContainer()\n const instance = container ? container.make(cls) : new cls()\n const methods = new Set<string>()\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 for (const name of Object.getOwnPropertyNames(proto)) methods.add(name)\n }\n return {\n actions: [...methods].filter((name) => isCallable(instance, name)).sort(),\n properties: Object.keys(instance).filter((name) => isUpdatable(instance, name)).sort(),\n }\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;AAAA,EACE;AAAA,EACA,gBAAAA;AAAA,EACA;AAAA,OAOK;AACP,SAAS,cAAc;;;ACRhB,IAAM,YAAN,cAAwB,MAA4B;AAAA,EACvC,OAAe;AAAA,EACxB,OAAkB;AAAA,EAClB,SAAiB;AAC5B;AAGO,IAAM,+BAAN,cAA2C,UAAU;AAAA,EACxC,OAAe;AAAA,EACf,OAAkB;AAAA,EAClB,SAAiB;AAAA,EAEnC,YAAY,YAAY,WAAW;AACjC,UAAM,6DAA6D,SAAS,cAAc;AAAA,EAC5F;AACF;AAGO,IAAM,yBAAN,cAAqC,UAAU;AAAA,EAClC,OAAe;AAAA,EACf,OAAkB;AAAA,EAClB,SAAiB;AAAA,EAEnC,YAAY,QAAgB,WAAmB;AAC7C,UAAM,mDAAmD,MAAM,6BAA6B,SAAS,IAAI;AAAA,EAC3G;AACF;AAGO,IAAM,4BAAN,cAAwC,UAAU;AAAA,EACrC,OAAe;AAAA,EACf,OAAkB;AAAA,EAClB,SAAiB;AAAA,EAEnC,YAAY,MAAc,WAAmB;AAC3C,UAAM,2BAA2B,IAAI,mBAAmB,SAAS,2CAA2C;AAAA,EAC9G;AACF;AAGO,IAAM,6BAAN,cAAyC,UAAU;AAAA,EACtC,OAAe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U,UAAU,YAAY;AACtC,QAAM,UAAU,UAAU,YAAY;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":["UrlGenerator","key","methods","Collection","key","Collection","key","UrlGenerator","LiveManager","inject","LiveManager","currentContainer","inject","key","fail","token","ConfigRepository","UrlGenerator","ValidationFactory","inject","Str","key","token","inject","Str","UrlGenerator","ValidationFactory","ConfigRepository","UrlGenerator","ValidationFactory","inject","inject","UrlGenerator","ValidationFactory","container","currentContainer","inject","LiveManager","key","key","inject","LiveManager","AsyncLocalStorage","ConfigRepository","CurrentRoute","Encrypter","Session","ViewFactory","currentContainer","Str","ConfigRepository","container","ConfigRepository","key","Str","values","key","container","AsyncLocalStorage","container","token","isRecord","key","hook","currentContainer","ConfigRepository","Session","CurrentRoute","ViewFactory","Encrypter","Str","node","relative","ConfigRepository","HttpRequest","LiveManager","Router","inject","existsSync","join","relative","sep","ConfigRepository","Str","LiveManager","container","Router","inject","HttpRequest","ConfigRepository","currentContainer","container","currentContainer","live"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@orieljs/live",
3
- "version": "0.1.0-alpha.7",
3
+ "version": "0.1.0-alpha.9",
4
4
  "description": "Livewire-style server components for Oriel: TSX rendering, signed snapshots, actions, events and Live.test().",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",
@@ -31,10 +31,10 @@
31
31
  "TRADEMARKS.md"
32
32
  ],
33
33
  "dependencies": {
34
- "@orieljs/contracts": "0.1.0-alpha.7",
35
- "@orieljs/support": "0.1.0-alpha.7",
36
- "@orieljs/collections": "0.1.0-alpha.7",
37
- "@orieljs/container": "0.1.0-alpha.7"
34
+ "@orieljs/contracts": "0.1.0-alpha.9",
35
+ "@orieljs/container": "0.1.0-alpha.9",
36
+ "@orieljs/support": "0.1.0-alpha.9",
37
+ "@orieljs/collections": "0.1.0-alpha.9"
38
38
  },
39
39
  "scripts": {
40
40
  "build": "tsup && node ../../../scripts/copy-license.mjs"