@orieljs/framework 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/{chunk-4MWG3B7G.js → chunk-YAB54Y5I.js} +17 -2
- package/dist/chunk-YAB54Y5I.js.map +1 -0
- package/dist/index.d.ts +3 -1
- package/dist/index.js +223 -67
- package/dist/index.js.map +1 -1
- package/dist/testing.js +1 -1
- package/docs/console.md +1 -0
- package/package.json +30 -30
- package/dist/chunk-4MWG3B7G.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../Config/facade.ts","../../Config/Repository.ts","../../Config/env.ts","../../Config/LoadEnvironment.ts","../../Config/LoadConfiguration.ts","../../Foundation/Application.ts","../../Foundation/ApplicationBuilder.ts","../../Foundation/errors.ts","../../Foundation/Vite.ts","../../Foundation/Http/ClosureKernel.ts","../../Http/errors.ts","../../Http/body.ts","../../Http/context.ts","../../Http/HttpRedirectResponse.ts","../../Http/HttpRedirector.ts","../../Http/clientAddress.ts","../../Http/FormUploadedFile.ts","../../Http/mime.ts","../../Http/IncomingRequest.ts","../../Http/input.ts","../../Http/helpers.ts","../../Http/HttpResponseFactory.ts","../../Http/Kernel.ts","../../Http/middleware/ConvertEmptyStringsToNull.ts","../../Http/middleware/TrimStrings.ts","../../Http/MiddlewareConfiguration.ts","../../Http/ErrorHandler.ts","../../Http/errorPages.ts","../../Http/ExceptionsConfiguration.ts","../../Http/server/types.ts","../../Http/server/static.ts","../../Http/server/bun.ts","../../Http/server/node.ts","../../Http/server/serve.ts","../../Http/commands.ts","../../Http/watch/environment.ts","../../Http/watch/files.ts","../../Http/watch/port.ts","../../Http/watch/WatchedServer.ts","../../Http/HttpServiceProvider.ts","../../Live/Component.ts","../../Live/errors.ts","../../Live/metadata.ts","../../Live/security.ts","../../Live/synthesizers.ts","../../Live/TemporaryUploadedFile.ts","../../Live/embed.ts","../../Live/Testable.ts","../../Live/flash.ts","../../Live/html.ts","../../Live/uploads.ts","../../Live/checksum.ts","../../Live/WithFileUploads.ts","../../Live/LiveComponentManager.ts","../../Live/lazy.ts","../../Live/naming.ts","../../Live/persistent.ts","../../Live/WithPagination.ts","../../Live/LiveServiceProvider.ts","../../Live/commands.ts","../../Live/Pagination.ts","../../Testing/time.ts","../../Testing/Console/PendingCommand.ts","../../Testing/assert.ts","../../Testing/Concerns/InteractsWithDatabase.ts","../../Testing/Database/assertions.ts","../../Testing/Database/traits.ts","../../Testing/Concerns/MakesHttpRequests.ts","../../Testing/environment.ts","../../Testing/Http/HttpClient.ts","../../Testing/TestResponse.ts","../../Testing/Fluent/AssertableInertia.ts","../../Testing/Fluent/AssertableJson.ts","../../Testing/Http/cookies.ts","../../Testing/Http/recorders.ts","../../Testing/Concerns/InteractsWithApplication.ts","../../Testing/Concerns/InteractsWithConsole.ts","../../Testing/Concerns/InteractsWithTime.ts","../../Testing/TestCase.ts","../../Testing/Fakes/support.ts","../../Testing/Fakes/EventFake.ts","../../Testing/Fakes/BusFake.ts","../../Testing/Fakes/QueueFake.ts","../../Testing/Fakes/MailFake.ts","../../Testing/Fakes/NotificationFake.ts","../../Testing/Fakes/StorageFake.ts","../../Testing/FakeFile.ts"],"sourcesContent":["import { ConfigRepository } from '@orieljs/contracts'\nimport { facade } from '@orieljs/support'\n\n/** How the error names a value's type: string, number, boolean, array, object, null, undefined. */\nconst kind = (value: unknown): string => (value === null ? 'null' : Array.isArray(value) ? 'array' : typeof value)\n\nconst isPlainObject = (value: unknown): value is Record<string, unknown> => {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return false\n const proto: unknown = Object.getPrototypeOf(value)\n return proto === Object.prototype || proto === null\n}\n\n/** Laravel 12's typed getters: the value, or an error naming the key when the value isn't of the type asked for. */\nfunction typed<T>(repository: ConfigRepository, key: string, defaultValue: unknown, expected: string, check: (value: unknown) => boolean): T {\n const value = repository.get<unknown>(key, defaultValue)\n if (!check(value)) throw new TypeError(`Configuration value for key [${key}] must be ${expected}, ${kind(value)} given.`)\n return value as T\n}\n\n/**\n * Laravel's Config facade: the bound ConfigRepository (`get`, `set`, `has`, `push`, `all`), with Laravel 12's\n * `prepend()`, `getMany()` and typed getters (`string()`, `integer()`, `float()`, `boolean()`, `array()`). A float is\n * any number (JavaScript has one number type); an array is a list or an object (a config section).\n */\nexport const Config = facade(ConfigRepository, {\n /** Several keys at once: a list of keys, or an object of keys and their defaults. */\n getMany(this: ConfigRepository, keys: readonly string[] | Readonly<Record<string, unknown>>): Record<string, unknown> {\n const entries: Array<[string, unknown]> = Array.isArray(keys) ? keys.map((key: string) => [key, undefined]) : Object.entries(keys)\n return Object.fromEntries(entries.map(([key, fallback]) => [key, this.get(key, fallback)]))\n },\n /** Puts a value first in the array at `key` (creating it when missing). */\n prepend(this: ConfigRepository, key: string, value: unknown): void {\n const current = this.get<unknown>(key, [])\n this.set(key, [value, ...(Array.isArray(current) ? current : [current])])\n },\n string(this: ConfigRepository, key: string, defaultValue?: string): string {\n return typed(this, key, defaultValue, 'a string', (value) => typeof value === 'string')\n },\n integer(this: ConfigRepository, key: string, defaultValue?: number): number {\n return typed(this, key, defaultValue, 'an integer', (value) => Number.isInteger(value))\n },\n float(this: ConfigRepository, key: string, defaultValue?: number): number {\n return typed(this, key, defaultValue, 'a float', (value) => typeof value === 'number')\n },\n boolean(this: ConfigRepository, key: string, defaultValue?: boolean): boolean {\n return typed(this, key, defaultValue, 'a boolean', (value) => typeof value === 'boolean')\n },\n array(this: ConfigRepository, key: string, defaultValue?: unknown[] | Record<string, unknown>): unknown[] | Record<string, unknown> {\n return typed(this, key, defaultValue, 'an array', (value) => Array.isArray(value) || isPlainObject(value))\n },\n})\n","import type { ConfigRepository } from '@orieljs/contracts'\nimport { Arr } from '@orieljs/support'\n\nexport class Repository implements ConfigRepository {\n constructor(private readonly items: Record<string, unknown> = {}) {}\n\n has(key: string): boolean {\n return Arr.has(this.items, key)\n }\n\n get<T = unknown>(key: string, defaultValue?: T): T {\n return Arr.get(this.items, key, defaultValue)\n }\n\n set(key: string, value: unknown): void\n set(values: Record<string, unknown>): void\n set(keyOrValues: string | Record<string, unknown>, value?: unknown): void {\n const entries = typeof keyOrValues === 'string' ? [[keyOrValues, value] as const] : Object.entries(keyOrValues)\n for (const [k, v] of entries) Arr.set(this.items, k, v)\n }\n\n push(key: string, value: unknown): void {\n const current = this.get<unknown[]>(key, [])\n this.set(key, [...(Array.isArray(current) ? current : [current]), value])\n }\n\n all(): Record<string, unknown> {\n return this.items\n }\n}\n","const CASTS: Record<string, string | boolean | null> = {\n 'true': true, '(true)': true,\n 'false': false, '(false)': false,\n 'null': null, '(null)': null,\n 'empty': '', '(empty)': '',\n}\n\nexport function env<T = undefined>(key: string, defaultValue?: T | (() => T)): T | string | boolean | null {\n const raw = process.env[key]\n if (raw === undefined) return typeof defaultValue === 'function' ? (defaultValue as () => T)() : (defaultValue as T)\n const lower = raw.toLowerCase()\n if (Object.hasOwn(CASTS, lower)) return CASTS[lower]!\n const quoted = /^([\"'])(.*)\\1$/s.exec(raw)\n return quoted ? quoted[2]! : raw\n}\n","import { existsSync, readFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { parse } from 'dotenv'\n\n/** Keys whose value is single-quoted in the file: phpdotenv leaves those literal (no ${NAME} expansion). */\nfunction singleQuoted(source: string): Set<string> {\n const keys = new Set<string>()\n for (const match of source.matchAll(/^[ \\t]*(?:export[ \\t]+)?([\\w.-]+)[ \\t]*=[ \\t]*'/gm)) keys.add(match[1]!)\n return keys\n}\n\n/**\n * Loads .env (or .env.<APP_ENV> when it exists). Never overwrites existing variables. Returns the file loaded, if any.\n * Like phpdotenv, `${NAME}` in an unquoted or double-quoted value becomes the variable's value (one set earlier in the\n * file, or in the environment); single-quoted values and unknown names stay as written.\n */\nexport function loadEnvironment(basePath: string): string | undefined {\n const appEnv = process.env.APP_ENV\n const specific = appEnv ? join(basePath, `.env.${appEnv}`) : undefined\n const file = specific && existsSync(specific) ? specific : join(basePath, '.env')\n if (!existsSync(file)) return undefined\n\n const source = readFileSync(file, 'utf8')\n const literal = singleQuoted(source)\n for (const [key, raw] of Object.entries(parse(source))) {\n const value = literal.has(key) ? raw : raw.replace(/\\$\\{([A-Za-z_][A-Za-z0-9_.]*)\\}/g, (match, name: string) => process.env[name] ?? match)\n if (process.env[key] === undefined) process.env[key] = value\n }\n return file\n}\n","import { existsSync, readdirSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { pathToFileURL } from 'node:url'\n\nconst CONFIG_FILE = /^(?!.*\\.d\\.ts$)([A-Za-z0-9_-]+)\\.(ts|js|mjs)$/\n\n/** Copies plain objects and arrays; class instances, functions and other values are kept by reference. */\nfunction clonePlain<T>(value: T): T {\n if (Array.isArray(value)) return value.map((item: unknown) => clonePlain(item)) as T\n if (typeof value === 'object' && value !== null) {\n const proto = Object.getPrototypeOf(value) as unknown\n if (proto !== Object.prototype && proto !== null) return value\n return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, clonePlain(item)])) as T\n }\n return value\n}\n\n/**\n * Imports config/*.{ts,js,mjs}; each file's default export becomes config[<file name>].\n * Config files are cached ES modules, so every call returns fresh copies (apps in one process never share config state).\n */\nexport async function loadConfiguration(configPath: string): Promise<Record<string, unknown>> {\n if (!existsSync(configPath)) return {}\n const files = readdirSync(configPath).filter((f) => CONFIG_FILE.test(f)).sort()\n const config: Record<string, unknown> = {}\n for (const file of files) {\n const name = CONFIG_FILE.exec(file)![1]!\n const mod = (await import(pathToFileURL(join(configPath, file)).href)) as { default?: unknown }\n config[name] = clonePlain(mod.default ?? {})\n }\n return config\n}\n","import { join } from 'node:path'\nimport {\n Application as ApplicationToken,\n ClassRegistry as ClassRegistryToken,\n ConfigRepository,\n HttpKernel,\n type Application as ApplicationContract,\n type ServiceProvider,\n type ServiceProviderClass,\n} from '@orieljs/contracts'\nimport { Container } from '@orieljs/container'\nimport { ClassRegistry, Str } from '@orieljs/support'\nimport { ApplicationBuilder } from './ApplicationBuilder'\nimport { ProviderBootError, ProviderRegisterError } from './errors'\nimport { Vite } from './Vite'\n\ntype LifecycleCallback = (app: ApplicationContract) => void | Promise<void>\n\n/** How long shutdown() waits for its callbacks before giving up, so a hung close never keeps the process alive. */\nconst SHUTDOWN_TIMEOUT_MS = 10_000\n\nexport class Application extends Container implements ApplicationContract {\n readonly version = '0.1.0-alpha.7'\n\n private readonly providers: ServiceProvider[] = []\n private readonly bootingCallbacks: LifecycleCallback[] = []\n private readonly bootedCallbacks: LifecycleCallback[] = []\n private readonly terminatingCallbacks: Array<() => void | Promise<void>> = []\n private readonly shutdownCallbacks: Array<() => void | Promise<void>> = []\n private shutdownPromise: Promise<void> | undefined\n private bootPromise: Promise<void> | undefined\n private hasBooted = false\n private inConsole = false\n\n constructor(private readonly base: string) {\n super()\n Container.setInstance(this)\n this.instance(ApplicationToken, this)\n // The class too: otherwise inject(Application) would build a second app and hijack the global instance.\n this.instance(Application, this)\n this.singleton(ClassRegistryToken, ClassRegistry)\n // One per request: a CSP nonce set with vite().useCspNonce() must not leak into other requests.\n this.scoped(Vite, () => new Vite(this))\n }\n\n /** Entry point used by bootstrap/app.ts. */\n static configure(options: { basePath: string }): ApplicationBuilder {\n return new ApplicationBuilder(new Application(options.basePath))\n }\n\n basePath(path = ''): string { return join(this.base, path) }\n appPath(path = ''): string { return this.basePath(join('app', path)) }\n bootstrapPath(path = ''): string { return this.basePath(join('bootstrap', path)) }\n configPath(path = ''): string { return this.basePath(join('config', path)) }\n databasePath(path = ''): string { return this.basePath(join('database', path)) }\n publicPath(path = ''): string { return this.basePath(join('public', path)) }\n resourcePath(path = ''): string { return this.basePath(join('resources', path)) }\n storagePath(path = ''): string { return this.basePath(join('storage', path)) }\n\n environment(): string\n environment(...environments: string[]): boolean\n environment(...environments: string[]): string | boolean {\n const fallback = process.env.APP_ENV ?? 'production'\n const current = this.bound(ConfigRepository)\n ? String(this.make(ConfigRepository).get('app.env', fallback))\n : fallback\n return environments.length === 0 ? current : environments.some((pattern) => Str.is(pattern, current))\n }\n\n isProduction(): boolean { return this.environment('production') }\n isLocal(): boolean { return this.environment('local') }\n runningUnitTests(): boolean { return this.environment('testing') }\n runningInConsole(): boolean { return this.inConsole }\n setRunningInConsole(value = true): void { this.inConsole = value }\n\n async register(provider: ServiceProvider | ServiceProviderClass): Promise<ServiceProvider> {\n const cls = typeof provider === 'function' ? provider : provider.constructor\n const existing = this.providers.find((p) => p.constructor === cls)\n if (existing) return existing\n\n const instance = typeof provider === 'function' ? new provider(this) : provider\n try {\n instance.register?.()\n } catch (error) {\n throw new ProviderRegisterError(instance.constructor.name, error)\n }\n this.providers.push(instance)\n if (this.hasBooted) await this.bootProvider(instance)\n return instance\n }\n\n getProviders(): ServiceProvider[] {\n return [...this.providers]\n }\n\n boot(): Promise<void> {\n return (this.bootPromise ??= this.runBoot())\n }\n\n isBooted(): boolean {\n return this.hasBooted\n }\n\n booting(callback: LifecycleCallback): void {\n this.bootingCallbacks.push(callback)\n }\n\n /** If already booted, the callback runs immediately (a rejection surfaces as an unhandled rejection). */\n booted(callback: LifecycleCallback): void {\n this.bootedCallbacks.push(callback)\n if (this.hasBooted) void callback(this)\n }\n\n terminating(callback: () => void | Promise<void>): void {\n this.terminatingCallbacks.push(callback)\n }\n\n async handle(request: Request): Promise<Response> {\n await this.boot()\n const scope = this.createScope()\n return scope.run(() => scope.make(HttpKernel).handle(request))\n }\n\n async terminate(): Promise<void> {\n for (const callback of this.terminatingCallbacks) await callback()\n }\n\n /**\n * A callback for the end of the process (the CLI after its command, the server on SIGTERM): close DB pools, Redis\n * clients and log files. Not in Laravel, whose PHP processes end with each request.\n */\n onShutdown(callback: () => void | Promise<void>): void {\n this.shutdownCallbacks.push(callback)\n }\n\n /**\n * Runs the shutdown callbacks once (a second call returns the same promise), newest first: an app's own callbacks\n * run before the framework closes what they use, then the framework's in the reverse of its providers' order (the\n * queue, database and cache connections close, then the log is written, then the session store closes). A failing\n * callback is printed with console.error (the log may be closed already) and the others still run; after 10 seconds\n * the rest are given up on, so the process can still exit. Never rejects.\n */\n shutdown(): Promise<void> {\n return (this.shutdownPromise ??= this.runShutdown())\n }\n\n private async runShutdown(): Promise<void> {\n if (this.shutdownCallbacks.length === 0) return\n const callbacks = [...this.shutdownCallbacks].reverse()\n const run = (async () => {\n for (const callback of callbacks) {\n try {\n await callback()\n } catch (error) {\n console.error(error)\n }\n }\n return 'done' as const\n })()\n let timer: ReturnType<typeof setTimeout> | undefined\n // Not unref'd: if a callback hangs on a promise and nothing else is left, the process must still reach its exit.\n const deadline = new Promise<'timeout'>((resolve) => (timer = setTimeout(() => resolve('timeout'), SHUTDOWN_TIMEOUT_MS)))\n const outcome = await Promise.race([run, deadline])\n clearTimeout(timer)\n if (outcome === 'timeout') {\n console.error(`The shutdown callbacks did not finish within ${SHUTDOWN_TIMEOUT_MS / 1000} seconds; carrying on with the exit.`)\n }\n }\n\n private async runBoot(): Promise<void> {\n for (const callback of this.bootingCallbacks) await callback(this)\n // Index loop on purpose: providers registered during boot are appended and booted in this pass.\n for (let i = 0; i < this.providers.length; i++) await this.bootProvider(this.providers[i]!)\n this.hasBooted = true\n for (const callback of this.bootedCallbacks) await callback(this)\n }\n\n private async bootProvider(provider: ServiceProvider): Promise<void> {\n try {\n await provider.boot?.()\n } catch (error) {\n throw new ProviderBootError(provider.constructor.name, error)\n }\n }\n}\n","import { isAbsolute, join } from 'node:path'\nimport {\n ConfigRepository,\n ExceptionCallbacks,\n MiddlewareCallbacks,\n RoutingPaths,\n type Application as ApplicationContract,\n type ExceptionsConfigurator,\n type MiddlewareConfigurator,\n type ServiceProvider,\n type ServiceProviderClass,\n} from '@orieljs/contracts'\nimport { loadConfiguration, loadEnvironment, Repository } from '@orieljs/config'\nimport type { Application } from './Application'\n\nexport interface RoutingOptions {\n /** One route file or several, loaded in order: web: ['routes/web.ts', 'routes/settings.ts', 'routes/auth.ts']. */\n web?: string | string[]\n api?: string | string[]\n console?: string\n /** A URI such as '/up', not a file. */\n health?: string\n apiPrefix?: string\n}\n\ntype Lifecycle = (app: ApplicationContract) => void | Promise<void>\n\nexport class ApplicationBuilder {\n private readonly providers: Array<ServiceProvider | ServiceProviderClass> = []\n private readonly middleware: Array<(middleware: MiddlewareConfigurator) => void> = []\n private readonly exceptions: Array<(exceptions: ExceptionsConfigurator) => void> = []\n private routing: RoutingPaths | undefined\n\n constructor(private readonly app: Application) {}\n\n withProviders(providers: Array<ServiceProvider | ServiceProviderClass> = []): this {\n this.providers.push(...providers)\n return this\n }\n\n withRouting(options: RoutingOptions): this {\n const abs = (p: string) => (isAbsolute(p) ? p : join(this.app.basePath(), p))\n const each = (p: string | string[]) => (Array.isArray(p) ? p.map(abs) : abs(p))\n const paths: RoutingPaths = { apiPrefix: options.apiPrefix ?? 'api' }\n if (options.web !== undefined) paths.web = each(options.web)\n if (options.api !== undefined) paths.api = each(options.api)\n if (options.console !== undefined) paths.console = abs(options.console)\n if (options.health !== undefined) paths.health = options.health\n this.routing = paths\n return this\n }\n\n withMiddleware(callback: (middleware: MiddlewareConfigurator) => void): this {\n this.middleware.push(callback)\n return this\n }\n\n withExceptions(callback: (exceptions: ExceptionsConfigurator) => void): this {\n this.exceptions.push(callback)\n return this\n }\n\n booting(callback: Lifecycle): this {\n this.app.booting(callback)\n return this\n }\n\n booted(callback: Lifecycle): this {\n this.app.booted(callback)\n return this\n }\n\n async create(): Promise<Application> {\n loadEnvironment(this.app.basePath())\n this.app.instance(ConfigRepository, new Repository(await loadConfiguration(this.app.configPath())))\n if (this.routing) this.app.instance(RoutingPaths, this.routing)\n this.app.instance(MiddlewareCallbacks, this.middleware as Array<(configurator: unknown) => void>)\n this.app.instance(ExceptionCallbacks, this.exceptions)\n for (const provider of this.providers) await this.app.register(provider)\n return this.app\n }\n}\n","export class ProviderBootError extends Error {\n override readonly name = 'ProviderBootError'\n constructor(readonly provider: string, cause: unknown) {\n super(`Service provider [${provider}] failed to boot: ${cause instanceof Error ? cause.message : String(cause)}`, { cause })\n }\n}\n\nexport class ProviderRegisterError extends Error {\n override readonly name = 'ProviderRegisterError'\n constructor(readonly provider: string, cause: unknown) {\n super(`Service provider [${provider}] failed to register: ${cause instanceof Error ? cause.message : String(cause)}`, { cause })\n }\n}\n","import { existsSync, readFileSync, statSync } from 'node:fs'\nimport { createHash, randomBytes } from 'node:crypto'\nimport { join } from 'node:path'\nimport { Application as ApplicationToken, ConfigRepository, HttpRequest, UrlGenerator, type Application, type Htmlable, type OrielError } from '@orieljs/contracts'\nimport { ContainerNotAvailableError, currentContainer } from '@orieljs/container'\n\n/** One entry of Vite's build manifest (vite's ManifestChunk). */\nexport interface ManifestChunk {\n file: string\n src?: string\n name?: string\n isEntry?: boolean\n isDynamicEntry?: boolean\n imports?: string[]\n dynamicImports?: string[]\n css?: string[]\n assets?: string[]\n [key: string]: unknown\n}\nexport type Manifest = Record<string, ManifestChunk>\n\nexport type TagAttributes = Record<string, string | boolean | null | undefined>\nexport type AttributesResolver = (src: string, url: string, chunk: ManifestChunk | undefined, manifest: Manifest | undefined) => TagAttributes\nexport type PreloadAttributesResolver = (src: string, url: string, chunk: ManifestChunk | undefined, manifest: Manifest | undefined) => TagAttributes | false\n\n/** A missing manifest or chunk (Laravel's ViteException / ViteManifestNotFoundException). */\nexport class ViteError extends Error implements OrielError {\n readonly kind = 'Server' as const\n readonly status = 500\n\n constructor(message: string) {\n super(message)\n this.name = 'ViteError'\n }\n}\n\n/** Markup the view renderer emits unescaped (Htmlable; Foundation can't import View's HtmlString). */\nexport class ViteHtml implements Htmlable {\n constructor(private readonly html: string) {}\n\n toHtml(): string {\n return this.html\n }\n\n toString(): string {\n return this.html\n }\n}\n\n/**\n * Marks the tags as tracked assets: when o:navigate reaches a page whose tracked URLs changed (a new build), it loads\n * the page in full rather than run the new bundle beside the old one. A tag attribute of `false` takes it off.\n */\nconst TRACKED: TagAttributes = { 'data-navigate-track': true }\nconst CSS_PATH = /\\.(css|less|sass|scss|styl|stylus|pcss|postcss)(\\?[^.]*)?$/\n\n/** Parsed manifests by path, reloaded when the file changes (a long-running server outlives a `vite build`). */\nconst manifests = new Map<string, { mtimeMs: number; manifest: Manifest }>()\n\nconst escapeAttribute = (value: string): string => value.replace(/&/g, '&').replace(/\"/g, '"')\n\n/**\n * Laravel's Illuminate\\Foundation\\Vite: the script, style and preload tags for Vite entry points. While the dev\n * server runs (public/hot holds its URL) it points at the dev server; otherwise it reads public/build/manifest.json.\n */\nexport class Vite {\n #hotFile: string | undefined\n #buildDirectory = 'build'\n #manifestFilename = 'manifest.json'\n #nonce: string | undefined\n #integrityKey: string | false = 'integrity'\n #entryPoints: string[] = []\n readonly #scriptResolvers: AttributesResolver[] = []\n readonly #styleResolvers: AttributesResolver[] = []\n readonly #preloadResolvers: PreloadAttributesResolver[] = []\n #assetPathResolver: ((path: string) => string) | undefined\n readonly #preloaded: Record<string, string[]> = {}\n\n constructor(protected readonly app: Application) {}\n\n // Configuration --------------------------------------------------------------------------------------------\n\n useCspNonce(nonce?: string): string {\n this.#nonce = nonce ?? randomBytes(30).toString('base64url').slice(0, 40)\n return this.#nonce\n }\n\n cspNonce(): string | undefined {\n return this.#nonce\n }\n\n useIntegrityKey(key: string | false): this {\n this.#integrityKey = key\n return this\n }\n\n withEntryPoints(entryPoints: string[]): this {\n this.#entryPoints = entryPoints\n return this\n }\n\n useHotFile(path: string): this {\n this.#hotFile = path\n return this\n }\n\n useBuildDirectory(path: string): this {\n this.#buildDirectory = path\n return this\n }\n\n useManifestFilename(filename: string): this {\n this.#manifestFilename = filename\n return this\n }\n\n useScriptTagAttributes(attributes: TagAttributes | AttributesResolver): this {\n this.#scriptResolvers.push(typeof attributes === 'function' ? attributes : () => attributes)\n return this\n }\n\n useStyleTagAttributes(attributes: TagAttributes | AttributesResolver): this {\n this.#styleResolvers.push(typeof attributes === 'function' ? attributes : () => attributes)\n return this\n }\n\n /** Extra preload attributes; a resolver returning false drops that preload. */\n usePreloadTagAttributes(attributes: TagAttributes | PreloadAttributesResolver | false): this {\n this.#preloadResolvers.push(typeof attributes === 'function' ? attributes : () => attributes)\n return this\n }\n\n createAssetPathsUsing(resolver: (path: string) => string): this {\n this.#assetPathResolver = resolver\n return this\n }\n\n // Dev server -----------------------------------------------------------------------------------------------\n\n hotFile(): string {\n return this.#hotFile ?? this.app.publicPath('hot')\n }\n\n isRunningHot(): boolean {\n return existsSync(this.hotFile())\n }\n\n /** The dev server URL written by @orieljs/vite, or undefined when it isn't running. */\n devServerUrl(): string | undefined {\n return this.isRunningHot() ? readFileSync(this.hotFile(), 'utf8').trimEnd() : undefined\n }\n\n // Tags -----------------------------------------------------------------------------------------------------\n\n /** Laravel's @vite([...]): preloads (styles first), then stylesheets, then scripts. */\n tags(entryPoints: string | string[], buildDirectory = this.#buildDirectory): ViteHtml {\n const entries = [entryPoints].flat()\n if (this.isRunningHot()) {\n return new ViteHtml(['@vite/client', ...entries].map((entry) => this.#tagForChunk(entry, this.#hotAsset(entry), undefined, undefined)).join(''))\n }\n const manifest = this.manifest(buildDirectory)\n const tags: string[] = []\n const preloads: Array<[string, string, ManifestChunk | undefined]> = []\n const cssChunk = (css: string): [string, ManifestChunk | undefined] => {\n const found = Object.entries(manifest).find(([, chunk]) => chunk.file === css)\n return found === undefined ? [css, undefined] : [found[0], found[1]]\n }\n for (const entry of entries) {\n const chunk = this.#chunk(manifest, entry)\n preloads.push([chunk.src ?? entry, this.#assetPath(`${buildDirectory}/${chunk.file}`), chunk])\n for (const name of this.#resolveImports(manifest, chunk)) {\n const imported = manifest[name]!\n preloads.push([name, this.#assetPath(`${buildDirectory}/${imported.file}`), imported])\n for (const css of imported.css ?? []) {\n const [key, partial] = cssChunk(css)\n preloads.push([key, this.#assetPath(`${buildDirectory}/${css}`), partial])\n tags.push(this.#tagForChunk(key, this.#assetPath(`${buildDirectory}/${css}`), partial, manifest))\n }\n }\n tags.push(this.#tagForChunk(entry, this.#assetPath(`${buildDirectory}/${chunk.file}`), chunk, manifest))\n for (const css of chunk.css ?? []) {\n const [key, partial] = cssChunk(css)\n preloads.push([key, this.#assetPath(`${buildDirectory}/${css}`), partial])\n tags.push(this.#tagForChunk(key, this.#assetPath(`${buildDirectory}/${css}`), partial, manifest))\n }\n }\n const uniqueTags = [...new Set(tags)]\n const stylesheets = uniqueTags.filter((tag) => tag.startsWith('<link'))\n const scripts = uniqueTags.filter((tag) => !tag.startsWith('<link'))\n const seen = new Set<string>()\n const uniquePreloads = preloads.filter(([, url]) => (seen.has(url) ? false : (seen.add(url), true)))\n const sorted = [...uniquePreloads.filter(([, url]) => CSS_PATH.test(url)), ...uniquePreloads.filter(([, url]) => !CSS_PATH.test(url))]\n const preloadTags = sorted.map(([src, url, chunk]) => this.#preloadTag(src, url, chunk, manifest))\n return new ViteHtml(preloadTags.join('') + stylesheets.join('') + scripts.join(''))\n }\n\n /** Laravel's @viteReactRefresh: the React Refresh preamble while the dev server runs; nothing otherwise. */\n reactRefresh(): ViteHtml | undefined {\n if (!this.isRunningHot()) return undefined\n const attributes = this.#parseAttributes({ nonce: this.#nonce ?? false })\n return new ViteHtml(\n [\n `<script type=\"module\" ${attributes.join(' ')}>`,\n ` import RefreshRuntime from '${this.#hotAsset('@react-refresh')}'`,\n ' RefreshRuntime.injectIntoGlobalHook(window)',\n ' window.$RefreshReg$ = () => {}',\n ' window.$RefreshSig$ = () => (type) => type',\n ' window.__vite_plugin_react_preamble_installed__ = true',\n '</script>',\n ].join('\\n'),\n )\n }\n\n /** The URL of a processed asset (Vite::asset('resources/images/logo.svg')). */\n asset(path: string, buildDirectory = this.#buildDirectory): string {\n if (this.isRunningHot()) return this.#hotAsset(path)\n return this.#assetPath(`${buildDirectory}/${this.#chunk(this.manifest(buildDirectory), path).file}`)\n }\n\n /** The built file's contents (Vite::content()). */\n content(path: string, buildDirectory = this.#buildDirectory): string {\n const chunk = this.#chunk(this.manifest(buildDirectory), path)\n const file = this.app.publicPath(join(buildDirectory, chunk.file))\n if (!existsSync(file)) throw new ViteError(`Unable to locate file from Vite manifest: ${file}.`)\n return readFileSync(file, 'utf8')\n }\n\n /** md5 of the manifest (a cache-busting asset version); undefined while hot or without a build. */\n manifestHash(buildDirectory = this.#buildDirectory): string | undefined {\n if (this.isRunningHot()) return undefined\n const path = this.manifestPath(buildDirectory)\n return existsSync(path) ? createHash('md5').update(readFileSync(path)).digest('hex') : undefined\n }\n\n manifestPath(buildDirectory = this.#buildDirectory): string {\n return this.app.publicPath(join(buildDirectory, this.#manifestFilename))\n }\n\n manifest(buildDirectory = this.#buildDirectory): Manifest {\n const path = this.manifestPath(buildDirectory)\n if (!existsSync(path)) throw new ViteError(`Vite manifest not found at: ${path}`)\n const { mtimeMs } = statSync(path)\n const cached = manifests.get(path)\n if (cached !== undefined && cached.mtimeMs === mtimeMs) return cached.manifest\n const manifest = JSON.parse(readFileSync(path, 'utf8')) as Manifest\n manifests.set(path, { mtimeMs, manifest })\n return manifest\n }\n\n /** URL → the attributes of the preload tags rendered so far (without href), for Link headers. */\n preloadedAssets(): Record<string, string[]> {\n return { ...this.#preloaded }\n }\n\n /** Renders withEntryPoints() (Vite is Htmlable, like Laravel's). */\n toHtml(): string {\n return this.tags(this.#entryPoints).toHtml()\n }\n\n // Internals ------------------------------------------------------------------------------------------------\n\n #hotAsset(path: string): string {\n return `${this.devServerUrl() ?? ''}/${path}`\n }\n\n #assetPath(path: string): string {\n if (this.#assetPathResolver !== undefined) return this.#assetPathResolver(path)\n if (this.app.bound(UrlGenerator)) return this.app.make(UrlGenerator).asset(path)\n const base = this.app.bound(ConfigRepository) ? this.app.make(ConfigRepository).get<string | null>('app.asset_url', null) : null\n return `${(base ?? '').replace(/\\/+$/, '')}/${path.replace(/^\\/+/, '')}`\n }\n\n #chunk(manifest: Manifest, file: string): ManifestChunk {\n const chunk = manifest[file]\n if (chunk === undefined) throw new ViteError(`Unable to locate file in Vite manifest: ${file}.`)\n return chunk\n }\n\n /** Every static import, depth first, each once. */\n #resolveImports(manifest: Manifest, chunk: ManifestChunk, seen = new Set<string>()): string[] {\n const imports: string[] = []\n for (const name of chunk.imports ?? []) {\n if (seen.has(name)) continue\n seen.add(name)\n imports.push(name)\n const imported = manifest[name]\n if (imported !== undefined) imports.push(...this.#resolveImports(manifest, imported, seen))\n }\n return imports\n }\n\n #tagForChunk(src: string, url: string, chunk: ManifestChunk | undefined, manifest: Manifest | undefined): string {\n if (CSS_PATH.test(url)) {\n const attributes = this.#parseAttributes({ rel: 'stylesheet', href: url, nonce: this.#nonce ?? false, ...TRACKED, ...this.#styleAttributes(src, url, chunk, manifest) })\n return `<link ${attributes.join(' ')} />`\n }\n const attributes = this.#parseAttributes({ type: 'module', src: url, nonce: this.#nonce ?? false, ...TRACKED, ...this.#scriptAttributes(src, url, chunk, manifest) })\n return `<script ${attributes.join(' ')}></script>`\n }\n\n #preloadTag(src: string, url: string, chunk: ManifestChunk | undefined, manifest: Manifest): string {\n const css = CSS_PATH.test(url)\n let attributes: TagAttributes = {\n rel: css ? 'preload' : 'modulepreload',\n as: css ? 'style' : 'script',\n href: url,\n nonce: this.#nonce ?? false,\n crossorigin: (css ? this.#styleAttributes(src, url, chunk, manifest) : this.#scriptAttributes(src, url, chunk, manifest)).crossorigin ?? false,\n }\n if (this.#integrityKey !== false) attributes.integrity = (chunk?.[this.#integrityKey] as string | undefined) ?? false\n for (const resolver of this.#preloadResolvers) {\n const resolved = resolver(src, url, chunk, manifest)\n if (resolved === false) return ''\n attributes = { ...attributes, ...resolved }\n }\n const { href: _href, ...rest } = attributes\n this.#preloaded[url] = this.#parseAttributes(rest)\n return `<link ${this.#parseAttributes(attributes).join(' ')} />`\n }\n\n #scriptAttributes(src: string, url: string, chunk: ManifestChunk | undefined, manifest: Manifest | undefined): TagAttributes {\n let attributes: TagAttributes = this.#integrityKey !== false ? { integrity: (chunk?.[this.#integrityKey] as string | undefined) ?? false } : {}\n for (const resolver of this.#scriptResolvers) attributes = { ...attributes, ...resolver(src, url, chunk, manifest) }\n return attributes\n }\n\n #styleAttributes(src: string, url: string, chunk: ManifestChunk | undefined, manifest: Manifest | undefined): TagAttributes {\n let attributes: TagAttributes = this.#integrityKey !== false ? { integrity: (chunk?.[this.#integrityKey] as string | undefined) ?? false } : {}\n for (const resolver of this.#styleResolvers) attributes = { ...attributes, ...resolver(src, url, chunk, manifest) }\n return attributes\n }\n\n /** false/null/undefined are dropped, true is a bare attribute, anything else name=\"value\". */\n #parseAttributes(attributes: TagAttributes): string[] {\n return Object.entries(attributes)\n .filter(([, value]) => value !== false && value !== null && value !== undefined)\n .map(([name, value]) => (value === true ? name : `${name}=\"${escapeAttribute(String(value))}\"`))\n }\n}\n\n/**\n * The Vite instance for the current context: the request's own (scoped, so a CSP nonce stays in its request),\n * else a fresh one for the application (a mail view rendered by a queue worker).\n */\nexport function currentVite(): Vite {\n const container = currentContainer()\n if (container === undefined) throw new ContainerNotAvailableError('Vite')\n if (container.bound(HttpRequest)) return container.make(Vite)\n return new Vite(container.make(ApplicationToken))\n}\n\n/** vite(['resources/js/app.tsx']) → the tags (Laravel's @vite); vite() → the Vite instance. */\nexport function vite(): Vite\nexport function vite(entryPoints: string | string[], buildDirectory?: string): ViteHtml\nexport function vite(entryPoints?: string | string[], buildDirectory?: string): Vite | ViteHtml {\n const instance = currentVite()\n return entryPoints === undefined ? instance : instance.tags(entryPoints, buildDirectory)\n}\n\n/** Laravel's @viteReactRefresh: put it before vite([...]) in the root view of a React app. */\nexport function viteReactRefresh(): ViteHtml | undefined {\n return currentVite().reactRefresh()\n}\n","import type { HttpKernel } from '@orieljs/contracts'\n\ntype Handler = (request: Request) => unknown\n\n/** Wave 0 stand-in for the Http kernel: exact \"METHOD /path\" matching only. Replaced by Wave 1's router. */\nexport class ClosureKernel implements HttpKernel {\n private readonly routes = new Map<string, Handler>()\n\n on(method: string, path: string, handler: Handler): this {\n this.routes.set(`${method.toUpperCase()} ${path}`, handler)\n return this\n }\n\n async handle(request: Request): Promise<Response> {\n const handler = this.routes.get(`${request.method} ${new URL(request.url).pathname}`)\n if (!handler) return new Response('Not Found', { status: 404, headers: { 'content-type': 'text/plain; charset=utf-8' } })\n return toResponse(await handler(request))\n }\n}\n\nfunction toResponse(output: unknown): Response {\n if (output instanceof Response) return output\n if (output === undefined || output === null) return new Response(null, { status: 204 })\n if (typeof output === 'string') return new Response(output, { headers: { 'content-type': 'text/html; charset=utf-8' } })\n return Response.json(output)\n}\n","import type { OrielError } from '@orieljs/contracts'\n\n/** Symfony's HttpException: abort(404), abort(403, 'Nope'). An empty message renders as the status text. */\nexport class HttpException extends Error implements OrielError {\n readonly kind = 'Http' as const\n override readonly name = 'HttpException'\n constructor(\n readonly status: number,\n message = '',\n readonly headers: Record<string, string> = {},\n ) {\n super(message)\n }\n}\n\n/** Carries a ready Response out of deep code: abort(response). The handler returns it as is. */\nexport class HttpResponseException extends Error implements OrielError {\n readonly kind = 'Http' as const\n override readonly name = 'HttpResponseException'\n readonly status: number\n constructor(readonly response: Response) {\n super(`HTTP response exception (${response.status}).`)\n this.status = response.status\n }\n}\n\n/** Http's internal failures (not thrown by this package itself; used by the kernel and error rendering). */\nexport class HttpServerError extends Error implements OrielError {\n readonly kind = 'Server' as const\n readonly status = 500\n override readonly name = 'HttpServerError'\n}\n","import { HttpException } from './errors'\n\n/**\n * Whether a JSON text nests objects and arrays deeper than `maxDepth`, found by scanning (no parsing, no recursion):\n * brackets inside strings don't count. The kernel answers 400 for such bodies (http.max_json_depth) before the\n * recursive input handling (sanitizing, TrimStrings, validation) could overflow the stack.\n */\nexport function exceedsJsonDepth(text: string, maxDepth: number): boolean {\n let depth = 0\n let inString = false\n for (let i = 0; i < text.length; i++) {\n const code = text.charCodeAt(i)\n if (inString) {\n if (code === 92) i++ // a backslash escapes the next character\n else if (code === 34) inString = false\n } else if (code === 34) inString = true\n else if (code === 123 || code === 91) {\n if (++depth > maxDepth) return true\n } else if (code === 125 || code === 93) depth--\n }\n return false\n}\n\n/** Reads a request body into memory, refusing more than `limit` bytes (413), like PHP's post_max_size. */\nexport async function readBody(raw: Request, limit: number | null): Promise<Uint8Array> {\n if (raw.body === null) return new Uint8Array(0)\n const declared = Number(raw.headers.get('content-length') ?? NaN)\n if (limit !== null && Number.isFinite(declared) && declared > limit) {\n await raw.body.cancel()\n throw new HttpException(413, 'Content Too Large')\n }\n const reader = raw.body.getReader()\n const chunks: Uint8Array[] = []\n let size = 0\n for (;;) {\n const { done, value } = await reader.read()\n if (done) break\n size += value.byteLength\n if (limit !== null && size > limit) {\n await reader.cancel()\n throw new HttpException(413, 'Content Too Large')\n }\n chunks.push(value)\n }\n const out = new Uint8Array(size)\n let offset = 0\n for (const chunk of chunks) {\n out.set(chunk, offset)\n offset += chunk.byteLength\n }\n return out\n}\n","import { CookieJar, HttpRequest, Session, type Container } from '@orieljs/contracts'\nimport { currentContainer } from '@orieljs/container'\n\n/** The current container, only when it is a request scope (the kernel binds HttpRequest there). */\nexport function requestScope(): Container | undefined {\n const container = currentContainer()\n return container !== undefined && container.bound(HttpRequest) ? container : undefined\n}\n\nexport function currentRequest(): HttpRequest | undefined {\n return requestScope()?.make(HttpRequest)\n}\n\n/** The request's session, or undefined outside a request or when no Session provider is registered. */\nexport function optionalSession(): Session | undefined {\n const scope = requestScope()\n return scope?.bound(Session) ? scope.make(Session) : undefined\n}\n\nexport function optionalCookieJar(): CookieJar | undefined {\n const scope = requestScope()\n return scope?.bound(CookieJar) ? scope.make(CookieJar) : undefined\n}\n","import type { Cookie, HeadersInit, MessageBag, RedirectResponse } from '@orieljs/contracts'\nimport { currentRequest, optionalCookieJar, optionalSession } from './context'\n\ntype ErrorsInput = Record<string, string | string[]> | MessageBag\n\n/** A Set-Cookie value. `minutes` 0 is a session cookie; a negative value deletes the cookie. */\nfunction serializeCookie(cookie: Cookie): string {\n const parts = [`${encodeURIComponent(cookie.name)}=${encodeURIComponent(cookie.value)}`, `Path=${cookie.path}`]\n if (cookie.domain !== undefined) parts.push(`Domain=${cookie.domain}`)\n if (cookie.secure) parts.push('Secure')\n if (cookie.httpOnly) parts.push('HttpOnly')\n parts.push(`SameSite=${cookie.sameSite.charAt(0).toUpperCase()}${cookie.sameSite.slice(1)}`)\n if (cookie.minutes < 0) parts.push('Max-Age=0', 'Expires=Thu, 01 Jan 1970 00:00:00 GMT')\n else if (cookie.minutes > 0) parts.push(`Max-Age=${Math.round(cookie.minutes * 60)}`)\n return parts.join('; ')\n}\n\n/**\n * Laravel's RedirectResponse. with()/withErrors()/withInput() flash to the request's Session immediately, like\n * Laravel; without a bound Session (an API-only app) they are skipped silently.\n */\nexport class HttpRedirectResponse implements RedirectResponse {\n readonly #headers: Headers\n\n constructor(\n readonly targetUrl: string,\n readonly status = 302,\n headers?: HeadersInit,\n ) {\n this.#headers = new Headers(headers)\n }\n\n with(key: string | Record<string, unknown>, value?: unknown): this {\n const session = optionalSession()\n if (session === undefined) return this\n if (typeof key === 'string') session.flash(key, value)\n else for (const [name, item] of Object.entries(key)) session.flash(name, item)\n return this\n }\n\n /** Flashes `errors` as { [bag]: { field: string[] } }, keeping the other bags already flashed. */\n withErrors(errors: ErrorsInput, bag = 'default'): this {\n const session = optionalSession()\n if (session === undefined) return this\n const source =\n typeof (errors as { toObject?: unknown }).toObject === 'function'\n ? (errors as MessageBag).toObject()\n : (errors as Record<string, string | string[]>)\n const normalized = Object.fromEntries(\n Object.entries(source).map(([field, messages]) => [field, Array.isArray(messages) ? [...messages] : [messages]]),\n )\n const existing = session.get<Record<string, Record<string, string[]>>>('errors', {})\n session.flash('errors', { ...existing, [bag]: normalized })\n return this\n }\n\n /** Flashes `input`, or the current request's input (files are never part of input()). */\n withInput(input?: Record<string, unknown>): this {\n const session = optionalSession()\n if (session === undefined) return this\n session.flashInput(input ?? currentRequest()?.input<Record<string, unknown>>() ?? {})\n return this\n }\n\n /**\n * Always a Set-Cookie header on this response (Laravel's RedirectResponse::withCookie). A bound CookieJar only\n * supplies the defaults (path, domain, secure, same-site); queueing would lose the cookie outside the web group.\n */\n withCookie(name: string, value: string, minutes = 0): this {\n const jar = optionalCookieJar()\n const cookie: Cookie =\n jar !== undefined\n ? jar.make(name, value, minutes)\n : { name, value, minutes, path: '/', secure: false, httpOnly: true, sameSite: 'lax' }\n this.#headers.append('Set-Cookie', serializeCookie(cookie))\n return this\n }\n\n header(name: string, value: string): this {\n this.#headers.set(name, value)\n return this\n }\n\n toResponse(): Response {\n const headers = new Headers(this.#headers)\n headers.set('Location', this.targetUrl)\n return new Response(null, { status: this.status, headers })\n }\n}\n","import { UrlGenerator, type HeadersInit, type Redirector } from '@orieljs/contracts'\nimport { inject } from '@orieljs/container'\nimport { currentRequest, optionalSession } from './context'\nimport { HttpRedirectResponse } from './HttpRedirectResponse'\n\n/**\n * A URL's path, query and fragment: '/dashboard?tab=1' (the intended URL is stored like this). Leading slashes\n * collapse to one, so '//evil.com/x' can never be read back as a protocol-relative URL.\n */\nfunction pathOf(url: string): string {\n let parsed: URL\n try {\n parsed = new URL(url, 'http://localhost')\n } catch {\n return '/'\n }\n return `${parsed.pathname.replace(/^\\/+/, '/')}${parsed.search}${parsed.hash}`\n}\n\n/** Laravel's Redirector. Stateless: the URL generator and session come from the current container. */\nexport class HttpRedirector implements Redirector {\n to(path: string, status = 302, headers?: HeadersInit): HttpRedirectResponse {\n return new HttpRedirectResponse(inject(UrlGenerator).to(path), status, headers)\n }\n\n route(name: string, parameters?: unknown, status = 302): HttpRedirectResponse {\n return new HttpRedirectResponse(inject(UrlGenerator).route(name, parameters), status)\n }\n\n back(fallback?: string, status = 302): HttpRedirectResponse {\n return new HttpRedirectResponse(inject(UrlGenerator).previous(fallback), status)\n }\n\n /** Pulls url.intended from the session (put there by guest()), else goes to `fallback`. */\n intended(fallback = '/', status = 302): HttpRedirectResponse {\n const path = optionalSession()?.pull<string | undefined>('url.intended') ?? fallback\n return this.to(path, status)\n }\n\n away(url: string, status = 302): HttpRedirectResponse {\n return new HttpRedirectResponse(url, status)\n }\n\n /**\n * Remembers where a guest was going (a GET page, else the previous URL), then redirects to `path`. Only the path\n * is stored, so intended() goes back on whichever host serves the app, and never to another site's Referer.\n */\n guest(path: string, status = 302): HttpRedirectResponse {\n const session = optionalSession()\n const request = currentRequest()\n if (session !== undefined) {\n const intended =\n request !== undefined && request.method() === 'GET' && !request.expectsJson()\n ? request.fullUrl()\n : inject(UrlGenerator).previous()\n session.put('url.intended', pathOf(intended))\n }\n return this.to(path, status)\n }\n\n setIntendedUrl(url: string): void {\n optionalSession()?.put('url.intended', url)\n }\n\n refresh(status = 302): HttpRedirectResponse {\n return this.to(currentRequest()?.fullUrl() ?? inject(UrlGenerator).current(), status)\n }\n}\n","/**\n * The socket address of each incoming Request, filled by the server adapters (and by test clients).\n * Kept on globalThis under a Symbol.for key, so a package that can't import @orieljs/http (Testing) can set it.\n */\nconst KEY = Symbol.for('oriel:http.client-address')\nconst store = ((globalThis as unknown as Record<symbol, WeakMap<Request, string> | undefined>)[KEY] ??= new WeakMap<Request, string>())\n\nexport function setClientAddress(request: Request, address: string | undefined): void {\n if (address !== undefined && address !== '') store.set(request, address)\n}\n\nexport function clientAddress(request: Request): string | undefined {\n return store.get(request)\n}\n","import { FilesystemManager, type UploadedFile } from '@orieljs/contracts'\nimport { inject } from '@orieljs/container'\nimport { FileType, Str } from '@orieljs/support'\nimport { extensionFromMime } from './mime'\n\n/** Extensions a stored file never takes from the client's claim alone: the formats the bytes are read for, and what a browser renders or runs. */\nconst NEVER_CLAIMED: ReadonlySet<string> = new Set([\n ...FileType.BINARY_AND_MARKUP_TYPES.flatMap(({ extensions }) => extensions),\n 'jpe', 'svgz', 'xhtml', 'xht', 'shtml', 'xsl', 'xslt', 'mht', 'mhtml', 'js', 'mjs',\n 'rss', 'atom', 'rdf', 'mathml', 'mml', 'xul',\n])\n\n/** A claim is kept only as a plain extension, the same test putFile() applies to the name it writes. */\nconst PLAIN_EXTENSION = /^[a-z0-9]+$/\n\n/** An uploaded file from a multipart body. store()/storeAs() go through the FilesystemManager. */\nexport class FormUploadedFile implements UploadedFile {\n readonly clientName: string\n readonly mimeType: string\n readonly size: number\n\n /**\n * Reads the leading bytes first, so extension(), hashName() and store() name the file by its content. The request\n * builds its uploads this way.\n */\n static async fromFile(file: Blob & { readonly name?: string }): Promise<FormUploadedFile> {\n return new FormUploadedFile(file, FileType.detectFileType(new Uint8Array(await file.slice(0, FileType.SNIFF_BYTES).arrayBuffer())))\n }\n\n constructor(\n private readonly file: Blob & { readonly name?: string },\n private readonly detected?: FileType.DetectedType,\n ) {\n this.clientName = file.name ?? ''\n this.mimeType = file.type === '' ? 'application/octet-stream' : file.type\n this.size = file.size\n }\n\n /**\n * Laravel's extension(): the type the bytes show (guessExtension()), when they were read and match a known format.\n * Text and bytes no format matches keep the client's claim (its MIME type, else its file name) when it is a plain\n * extension, unless it names a format the bytes would have shown or one a browser renders or runs: otherwise 'txt'\n * for text, '' for the rest. Unread (built directly), the client's claim when it is a plain extension, else ''.\n */\n extension(): string {\n const claimed = extensionFromMime(this.mimeType) ?? this.clientExtension()\n const detected = this.detected\n if (detected === undefined) return PLAIN_EXTENSION.test(claimed) ? claimed : ''\n if (detected !== FileType.TEXT && detected.extensions.length > 0) return detected.extensions[0]!\n if (PLAIN_EXTENSION.test(claimed) && !NEVER_CLAIMED.has(claimed)) return claimed\n return detected === FileType.TEXT ? 'txt' : ''\n }\n\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 the guessed extension. */\n hashName(): string {\n const extension = this.extension()\n return extension === '' ? Str.random(40) : `${Str.random(40)}.${extension}`\n }\n\n arrayBuffer(): Promise<ArrayBuffer> {\n return this.file.arrayBuffer()\n }\n\n text(): Promise<string> {\n return this.file.text()\n }\n\n stream(): ReadableStream<Uint8Array> {\n return this.file.stream() as ReadableStream<Uint8Array>\n }\n\n store(directory: string, disk?: string): Promise<string> {\n return inject(FilesystemManager).disk(disk).putFile(directory, this)\n }\n\n storeAs(directory: string, name: string, disk?: string): Promise<string> {\n return inject(FilesystemManager).disk(disk).putFileAs(directory, this, name)\n }\n}\n","/** A small extension ↔ MIME map for uploads and downloads (not exhaustive on purpose). */\nconst TYPES: Record<string, string> = {\n avif: 'image/avif',\n css: 'text/css',\n csv: 'text/csv',\n doc: 'application/msword',\n docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',\n gif: 'image/gif',\n gz: 'application/gzip',\n html: 'text/html',\n ico: 'image/vnd.microsoft.icon',\n jpg: 'image/jpeg',\n js: 'text/javascript',\n map: 'application/json',\n json: 'application/json',\n md: 'text/markdown',\n mp3: 'audio/mpeg',\n mp4: 'video/mp4',\n otf: 'font/otf',\n pdf: 'application/pdf',\n png: 'image/png',\n svg: 'image/svg+xml',\n ttf: 'font/ttf',\n txt: 'text/plain',\n wasm: 'application/wasm',\n webm: 'video/webm',\n webp: 'image/webp',\n woff: 'font/woff',\n woff2: 'font/woff2',\n xls: 'application/vnd.ms-excel',\n xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',\n xml: 'application/xml',\n zip: 'application/zip',\n}\nconst ALIASES: Record<string, string> = { jpeg: 'jpg', htm: 'html', mjs: 'js', text: 'txt' }\nconst EXTENSIONS = Object.fromEntries(Object.entries(TYPES).map(([extension, type]) => [type, extension]))\n\n/** 'report.PDF' or 'pdf' → 'application/pdf'; unknown → 'application/octet-stream'. */\nexport function mimeFromExtension(pathOrExtension: string): string {\n const extension = pathOrExtension.slice(pathOrExtension.lastIndexOf('.') + 1).toLowerCase()\n return TYPES[ALIASES[extension] ?? extension] ?? 'application/octet-stream'\n}\n\n/** 'image/jpeg; charset=…' → 'jpg'; unknown → undefined. */\nexport function extensionFromMime(type: string): string | undefined {\n return EXTENSIONS[type.split(';')[0]!.trim().toLowerCase()]\n}\n","import {\n AuthFactory,\n CurrentRoute,\n Session,\n ValidationFactory,\n type HttpRequest,\n type InferValidatedType,\n type Rules,\n type UploadedFile,\n} from '@orieljs/contracts'\nimport { currentContainer, inject } from '@orieljs/container'\nimport { Arr, Str, type Stringable } from '@orieljs/support'\nimport { exceedsJsonDepth, readBody } from './body'\nimport { HttpException } from './errors'\nimport { clientAddress } from './clientAddress'\nimport { FormUploadedFile } from './FormUploadedFile'\nimport { fromEntries, isBlank, isPlainObject, mergeRecursive, sanitize, transformLeaves } from './input'\n\ntype Tree = Record<string, unknown>\n\nexport interface IncomingRequestOptions {\n /** Proxy addresses whose X-Forwarded-* headers are believed: exact IPs, IPv4 CIDRs, or '*'. */\n trustedProxies?: readonly string[]\n /** Largest request body in bytes before a 413 (config http.max_body_size); null is unlimited. Default 8 MB. */\n maxBodySize?: number | null\n /** Deepest nesting of objects and arrays in a JSON body before a 400 (config http.max_json_depth); null is unlimited. Default 512. */\n maxJsonDepth?: number | null\n}\n\nconst TRUE_VALUES = new Set(['1', 'true', 'on', 'yes'])\n\nconst normalizeIp = (ip: string): string => ip.trim().replace(/^::ffff:(\\d+\\.\\d+\\.\\d+\\.\\d+)$/i, '$1')\n\nfunction ipv4ToNumber(ip: string): number | undefined {\n const parts = ip.split('.')\n if (parts.length !== 4 || parts.some((part) => !/^\\d{1,3}$/.test(part) || Number(part) > 255)) return undefined\n return parts.reduce((total, part) => total * 256 + Number(part), 0)\n}\n\n/** Exact match, IPv4 CIDR ('10.0.0.0/8') or '*'. */\nexport function ipMatches(ip: string, patterns: readonly string[]): boolean {\n const address = normalizeIp(ip)\n return patterns.some((pattern) => {\n if (pattern === '*') return true\n if (!pattern.includes('/')) return normalizeIp(pattern) === address\n const [range, bits] = pattern.split('/') as [string, string]\n const base = ipv4ToNumber(range)\n const value = ipv4ToNumber(address)\n const size = Number(bits)\n if (base === undefined || value === undefined || !(size >= 0 && size <= 32)) return false\n const mask = size === 0 ? 0 : (~0 << (32 - size)) >>> 0\n return ((base & mask) >>> 0) === ((value & mask) >>> 0)\n })\n}\n\n/**\n * The HttpRequest implementation (Laravel's Illuminate\\Http\\Request). The kernel calls load() once, before any\n * middleware, so every accessor below is synchronous.\n *\n * `http.max_body_size` applies to the bodies this class parses (JSON, urlencoded and multipart). A handler that reads\n * `request.raw` directly bypasses it and must enforce its own limit.\n */\nexport class IncomingRequest implements HttpRequest {\n readonly #url: URL\n readonly #trustedProxies: readonly string[]\n readonly #maxBodySize: number | null\n readonly #maxJsonDepth: number | null\n #query: Tree\n #body: Tree = {}\n #files: Tree = {}\n #content = ''\n #method: string\n #cookies: Record<string, string> | undefined\n #loading: Promise<this> | undefined\n #userResolver: ((guard?: string) => unknown) | undefined\n\n constructor(\n readonly raw: Request,\n options: IncomingRequestOptions = {},\n ) {\n this.#url = new URL(raw.url)\n this.#trustedProxies = options.trustedProxies ?? []\n this.#maxBodySize = options.maxBodySize === undefined ? 8 * 1024 * 1024 : options.maxBodySize\n this.#maxJsonDepth = options.maxJsonDepth === undefined ? 512 : options.maxJsonDepth\n this.#query = fromEntries(this.#url.searchParams.entries())\n this.#method = raw.method.toUpperCase()\n }\n\n /** Reads and parses the body (JSON, urlencoded or multipart) once, then applies method spoofing. */\n load(): Promise<this> {\n return (this.#loading ??= this.#load())\n }\n\n async #load(): Promise<this> {\n const method = this.raw.method.toUpperCase()\n if (method !== 'GET' && method !== 'HEAD' && this.raw.body !== null) {\n const type = (this.raw.headers.get('content-type') ?? '').toLowerCase()\n const isJson = type.includes('/json') || type.includes('+json')\n const isUrlencoded = type.startsWith('application/x-www-form-urlencoded')\n const isMultipart = type.startsWith('multipart/form-data')\n if (isJson || isUrlencoded || isMultipart) {\n // Size (413) and depth (400) errors must reach the caller; only a malformed body reads as empty input, as in Laravel.\n const bytes = await readBody(this.raw, this.#maxBodySize)\n if (isJson && this.#maxJsonDepth !== null && exceedsJsonDepth(new TextDecoder().decode(bytes), this.#maxJsonDepth)) {\n throw new HttpException(400, 'The request body is nested too deeply.')\n }\n try {\n if (isJson) {\n this.#content = new TextDecoder().decode(bytes)\n this.#body = this.#parseJson(this.#content)\n } else if (isUrlencoded) {\n this.#content = new TextDecoder().decode(bytes)\n this.#body = fromEntries(new URLSearchParams(this.#content).entries())\n } else {\n await this.#parseForm(await new Response(bytes as Uint8Array<ArrayBuffer>, { headers: { 'content-type': this.raw.headers.get('content-type') ?? '' } }).formData())\n }\n } catch {\n // A malformed body reads as empty input, as in Laravel.\n }\n }\n }\n if (method === 'POST') {\n const override =\n this.raw.headers.get('x-http-method-override') ?? this.#string(this.#body._method) ?? this.#string(this.#query._method)\n const spoofed = override?.toUpperCase()\n if (spoofed !== undefined && /^[A-Z]+$/.test(spoofed) && !['GET', 'HEAD', 'CONNECT', 'TRACE'].includes(spoofed)) {\n this.#method = spoofed\n }\n }\n return this\n }\n\n #parseJson(text: string): Tree {\n let parsed: unknown\n try {\n parsed = JSON.parse(text)\n } catch {\n return {}\n }\n if (Array.isArray(parsed)) return sanitize({ ...parsed }) as Tree\n return isPlainObject(parsed) ? (sanitize(parsed) as Tree) : {}\n }\n\n async #parseForm(form: FormData): Promise<void> {\n const fields: Array<[string, unknown]> = []\n const files: Array<[string, unknown]> = []\n for (const [name, value] of form.entries()) {\n if (typeof value === 'string') fields.push([name, value])\n // A file input left empty arrives as filename=\"\" with no bytes (PHP's UPLOAD_ERR_NO_FILE).\n else if (!((value.name ?? '') === '' && value.size === 0)) files.push([name, await FormUploadedFile.fromFile(value)])\n }\n this.#body = fromEntries(fields)\n this.#files = fromEntries(files)\n }\n\n #string(value: unknown): string | undefined {\n return typeof value === 'string' && value !== '' ? value : undefined\n }\n\n method(): string {\n return this.#method\n }\n\n isMethod(method: string): boolean {\n return this.#method === method.toUpperCase()\n }\n\n /** The scheme and host, honouring X-Forwarded-Proto/Host from trusted proxies. */\n root(): string {\n const trusted = this.#fromTrustedProxy()\n const proto = trusted ? this.raw.headers.get('x-forwarded-proto')?.split(',')[0]?.trim() : undefined\n const host = trusted ? this.raw.headers.get('x-forwarded-host')?.split(',')[0]?.trim() : undefined\n const scheme = proto === 'https' || proto === 'http' ? proto : this.#url.protocol.slice(0, -1)\n return `${scheme}://${host !== undefined && host !== '' ? host : this.#url.host}`\n }\n\n /** The URL without the query string or a trailing slash. */\n url(): string {\n return `${this.root()}${this.#url.pathname}`.replace(/\\/+$/, '')\n }\n\n fullUrl(): string {\n return this.#url.search === '' ? this.url() : `${this.url()}${this.#url.search}`\n }\n\n /** 'posts/1', or '/' for the root. */\n path(): string {\n const trimmed = this.#url.pathname.replace(/^\\/+|\\/+$/g, '')\n return trimmed === '' ? '/' : trimmed\n }\n\n decodedPath(): string {\n try {\n return decodeURIComponent(this.path())\n } catch {\n return this.path()\n }\n }\n\n secure(): boolean {\n return this.root().startsWith('https:')\n }\n\n /** request.is('admin/*'): wildcard match against the decoded path. */\n is(...patterns: string[]): boolean {\n const path = this.decodedPath()\n return patterns.some((pattern) => {\n const trimmed = pattern.replace(/^\\/+|\\/+$/g, '')\n return Str.is(trimmed === '' ? '/' : trimmed, path)\n })\n }\n\n routeIs(...names: string[]): boolean {\n const name = this.#currentRoute()?.route.getName()\n return name !== undefined && names.some((pattern) => Str.is(pattern, name))\n }\n\n header(name: string): string | undefined\n header(name: string, defaultValue: string): string\n header(name: string, defaultValue?: string): string | undefined {\n return this.raw.headers.get(name) ?? defaultValue\n }\n\n bearerToken(): string | undefined {\n const header = this.header('authorization', '')\n const position = header.toLowerCase().lastIndexOf('bearer ')\n if (position === -1) return undefined\n const token = header.slice(position + 7).split(',')[0]!.trim()\n return token === '' ? undefined : token\n }\n\n userAgent(): string | undefined {\n return this.header('user-agent')\n }\n\n /** The socket address, or the right-most untrusted X-Forwarded-For entry when the socket is a trusted proxy. */\n ip(): string | undefined {\n const socket = clientAddress(this.raw)\n if (socket === undefined) return undefined\n const address = normalizeIp(socket)\n if (!this.#fromTrustedProxy()) return address\n const chain = (this.raw.headers.get('x-forwarded-for') ?? '')\n .split(',')\n .map((entry) => normalizeIp(entry))\n .filter((entry) => entry !== '')\n for (let i = chain.length - 1; i >= 0; i--) if (!ipMatches(chain[i]!, this.#trustedProxies)) return chain[i]\n return chain[0] ?? address\n }\n\n #fromTrustedProxy(): boolean {\n const socket = clientAddress(this.raw)\n return socket !== undefined && this.#trustedProxies.length > 0 && ipMatches(socket, this.#trustedProxies)\n }\n\n ajax(): boolean {\n return this.header('x-requested-with') === 'XMLHttpRequest'\n }\n\n pjax(): boolean {\n return this.header('x-pjax') === 'true'\n }\n\n /** The first Accept type is JSON. */\n wantsJson(): boolean {\n const first = this.header('accept', '').split(',')[0]!.trim()\n return first.includes('/json') || first.includes('+json')\n }\n\n /** Laravel: (ajax and not pjax and accepts anything) or wantsJson. */\n expectsJson(): boolean {\n const first = this.header('accept', '').split(',')[0]!.split(';')[0]!.trim()\n const acceptsAny = first === '' || first === '*/*' || first === '*'\n return (this.ajax() && !this.pjax() && acceptsAny) || this.wantsJson()\n }\n\n /** The raw body text for JSON and urlencoded requests ('' otherwise; the raw stream stays unread for other types). */\n content(): string {\n return this.#content\n }\n\n query<T = unknown>(key?: string, defaultValue?: T): T {\n return Arr.get<T>(this.#query, key, defaultValue)\n }\n\n /** Body wins over the query string (PHP's $body + $query). Files are not input. */\n input<T = unknown>(key?: string, defaultValue?: T): T {\n return Arr.get<T>({ ...this.#query, ...this.#body }, key, defaultValue)\n }\n\n /** Input plus files (array_replace_recursive). */\n all(): Record<string, unknown> {\n return mergeRecursive({ ...this.#query, ...this.#body }, this.#files)\n }\n\n only(...keys: Array<string | string[]>): Record<string, unknown> {\n const all = this.all()\n const out: Tree = {}\n for (const key of keys.flat()) if (Arr.has(all, key)) Arr.set(out, key, Arr.get(all, key))\n return out\n }\n\n except(...keys: Array<string | string[]>): Record<string, unknown> {\n const all = structuredCloneInput(this.all())\n for (const key of keys.flat()) Arr.forget(all, key)\n return all\n }\n\n has(...keys: Array<string | string[]>): boolean {\n const all = this.all()\n return keys.flat().every((key) => Arr.has(all, key))\n }\n\n hasAny(...keys: Array<string | string[]>): boolean {\n const all = this.all()\n return keys.flat().some((key) => Arr.has(all, key))\n }\n\n missing(...keys: Array<string | string[]>): boolean {\n return !this.has(...keys)\n }\n\n filled(key: string): boolean {\n return !isBlank(Arr.get(this.all(), key))\n }\n\n /** Laravel's string(): the input as a Stringable (the default when it is missing or null): request().string('q').trim(). */\n string(key: string, defaultValue = ''): Stringable {\n const value = this.input<unknown>(key)\n return Str.of(value === undefined || value === null ? defaultValue : value)\n }\n\n /** Laravel's str(): string() under its short name. */\n str(key: string, defaultValue = ''): Stringable {\n return this.string(key, defaultValue)\n }\n\n /** PHP's FILTER_VALIDATE_BOOLEAN: '1', 'true', 'on', 'yes' (any case) and true are true. */\n boolean(key: string, defaultValue = false): boolean {\n const value = this.input<unknown>(key)\n if (value === undefined) return defaultValue\n if (typeof value === 'boolean') return value\n if (typeof value === 'number') return value === 1\n return typeof value === 'string' && TRUE_VALUES.has(value.trim().toLowerCase())\n }\n\n /** PHP's intval: leading digits, else 0. */\n integer(key: string, defaultValue = 0): number {\n const value = this.input<unknown>(key)\n if (value === undefined) return defaultValue\n if (typeof value === 'number') return Number.isFinite(value) ? Math.trunc(value) : 0\n if (typeof value === 'boolean') return value ? 1 : 0\n const parsed = Number.parseInt(String(value).trim(), 10)\n return Number.isNaN(parsed) ? 0 : parsed\n }\n\n /** Adds or replaces top-level body values. */\n merge(values: Record<string, unknown>): this {\n this.#body = { ...this.#body, ...(sanitize(values) as Tree) }\n return this\n }\n\n /** Rewrites every scalar in the query and the body (TrimStrings and ConvertEmptyStringsToNull use this). */\n transformInput(transform: (key: string, value: unknown) => unknown): this {\n this.#query = transformLeaves(this.#query, transform)\n this.#body = transformLeaves(this.#body, transform)\n return this\n }\n\n file(key: string): UploadedFile | undefined {\n const value = Arr.get<unknown>(this.#files, key)\n return value instanceof FormUploadedFile ? value : undefined\n }\n\n hasFile(key: string): boolean {\n const value = Arr.get<unknown>(this.#files, key)\n return value instanceof FormUploadedFile || (Array.isArray(value) && value.some((item) => item instanceof FormUploadedFile))\n }\n\n allFiles(): Record<string, unknown> {\n return { ...this.#files }\n }\n\n cookie(name: string): string | undefined {\n return this.cookies()[name]\n }\n\n cookies(): Record<string, string> {\n if (this.#cookies === undefined) {\n const cookies: Record<string, string> = {}\n for (const part of (this.raw.headers.get('cookie') ?? '').split(';')) {\n const index = part.indexOf('=')\n if (index === -1) continue\n const name = part.slice(0, index).trim()\n if (name === '' || Object.hasOwn(cookies, name)) continue\n let value = part.slice(index + 1).trim()\n if (value.startsWith('\"') && value.endsWith('\"')) value = value.slice(1, -1)\n try {\n cookies[name] = decodeURIComponent(value)\n } catch {\n cookies[name] = value\n }\n }\n this.#cookies = cookies\n }\n return { ...this.#cookies }\n }\n\n /** Replaces the parsed cookies (EncryptCookies calls this after decrypting). */\n setCookies(cookies: Record<string, string>): void {\n this.#cookies = { ...cookies }\n }\n\n /** One route parameter (after model binding), or all of them. */\n route<T = unknown>(key?: string): T {\n const parameters = this.#currentRoute()?.parameters ?? {}\n return (key === undefined ? { ...parameters } : parameters[key]) as T\n }\n\n session(): Session {\n return inject(Session)\n }\n\n /**\n * The signed-in user, through the resolver Auth sets, else the current scope's guard (the default, or `guard`).\n * The guard keeps the user it found, so it is looked up once per request. Undefined for a guest or without auth.\n */\n async user<T = unknown>(guard?: string): Promise<T | undefined> {\n if (this.#userResolver !== undefined) return (await this.#userResolver(guard)) as T | undefined\n const container = currentContainer()\n if (container === undefined || !container.bound(AuthFactory)) return undefined\n return (await container.make(AuthFactory).guard(guard).user()) as T | undefined\n }\n\n setUserResolver(resolver: (guard?: string) => unknown): void {\n this.#userResolver = resolver\n }\n\n /**\n * Validates all() through the ValidationFactory; throws its Validation error on failure. The data is typed from the\n * rules: `validate({ title: 'required|string' })` is `{ title: string }`.\n */\n validate<const R extends Rules>(\n rules: R,\n messages?: Record<string, string>,\n attributes?: Record<string, string>,\n ): Promise<InferValidatedType<R>> {\n return inject(ValidationFactory).make(this.all(), rules, messages, attributes).validated<InferValidatedType<R>>()\n }\n\n #currentRoute() {\n const container = currentContainer()\n return container?.bound(CurrentRoute) ? container.make(CurrentRoute) : undefined\n }\n}\n\n/** A copy deep enough for except() to forget nested keys without touching the request. */\nfunction structuredCloneInput(tree: Tree): Tree {\n const out: Tree = {}\n for (const [key, value] of Object.entries(tree)) {\n out[key] = isPlainObject(value) ? structuredCloneInput(value) : Array.isArray(value) ? [...value] : value\n }\n return out\n}\n","/** Helpers for request input: PHP-style bracket keys, safe cloning (no prototype pollution) and blank checks. */\n\ntype Tree = Record<string, unknown>\n\nconst FORBIDDEN = new Set(['__proto__', 'prototype', 'constructor'])\n\n/** Keys PHP treats as integers: '0', '7', '42' (not '07' or '-1'). */\nconst INTEGER_KEY = /^(?:0|[1-9]\\d*)$/\n\n// Duplicated in Routing's BaseUrlGenerator.ts on purpose: Http, Routing and Pipeline may not import each other.\nexport const isPlainObject = (value: unknown): value is Tree => {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return false\n const prototype = Object.getPrototypeOf(value) as unknown\n return prototype === Object.prototype || prototype === null\n}\n\n/** 'user[name]' → ['user', 'name']; 'tags[]' → ['tags', '']; a malformed key stays whole. */\nexport function parseBracketKey(name: string): string[] {\n const open = name.indexOf('[')\n if (open <= 0 || !name.endsWith(']')) return [name]\n const segments = [name.slice(0, open)]\n const rest = name.slice(open)\n const matches = rest.match(/\\[[^[\\]]*\\]/g)\n if (matches === null || matches.join('') !== rest) return [name]\n for (const match of matches) segments.push(match.slice(1, -1))\n return segments\n}\n\n/** Objects whose keys are exactly 0..n-1 become arrays, recursively (PHP arrays → JS lists). */\nexport function normalizeLists(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(normalizeLists)\n if (!isPlainObject(value)) return value\n const keys = Object.keys(value)\n const out: Tree = {}\n for (const key of keys) out[key] = normalizeLists(value[key])\n if (keys.length > 0 && keys.every((key, index) => key === String(index))) return keys.map((key) => out[key])\n return out\n}\n\n/**\n * Builds nested input from flat form entries, PHP style: 'user[name]', 'tags[]', 'a[b][]'.\n * Keys containing __proto__/prototype/constructor are dropped.\n */\nexport function fromEntries(entries: Iterable<readonly [string, unknown]>): Tree {\n const root: Tree = {}\n // The next '[]' index per node, kept as PHP does (one past the highest integer key) so appending stays O(1).\n const nextIndex = new WeakMap<Tree, number>()\n for (const [name, value] of entries) {\n const segments = parseBracketKey(name)\n if (segments.some((segment) => FORBIDDEN.has(segment))) continue\n let node = root\n for (let i = 0; i < segments.length; i++) {\n let segment = segments[i]!\n const next = nextIndex.get(node) ?? 0\n if (segment === '') {\n segment = String(next)\n nextIndex.set(node, next + 1)\n } else if (INTEGER_KEY.test(segment) && Number(segment) >= next) {\n nextIndex.set(node, Number(segment) + 1)\n }\n if (i === segments.length - 1) {\n node[segment] = value\n break\n }\n if (!isPlainObject(node[segment])) node[segment] = {}\n node = node[segment] as Tree\n }\n }\n return normalizeLists(root) as Tree\n}\n\n/** Deep copy of parsed JSON without dangerous keys (JSON.parse creates an own \"__proto__\" property). */\nexport function sanitize(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(sanitize)\n if (!isPlainObject(value)) return value\n const out: Tree = {}\n for (const [key, item] of Object.entries(value)) if (!FORBIDDEN.has(key)) out[key] = sanitize(item)\n return out\n}\n\n/** array_replace_recursive: `override` wins, nested plain objects merge. */\nexport function mergeRecursive(base: Tree, override: Tree): Tree {\n const out: Tree = { ...base }\n for (const [key, value] of Object.entries(override)) {\n if (FORBIDDEN.has(key)) continue\n const current = out[key]\n out[key] =\n (isPlainObject(current) || Array.isArray(current)) && (isPlainObject(value) || Array.isArray(value))\n ? normalizeLists(mergeRecursive({ ...current } as Tree, { ...value } as Tree))\n : value\n }\n return out\n}\n\n/** Laravel's blank(): null, undefined, whitespace-only strings, and empty arrays/objects. */\nexport function isBlank(value: unknown): boolean {\n if (value === null || value === undefined) return true\n if (typeof value === 'string') return value.trim() === ''\n if (Array.isArray(value)) return value.length === 0\n if (isPlainObject(value)) return Object.keys(value).length === 0\n return false\n}\n\n/** Applies `transform(dottedKey, value)` to every scalar leaf, inside nested objects and lists; the result replaces the leaf. */\nexport function transformLeaves(tree: Tree, transform: (key: string, value: unknown) => unknown, prefix = ''): Tree {\n const out: Tree = {}\n for (const [key, value] of Object.entries(tree)) out[key] = transformValue(`${prefix}${key}`, value, transform)\n return out\n}\n\nfunction transformValue(path: string, value: unknown, transform: (key: string, value: unknown) => unknown): unknown {\n if (Array.isArray(value)) return value.map((item, index) => transformValue(`${path}.${index}`, item, transform))\n if (isPlainObject(value)) return transformLeaves(value, transform, `${path}.`)\n return transform(path, value)\n}\n","import {\n HttpRequest,\n Redirector,\n ResponseFactory,\n UrlGenerator,\n type BodyInit,\n type HeadersInit,\n type RedirectResponse,\n type RouteArguments,\n type RouteName,\n} from '@orieljs/contracts'\nimport { inject } from '@orieljs/container'\nimport { HttpException, HttpResponseException } from './errors'\nimport type { IncomingRequest } from './IncomingRequest'\n\n/**\n * request() → the current request (Laravel's Illuminate\\Http\\Request: the HttpRequest contract plus its extras, such\n * as string()); request('key', default) → its input.\n */\nexport function request(): IncomingRequest\nexport function request<T = unknown>(key: string, defaultValue?: T): T\nexport function request(key?: string, defaultValue?: unknown): unknown {\n const current = inject(HttpRequest)\n return key === undefined ? current : current.input(key, defaultValue)\n}\n\n/** response() → the ResponseFactory; response(content, status, headers) → a Response. */\nexport function response(): ResponseFactory\nexport function response(content: BodyInit | null, status?: number, headers?: HeadersInit): Response\nexport function response(content?: BodyInit | null, status?: number, headers?: HeadersInit): ResponseFactory | Response {\n const factory = inject(ResponseFactory)\n return content === undefined ? factory : factory.make(content, status, headers)\n}\n\n/** The Redirector with its route() typed by the generated route names and their parameters. */\nexport type TypedRedirector = Omit<Redirector, 'route'> & {\n route<N extends RouteName>(name: N, ...args: RouteArguments<N, [status?: number]>): RedirectResponse\n}\n\n/** redirect() → the Redirector; redirect('/path', status) → a RedirectResponse. */\nexport function redirect(): TypedRedirector\nexport function redirect(to: string, status?: number): RedirectResponse\nexport function redirect(to?: string, status?: number): TypedRedirector | RedirectResponse {\n const redirector = inject(Redirector)\n return to === undefined ? redirector : redirector.to(to, status)\n}\n\n/** Redirect to the previous URL (same argument order as Redirector.back()). */\nexport function back(fallback?: string, status?: number): RedirectResponse {\n return inject(Redirector).back(fallback, status)\n}\n\n/** url() → the UrlGenerator; url('/path', query, absolute) → a URL. */\nexport function url(): UrlGenerator\nexport function url(path: string, query?: Record<string, unknown>, absolute?: boolean): string\nexport function url(path?: string, query?: Record<string, unknown>, absolute?: boolean): UrlGenerator | string {\n const generator = inject(UrlGenerator)\n return path === undefined ? generator : generator.to(path, query, absolute)\n}\n\n/**\n * The URL of a named route: route('posts.show', post), route('posts.show', { post, page: 2 }). Once `oriel\n * route:types` has run, the name and the route's parameters are checked.\n */\nexport function route<N extends RouteName>(name: N, ...args: RouteArguments<N>): string {\n const [parameters, absolute] = args as [parameters?: unknown, absolute?: boolean]\n return inject(UrlGenerator).route(name, parameters, absolute)\n}\n\n/** abort(404), abort(403, 'Nope', headers), or abort(response) to send a ready response. */\nexport function abort(status: number | Response, message = '', headers: Record<string, string> = {}): never {\n if (status instanceof Response) throw new HttpResponseException(status)\n throw new HttpException(status, message, headers)\n}\n\nexport function abortIf(condition: unknown, status: number | Response, message = '', headers: Record<string, string> = {}): void {\n if (condition) abort(status, message, headers)\n}\n\nexport function abortUnless(condition: unknown, status: number | Response, message = '', headers: Record<string, string> = {}): void {\n if (!condition) abort(status, message, headers)\n}\n","import { createReadStream } from 'node:fs'\nimport { stat } from 'node:fs/promises'\nimport { basename } from 'node:path'\nimport { Readable } from 'node:stream'\nimport { ViewFactory, type BodyInit, type HeadersInit, type ResponseFactory } from '@orieljs/contracts'\nimport { inject } from '@orieljs/container'\nimport { HttpException } from './errors'\nimport { mimeFromExtension } from './mime'\n\n/** 'attachment; filename=\"report.pdf\"' plus filename* for non-ASCII names (RFC 6266). */\nexport function contentDisposition(type: 'attachment' | 'inline', name: string): string {\n const fallback = name.replace(/[^\\x20-\\x7e]/g, '_').replace(/[\"\\\\]/g, '\\\\$&')\n const header = `${type}; filename=\"${fallback}\"`\n return /^[\\x20-\\x7e]*$/.test(name) ? header : `${header}; filename*=UTF-8''${encodeURIComponent(name)}`\n}\n\n/** Laravel's ResponseFactory (the response() helper). */\nexport class HttpResponseFactory implements ResponseFactory {\n /** Strings default to text/html; charset=utf-8, as in Laravel. */\n make(content: BodyInit | null = null, status = 200, headers?: HeadersInit): Response {\n const merged = new Headers(headers)\n if (typeof content === 'string' && !merged.has('content-type')) merged.set('content-type', 'text/html; charset=utf-8')\n return new Response(content, { status, headers: merged })\n }\n\n json(data: unknown, status = 200, headers?: HeadersInit): Response {\n const merged = new Headers(headers)\n if (!merged.has('content-type')) merged.set('content-type', 'application/json')\n return new Response(JSON.stringify(data === undefined ? null : data), { status, headers: merged })\n }\n\n noContent(status = 204): Response {\n return new Response(null, { status })\n }\n\n /** Renders a view (through the ViewFactory) into an HTML response. */\n async view(name: string, data: Record<string, unknown> = {}, status = 200, headers?: HeadersInit): Promise<Response> {\n const html = await inject(ViewFactory).make(name, data).render()\n return this.make(html, status, headers)\n }\n\n /** Streams a file as an attachment. A missing file is a 404. */\n download(path: string, name = basename(path), headers?: HeadersInit): Promise<Response> {\n return this.#file(path, 'attachment', name, headers)\n }\n\n /** Streams a file for the browser to display (Laravel's response()->file()). */\n file(path: string, headers?: HeadersInit): Promise<Response> {\n return this.#file(path, 'inline', basename(path), headers)\n }\n\n stream(body: ReadableStream, status = 200, headers?: HeadersInit): Response {\n return new Response(body, { status, headers })\n }\n\n async #file(path: string, disposition: 'attachment' | 'inline', name: string, headers?: HeadersInit): Promise<Response> {\n const info = await stat(path).catch(() => undefined)\n // No file path in the message: HTTP error messages are shown to clients.\n if (info === undefined || !info.isFile()) throw new HttpException(404)\n const merged = new Headers(headers)\n if (!merged.has('content-type')) merged.set('content-type', mimeFromExtension(name))\n merged.set('content-length', String(info.size))\n merged.set('content-disposition', contentDisposition(disposition, name))\n const body = Readable.toWeb(createReadStream(path)) as ReadableStream<Uint8Array>\n return new Response(body, { status: 200, headers: merged })\n }\n}\n","import {\n ConfigRepository,\n CurrentRoute,\n ExceptionHandler,\n HttpRequest,\n PipelineFactory,\n Router,\n type Application,\n type Container,\n type HttpKernel,\n type Middleware,\n type MiddlewareClass,\n} from '@orieljs/contracts'\nimport { currentContainer } from '@orieljs/container'\nimport { HttpServerError } from './errors'\nimport { IncomingRequest } from './IncomingRequest'\nimport { ConvertEmptyStringsToNull } from './middleware/ConvertEmptyStringsToNull'\nimport { TrimStrings } from './middleware/TrimStrings'\n\ninterface RequestState {\n readonly scope: Container\n readonly request: IncomingRequest\n readonly middleware: Middleware[]\n}\n\n/** The plain-text 500 the kernel falls back to. Exported so the server adapters can reuse it. */\nexport const plainServerError = (): Response =>\n new Response('Server Error', { status: 500, headers: { 'content-type': 'text/plain; charset=utf-8' } })\n\n/**\n * Laravel's Http Kernel: wraps the raw Request, binds it in the request scope, loads the body, then sends it through\n * the global middleware to the router. Every stage renders its own errors through the ExceptionHandler.\n */\nexport class Kernel implements HttpKernel {\n #middleware: MiddlewareClass[] = [TrimStrings, ConvertEmptyStringsToNull]\n readonly #requests = new WeakMap<Request, RequestState>()\n\n constructor(protected readonly app: Application) {}\n\n getGlobalMiddleware(): MiddlewareClass[] {\n return [...this.#middleware]\n }\n\n setGlobalMiddleware(middleware: MiddlewareClass[]): this {\n this.#middleware = [...middleware]\n return this\n }\n\n appendMiddleware(...middleware: MiddlewareClass[]): this {\n for (const cls of middleware) if (!this.#middleware.includes(cls)) this.#middleware.push(cls)\n return this\n }\n\n prependMiddleware(...middleware: MiddlewareClass[]): this {\n for (const cls of [...middleware].reverse()) if (!this.#middleware.includes(cls)) this.#middleware.unshift(cls)\n return this\n }\n\n hasMiddleware(middleware: MiddlewareClass): boolean {\n return this.#middleware.includes(middleware)\n }\n\n /** Runs in the current request scope (Application.handle() opens one); called directly, it opens its own. */\n handle(raw: Request): Promise<Response> {\n const current = currentContainer()\n const scope = current !== undefined && current !== this.app ? current : this.app.createScope()\n return scope.run(() => this.#handle(raw, scope))\n }\n\n async #handle(raw: Request, scope: Container): Promise<Response> {\n let request: IncomingRequest | undefined\n let response: Response\n try {\n request = new IncomingRequest(raw, {\n trustedProxies: this.#trustedProxies(),\n maxBodySize: this.#maxBodySize(),\n maxJsonDepth: this.#maxJsonDepth(),\n })\n scope.instance(HttpRequest, request)\n const state: RequestState = { scope, request, middleware: [] }\n this.#requests.set(raw, state)\n await request.load()\n response = await this.#sendThroughGlobal(state)\n } catch (error) {\n request ??= this.#bareRequest(scope, raw)\n if (request !== undefined) {\n response = await this.#renderLast(scope, request, error)\n } else {\n await this.#report(scope, error)\n response = plainServerError()\n }\n }\n // HEAD: same status and headers as GET, no body. Cancel the dropped body so an open file stream is released.\n if (raw.method.toUpperCase() === 'HEAD' && response.body !== null) {\n await response.body.cancel().catch(() => undefined)\n response = new Response(null, { status: response.status, statusText: response.statusText, headers: response.headers })\n }\n return response\n }\n\n /** The request without options, for rendering an error raised while the real one was being built. */\n #bareRequest(scope: Container, raw: Request): IncomingRequest | undefined {\n try {\n const request = new IncomingRequest(raw)\n scope.instance(HttpRequest, request)\n return request\n } catch {\n return undefined\n }\n }\n\n /** Runs terminate() on the global and route middleware (inside the request's scope), then Application.terminate(), inside the same scope, so terminating callbacks see the request's bindings. */\n async terminate(raw: Request, response: Response): Promise<void> {\n const state = this.#requests.get(raw)\n if (state !== undefined) {\n this.#requests.delete(raw)\n await state.scope.run(async () => {\n const route = state.scope.bound(CurrentRoute) ? state.scope.make(CurrentRoute).middleware : []\n for (const middleware of [...state.middleware, ...route]) {\n if (typeof middleware.terminate !== 'function') continue\n try {\n await middleware.terminate(state.request, response)\n } catch (error) {\n await this.#report(state.scope, error)\n }\n }\n await this.app.terminate()\n })\n return\n }\n await this.app.terminate()\n }\n\n #sendThroughGlobal(state: RequestState): Promise<Response> {\n const { scope, request } = state\n const pipes = this.#middleware.map((cls) => {\n const instance = scope.make(cls)\n state.middleware.push(instance)\n return (passable: HttpRequest, next: (passable: HttpRequest) => Promise<unknown>) =>\n this.#guard(scope, passable, () => instance.handle(passable, next as (r: HttpRequest) => Promise<Response>))\n })\n return scope\n .make(PipelineFactory)\n .make<HttpRequest>()\n .send(request)\n .through(pipes)\n .then((passable) => this.#guard(scope, passable, () => this.#dispatch(scope, passable)))\n }\n\n #dispatch(scope: Container, request: HttpRequest): Promise<Response> {\n return scope.make(Router).dispatch(request)\n }\n\n /** Converts a Responsable result, and renders a thrown error at this stage (Laravel's Routing\\Pipeline). */\n async #guard(scope: Container, request: HttpRequest, run: () => Promise<unknown>): Promise<Response> {\n try {\n const result = await run()\n if (result instanceof Response) return result\n const responsable = result as { toResponse?: (request: unknown) => Response | Promise<Response> } | null\n if (typeof responsable?.toResponse === 'function') return await responsable.toResponse(request)\n throw new HttpServerError('Middleware must return a Response.')\n } catch (error) {\n if (!scope.bound(ExceptionHandler)) throw error\n const handler = scope.make(ExceptionHandler)\n await handler.report(error)\n return handler.render(request, error)\n }\n }\n\n /** Last resort: the handler failed or isn't bound. Never throws. */\n async #renderLast(scope: Container, request: HttpRequest, error: unknown): Promise<Response> {\n if (scope.bound(ExceptionHandler)) {\n try {\n const handler = scope.make(ExceptionHandler)\n await handler.report(error)\n return await handler.render(request, error)\n } catch (renderError) {\n console.error(renderError)\n }\n } else {\n console.error(error)\n }\n return plainServerError()\n }\n\n async #report(scope: Container, error: unknown): Promise<void> {\n try {\n if (scope.bound(ExceptionHandler)) await scope.make(ExceptionHandler).report(error)\n else console.error(error)\n } catch (reportError) {\n console.error(reportError)\n }\n }\n\n /** config('http.max_body_size'): bytes, or null for no limit. Anything else is a configuration error. */\n #maxBodySize(): number | null {\n if (!this.app.bound(ConfigRepository)) return 8 * 1024 * 1024\n const value = this.app.make(ConfigRepository).get<unknown>('http.max_body_size', 8 * 1024 * 1024)\n if (value === null) return null\n if (typeof value === 'number' && Number.isFinite(value) && value >= 0) return value\n throw new HttpServerError(\n `Invalid http.max_body_size ${JSON.stringify(value) ?? String(value)}: use a number of bytes (0 or more), or null for no limit.`,\n )\n }\n\n /** config('http.max_json_depth'): how deep a JSON body may nest, or null for no limit. */\n #maxJsonDepth(): number | null {\n if (!this.app.bound(ConfigRepository)) return 512\n const value = this.app.make(ConfigRepository).get<unknown>('http.max_json_depth', 512)\n if (value === null) return null\n if (typeof value === 'number' && Number.isInteger(value) && value >= 1) return value\n throw new HttpServerError(\n `Invalid http.max_json_depth ${JSON.stringify(value) ?? String(value)}: use a whole number (1 or more), or null for no limit.`,\n )\n }\n\n /** config('http.trusted_proxies'): an array, or a comma-separated string such as '*' or '10.0.0.0/8,::1'. */\n #trustedProxies(): string[] {\n if (!this.app.bound(ConfigRepository)) return []\n const value = this.app.make(ConfigRepository).get<unknown>('http.trusted_proxies', [])\n if (typeof value === 'string') return value.split(',').map((entry) => entry.trim()).filter((entry) => entry !== '')\n return Array.isArray(value) ? value.map(String) : []\n }\n}\n","import type { HttpRequest, Middleware, Next } from '@orieljs/contracts'\nimport { IncomingRequest } from '../IncomingRequest'\n\n/** '' becomes null in the query and body, so `nullable` validation behaves as in Laravel. */\nexport class ConvertEmptyStringsToNull implements Middleware {\n async handle(request: HttpRequest, next: Next): Promise<Response> {\n if (request instanceof IncomingRequest) request.transformInput((_key, value) => (value === '' ? null : value))\n return next(request)\n }\n}\n","import type { HttpRequest, Middleware, Next } from '@orieljs/contracts'\nimport { IncomingRequest } from '../IncomingRequest'\n\n/** Laravel's trim: whitespace plus BOM, zero-width space and left-to-right mark. */\nconst TRIM = /^[\\s\\uFEFF\\u200B\\u200E]+|[\\s\\uFEFF\\u200B\\u200E]+$/g\n\n/** Trims every string in the query and body, except password fields (Laravel's TrimStrings). */\nexport class TrimStrings implements Middleware {\n /** Dotted input keys left untouched. Override in a subclass to change. */\n protected except: string[] = ['current_password', 'password', 'password_confirmation']\n\n async handle(request: HttpRequest, next: Next): Promise<Response> {\n if (request instanceof IncomingRequest) {\n request.transformInput((key, value) =>\n typeof value === 'string' && !this.except.includes(key) ? value.replace(TRIM, '') : value,\n )\n }\n return next(request)\n }\n}\n","import {\n ConfigRepository,\n MiddlewareCallbacks,\n Router,\n type Application,\n type HttpRequest,\n type MiddlewareClass,\n type MiddlewareConfigurator,\n type MiddlewareReference,\n} from '@orieljs/contracts'\nimport type { Kernel } from './Kernel'\n\ninterface GroupOptions {\n append?: MiddlewareClass[]\n prepend?: MiddlewareClass[]\n remove?: MiddlewareClass[]\n}\n\n/** The `m` in withMiddleware((m) => …): edits the kernel's global middleware and the router's groups and aliases. */\nexport class MiddlewareConfiguration implements MiddlewareConfigurator {\n constructor(\n private readonly kernel: Kernel,\n private readonly router: Router,\n private readonly config?: ConfigRepository,\n ) {}\n\n append(...middleware: MiddlewareClass[]): this {\n this.kernel.appendMiddleware(...middleware)\n return this\n }\n\n prepend(...middleware: MiddlewareClass[]): this {\n this.kernel.prependMiddleware(...middleware)\n return this\n }\n\n web(options: GroupOptions): this {\n return this.#modifyGroup('web', options)\n }\n\n api(options: GroupOptions): this {\n return this.#modifyGroup('api', options)\n }\n\n alias(aliases: Record<string, MiddlewareClass>): this {\n for (const [name, middleware] of Object.entries(aliases)) this.router.aliasMiddleware(name, middleware)\n return this\n }\n\n group(name: string, middleware: Array<MiddlewareClass | string>): this {\n this.router.middlewareGroup(name, middleware)\n return this\n }\n\n /** Stored in config('http.csrf_except'), which the Session component's VerifyCsrfToken reads. */\n validateCsrfTokens(options: { except: string[] }): this {\n const current = this.config?.get<string[]>('http.csrf_except', []) ?? []\n this.config?.set('http.csrf_except', [...current, ...options.except])\n return this\n }\n\n /** Stored in config('http.redirect_guests_to'), which the Auth middleware and the exception handler read. */\n redirectGuestsTo(url: string | ((request: HttpRequest) => string)): this {\n this.config?.set('http.redirect_guests_to', url)\n return this\n }\n\n /** Laravel 11's redirectUsersTo(): stored in config('http.redirect_users_to') for Auth's RedirectIfAuthenticated. */\n redirectUsersTo(url: string | ((request: HttpRequest) => string)): this {\n this.config?.set('http.redirect_users_to', url)\n return this\n }\n\n /** Laravel's order: prepends, then the group minus removals, then appends. */\n #modifyGroup(name: string, { append = [], prepend = [], remove = [] }: GroupOptions): this {\n const current: MiddlewareReference[] = this.router.getMiddlewareGroups()[name] ?? []\n const moved = new Set<MiddlewareReference>([...append, ...prepend, ...remove])\n this.router.middlewareGroup(name, [...prepend, ...current.filter((entry) => !moved.has(entry)), ...append])\n return this\n }\n}\n\n/** Runs the withMiddleware() callbacks collected by the ApplicationBuilder (HttpServiceProvider calls this once booted). */\nexport function applyMiddlewareCallbacks(app: Application, kernel: Kernel): void {\n if (!app.bound(MiddlewareCallbacks)) return\n const callbacks = app.make(MiddlewareCallbacks) as Array<(configurator: MiddlewareConfigurator) => void>\n if (callbacks.length === 0) return\n const config = app.bound(ConfigRepository) ? app.make(ConfigRepository) : undefined\n const configurator = new MiddlewareConfiguration(kernel, app.make(Router), config)\n for (const callback of callbacks) callback(configurator)\n}\n","import {\n ConfigRepository,\n LogManager,\n Redirector,\n UrlGenerator,\n ViewFactory,\n type Application,\n type AuthenticationError,\n type Container,\n type ErrorKind,\n type ExceptionHandler,\n type HttpRequest,\n type OrielError,\n type ValidationError,\n} from '@orieljs/contracts'\nimport { currentContainer } from '@orieljs/container'\nimport { debugPage, minimalPage, stackFrames, statusText } from './errorPages'\nimport { HttpResponseException } from './errors'\nimport { IncomingRequest } from './IncomingRequest'\n\nexport type ReportCallback = (error: unknown) => void | boolean | Promise<void | boolean>\nexport type RenderCallback = (error: unknown, request: unknown) => Response | undefined | Promise<Response | undefined>\nexport type ErrorClass = abstract new (...args: never[]) => Error\nexport type JsonWhenCallback = (request: HttpRequest, error: unknown) => boolean\n\n/** Laravel's $internalDontReport: expected errors that are rendered, never logged ('Server' is not here). */\nconst NOT_REPORTED = new Set<ErrorKind>(['Http', 'ModelNotFound', 'Validation', 'Authentication', 'Authorization', 'TokenMismatch'])\n/** Kinds whose message is safe to show to users, at any status (Laravel's HttpException rendering). */\nconst HTTP_KINDS = new Set<ErrorKind>(['Http', 'ModelNotFound', 'Authorization', 'TokenMismatch'])\n\nconst kindOf = (error: unknown): ErrorKind | undefined =>\n typeof error === 'object' && error !== null && typeof (error as OrielError).kind === 'string' ? (error as OrielError).kind : undefined\n\n/** HTTP status for an error (spec §7). */\nexport function statusFor(error: unknown): number {\n const status = (error as Partial<OrielError> | null)?.status\n switch (kindOf(error)) {\n case 'Http':\n return status ?? 500\n case 'ModelNotFound':\n return 404\n case 'Authorization':\n return status ?? 403\n case 'TokenMismatch':\n return 419\n case 'Authentication':\n return 401\n case 'Validation':\n return status ?? 422\n case 'Server':\n return status ?? 500\n default:\n return 500\n }\n}\n\n/** \"The title field is required. (and 2 more errors)\" (Laravel's ValidationException::summarize). */\nexport function summarizeValidation(errors: Record<string, string[]>): string {\n const messages = Object.values(errors).flat()\n if (messages.length === 0) return 'The given data was invalid.'\n const more = messages.length - 1\n return more === 0 ? messages[0]! : `${messages[0]!} (and ${more} more ${more === 1 ? 'error' : 'errors'})`\n}\n\n/** An HTTP-like error: its message may be shown and it doesn't get the debug page. */\nconst isHttpLike = (error: unknown): boolean => {\n const kind = kindOf(error)\n return kind !== undefined && HTTP_KINDS.has(kind)\n}\n\n/** The exception handler (spec §7): report through the LogManager, render by error kind. */\nexport class ErrorHandler implements ExceptionHandler {\n /** Input keys never flashed back on a validation redirect. */\n protected dontFlash = ['current_password', 'password', 'password_confirmation']\n readonly #reportCallbacks: ReportCallback[] = []\n readonly #renderCallbacks: RenderCallback[] = []\n readonly #dontReport: ErrorClass[] = []\n readonly #reported = new WeakSet<object>()\n #jsonWhen: JsonWhenCallback | undefined\n\n constructor(protected readonly app: Application) {}\n\n reportUsing(callback: ReportCallback): void {\n this.#reportCallbacks.push(callback)\n }\n\n renderUsing(callback: RenderCallback): void {\n this.#renderCallbacks.push(callback)\n }\n\n ignore(...classes: ErrorClass[]): void {\n this.#dontReport.push(...classes)\n }\n\n /** Laravel's shouldRenderJsonWhen(): the callback decides JSON or HTML instead of the Accept header. */\n shouldRenderJsonWhen(callback: JsonWhenCallback): void {\n this.#jsonWhen = callback\n }\n\n /** Laravel's shouldReturnJson(): the shouldRenderJsonWhen() callback when set, else request.expectsJson(). */\n protected shouldReturnJson(request: HttpRequest, error: unknown): boolean {\n return this.#jsonWhen !== undefined ? this.#jsonWhen(request, error) : request.expectsJson()\n }\n\n shouldReport(error: unknown): boolean {\n const kind = kindOf(error)\n if (kind !== undefined && NOT_REPORTED.has(kind)) return false\n return !this.#dontReport.some((cls) => error instanceof cls)\n }\n\n /** Report callbacks first (returning false stops the default log), then LogManager.error(), else console.error. Once per error. */\n async report(error: unknown): Promise<void> {\n if (!this.shouldReport(error)) return\n if (typeof error === 'object' && error !== null) {\n if (this.#reported.has(error)) return\n this.#reported.add(error)\n }\n try {\n for (const callback of this.#reportCallbacks) if ((await callback(error)) === false) return\n const container = this.#container()\n if (container.bound(LogManager)) {\n const message = error instanceof Error ? error.message : String(error)\n container.make(LogManager).error(message, { exception: error })\n } else {\n console.error(error)\n }\n } catch (reportError) {\n console.error(reportError)\n }\n }\n\n async render(request: unknown, error: unknown): Promise<Response> {\n for (const callback of this.#renderCallbacks) {\n const response = await callback(error, request)\n if (response instanceof Response) return response\n }\n if (error instanceof HttpResponseException) return error.response\n const custom = await this.#renderCustom(request, error)\n if (custom !== undefined) return custom\n\n const http = this.#httpRequest(request)\n const kind = kindOf(error)\n let response: Response\n if (kind === 'Validation') response = await this.#renderValidation(http, error as ValidationError)\n else if (kind === 'Authentication') response = await this.#renderAuthentication(http, error as AuthenticationError)\n else if (this.shouldReturnJson(http, error)) response = this.#renderJson(error)\n else response = await this.#renderHtml(http, error)\n\n const headers = (error as Partial<OrielError> | null)?.headers\n return headers === undefined ? response : withHeaders(response, headers)\n }\n\n /** An error with its own render(request) or toResponse(request) (Laravel's renderable exceptions / Responsable). */\n async #renderCustom(request: unknown, error: unknown): Promise<Response | undefined> {\n if (typeof error !== 'object' || error === null) return undefined\n const candidate = error as { render?: (request: unknown) => unknown; toResponse?: (request: unknown) => unknown }\n for (const method of [candidate.render, candidate.toResponse]) {\n if (typeof method !== 'function') continue\n const response = await method.call(error, request)\n if (response instanceof Response) return response\n }\n return undefined\n }\n\n async #renderValidation(request: HttpRequest, error: ValidationError): Promise<Response> {\n if (this.shouldReturnJson(request, error)) {\n return this.#json({ message: summarizeValidation(error.errors), errors: error.errors }, statusFor(error))\n }\n const input = { ...request.input<Record<string, unknown>>() }\n for (const key of this.dontFlash) delete input[key]\n const container = this.#container()\n if (!container.bound(Redirector)) {\n return this.#redirect(error.redirectTo ?? request.header('referer') ?? '/')\n }\n const redirector = container.make(Redirector)\n const redirect = error.redirectTo !== undefined ? redirector.to(error.redirectTo) : redirector.back()\n // toResponse(request) may return a Promise per the Responsable contract; await it.\n const response = await redirect.withInput(input).withErrors(error.errors, error.errorBag).toResponse(request)\n return response\n }\n\n async #renderAuthentication(request: HttpRequest, error: AuthenticationError): Promise<Response> {\n if (this.shouldReturnJson(request, error)) return this.#json({ message: error.message || 'Unauthenticated.' }, 401)\n const target = error.redirectTo ?? this.#guestRedirect(request)\n const container = this.#container()\n if (!container.bound(Redirector)) return this.#redirect(target)\n const redirector = container.make(Redirector) as Redirector & { guest?: (path: string) => { toResponse(r: unknown): unknown } }\n const redirect = typeof redirector.guest === 'function' ? redirector.guest(target) : redirector.to(target)\n // toResponse(request) may return a Promise per the Responsable contract; await it.\n return (await redirect.toResponse(request)) as Response\n }\n\n /** config('http.redirect_guests_to'), then route('login'), then '/login'. */\n #guestRedirect(request: HttpRequest): string {\n const configured = this.#config<unknown>('http.redirect_guests_to', undefined)\n if (typeof configured === 'function') return String((configured as (request: HttpRequest) => string)(request))\n if (typeof configured === 'string' && configured !== '') return configured\n const container = this.#container()\n if (container.bound(UrlGenerator)) {\n const url = container.make(UrlGenerator)\n if (url.hasRoute('login')) return url.route('login')\n }\n return '/login'\n }\n\n #renderJson(error: unknown): Response {\n const status = statusFor(error)\n if (isHttpLike(error)) {\n const message = error instanceof Error && error.message !== '' ? error.message : statusText(status)\n return this.#json({ message }, status)\n }\n if (!this.#debug()) return this.#json({ message: 'Server Error' }, status)\n const err = error instanceof Error ? error : new Error(String(error))\n const [frame] = stackFrames(err)\n return this.#json(\n {\n message: err.message,\n exception: err.name,\n file: frame?.file,\n line: frame?.line,\n trace: stackFrames(err).map((entry) => entry.text),\n },\n status,\n )\n }\n\n async #renderHtml(request: HttpRequest, error: unknown): Promise<Response> {\n const status = statusFor(error)\n if (!isHttpLike(error) && this.#debug()) {\n return this.#html(await debugPage(error, request.method(), request.fullUrl()), status)\n }\n const message = status === 403 && error instanceof Error && error.message !== '' ? error.message : statusText(status)\n const view = await this.#errorView(status, error, message)\n return this.#html(view ?? minimalPage(status, message), status)\n }\n\n /** resources/views/errors/{status}.tsx, then errors/4xx or errors/5xx, through the ViewFactory. */\n async #errorView(status: number, error: unknown, message: string): Promise<string | undefined> {\n const container = this.#container()\n if (!container.bound(ViewFactory)) return undefined\n const views = container.make(ViewFactory)\n for (const name of [`errors.${status}`, `errors.${Math.floor(status / 100)}xx`]) {\n if (!views.exists(name)) continue\n try {\n return await views.make(name, { exception: error, status, message }).render()\n } catch (viewError) {\n await this.report(viewError)\n return undefined\n }\n }\n return undefined\n }\n\n #httpRequest(request: unknown): HttpRequest {\n if (typeof request === 'object' && request !== null && typeof (request as HttpRequest).expectsJson === 'function') {\n return request as HttpRequest\n }\n return new IncomingRequest(request instanceof Request ? request : new Request('http://localhost/'))\n }\n\n #json(body: unknown, status: number): Response {\n return new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } })\n }\n\n #html(body: string, status: number): Response {\n return new Response(body, { status, headers: { 'content-type': 'text/html; charset=utf-8' } })\n }\n\n #redirect(location: string): Response {\n return new Response(null, { status: 302, headers: { Location: location } })\n }\n\n #debug(): boolean {\n return this.#config<unknown>('app.debug', false) === true\n }\n\n #config<T>(key: string, fallback: T): T {\n return this.app.bound(ConfigRepository) ? this.app.make(ConfigRepository).get<T>(key, fallback) : fallback\n }\n\n /** The request scope while handling a request (so scoped services resolve), else the application. */\n #container(): Container {\n return currentContainer() ?? this.app\n }\n}\n\n/**\n * A copy of `response` with the headers added. The rendered response's own headers may be immutable (a fetch() or\n * Response.redirect() response), so they are never set in place.\n */\nfunction withHeaders(response: Response, extra: Record<string, string>): Response {\n const headers = new Headers(response.headers)\n for (const [name, value] of Object.entries(extra)) headers.set(name, value)\n return new Response(response.body, { status: response.status, statusText: response.statusText, headers })\n}\n","import { readFile } from 'node:fs/promises'\nimport { fileURLToPath } from 'node:url'\n\nconst STATUS_TEXTS: Record<number, string> = {\n 400: 'Bad Request',\n 401: 'Unauthorized',\n 402: 'Payment Required',\n 403: 'Forbidden',\n 404: 'Not Found',\n 405: 'Method Not Allowed',\n 406: 'Not Acceptable',\n 407: 'Proxy Authentication Required',\n 408: 'Request Timeout',\n 409: 'Conflict',\n 410: 'Gone',\n 411: 'Length Required',\n 412: 'Precondition Failed',\n 413: 'Content Too Large',\n 414: 'URI Too Long',\n 415: 'Unsupported Media Type',\n 416: 'Range Not Satisfiable',\n 417: 'Expectation Failed',\n 418: \"I'm a teapot\",\n 419: 'Page Expired',\n 421: 'Misdirected Request',\n 422: 'Unprocessable Content',\n 423: 'Locked',\n 424: 'Failed Dependency',\n 425: 'Too Early',\n 426: 'Upgrade Required',\n 428: 'Precondition Required',\n 429: 'Too Many Requests',\n 431: 'Request Header Fields Too Large',\n 451: 'Unavailable For Legal Reasons',\n 500: 'Server Error',\n 501: 'Not Implemented',\n 502: 'Bad Gateway',\n 503: 'Service Unavailable',\n 504: 'Gateway Timeout',\n 505: 'HTTP Version Not Supported',\n 506: 'Variant Also Negotiates',\n 507: 'Insufficient Storage',\n 508: 'Loop Detected',\n 510: 'Not Extended',\n 511: 'Network Authentication Required',\n}\n\n/**\n * The text an error page shows for a status: Laravel's own wording where it has a view (\"Server Error\", \"Page\n * Expired\"), else Symfony's `Response::$statusTexts`, which Laravel shows for the others.\n */\nexport function statusText(status: number): string {\n return STATUS_TEXTS[status] ?? (status >= 500 ? 'Server Error' : 'Error')\n}\n\nexport function escapeHtml(value: string): string {\n return value.replace(/[&<>\"']/g, (char) => `&#${char.charCodeAt(0)};`)\n}\n\n/** Laravel's minimal error page: \"404 | Not Found\". */\nexport function minimalPage(status: number, message: string): string {\n const title = escapeHtml(message)\n return `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<title>${title}</title>\n<style>body{margin:0;font-family:ui-sans-serif,system-ui,sans-serif;background:#f7fafc;color:#1a202c;display:flex;align-items:center;justify-content:center;min-height:100vh}.code{padding:0 1rem;border-right:1px solid #a0aec0;font-size:1.125rem}.message{padding:0 1rem;font-size:1.125rem;text-transform:uppercase;letter-spacing:.05em}</style>\n</head>\n<body><div class=\"code\">${status}</div><div class=\"message\">${title}</div></body>\n</html>`\n}\n\nexport interface StackFrame {\n readonly file: string\n readonly line: number\n readonly column: number\n readonly text: string\n}\n\n/** Parses V8/JavaScriptCore stack lines into frames that point at files. */\nexport function stackFrames(error: Error): StackFrame[] {\n const frames: StackFrame[] = []\n for (const raw of (error.stack ?? '').split('\\n').slice(1)) {\n const text = raw.trim()\n const match = /(?:\\(|@|at )((?:file:\\/\\/)?(?:\\/|[A-Za-z]:\\\\)[^()]*?):(\\d+):(\\d+)\\)?$/.exec(text)\n if (match === null) continue\n const location = match[1]!\n const file = location.startsWith('file://') ? fileURLToPath(location) : location\n frames.push({ file, line: Number(match[2]), column: Number(match[3]), text })\n }\n return frames\n}\n\n/** Up to `radius` lines either side of the frame's line, or undefined when the file can't be read. */\nasync function excerpt(frame: StackFrame, radius = 5): Promise<string | undefined> {\n const source = await readFile(frame.file, 'utf8').catch(() => undefined)\n if (source === undefined) return undefined\n const lines = source.split('\\n')\n const start = Math.max(1, frame.line - radius)\n const end = Math.min(lines.length, frame.line + radius)\n const rows: string[] = []\n for (let number = start; number <= end; number++) {\n const current = number === frame.line ? ' class=\"current\"' : ''\n rows.push(`<tr${current}><td class=\"n\">${number}</td><td><code>${escapeHtml(lines[number - 1] ?? '')}</code></td></tr>`)\n }\n return `<table class=\"source\">${rows.join('')}</table>`\n}\n\n/** The APP_DEBUG page: class, message, request, a source excerpt of the first app frame, the stack and causes. */\nexport async function debugPage(error: unknown, method: string, url: string): Promise<string> {\n const err = error instanceof Error ? error : new Error(String(error))\n const frames = stackFrames(err)\n const appFrame = frames.find((frame) => !frame.file.includes('node_modules') && !frame.file.startsWith('node:')) ?? frames[0]\n const source = appFrame === undefined ? undefined : await excerpt(appFrame)\n const causes: string[] = []\n for (let cause = err.cause, depth = 0; cause !== undefined && depth < 5; cause = (cause as Error).cause, depth++) {\n causes.push(`<li>${escapeHtml(cause instanceof Error ? `${cause.name}: ${cause.message}` : String(cause))}</li>`)\n }\n return `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<title>${escapeHtml(err.message || err.name)}</title>\n<style>body{margin:0;font-family:ui-sans-serif,system-ui,sans-serif;background:#f3f4f6;color:#111827}main{max-width:1100px;margin:2rem auto;padding:0 1rem}header{background:#fff;border-radius:.5rem;padding:1.5rem;box-shadow:0 1px 3px #0001}.class{color:#dc2626;font-weight:600}.message{font-size:1.5rem;margin:.5rem 0}.request{color:#6b7280}section{background:#fff;border-radius:.5rem;padding:1rem;margin-top:1rem;box-shadow:0 1px 3px #0001;overflow:auto}.source td{padding:0 .5rem;white-space:pre;font-size:.85rem}.source .n{color:#9ca3af;text-align:right}.source .current{background:#fee2e2}ol{font-family:ui-monospace,monospace;font-size:.85rem}</style>\n</head>\n<body><main>\n<header><div class=\"class\">${escapeHtml(err.name)}</div><div class=\"message\">${escapeHtml(err.message)}</div><div class=\"request\">${escapeHtml(method)} ${escapeHtml(url)}</div></header>\n${appFrame === undefined ? '' : `<section><div>${escapeHtml(appFrame.file)}:${appFrame.line}</div>${source ?? ''}</section>`}\n<section><ol>${frames.map((frame) => `<li>${escapeHtml(frame.text)}</li>`).join('')}</ol></section>\n${causes.length === 0 ? '' : `<section><div>Caused by</div><ul>${causes.join('')}</ul></section>`}\n</main></body>\n</html>`\n}\n","import { ExceptionCallbacks, type Application, type ExceptionsConfigurator, type HttpRequest } from '@orieljs/contracts'\nimport type { ErrorClass, ErrorHandler, RenderCallback, ReportCallback } from './ErrorHandler'\n\n/** The `e` in withExceptions((e) => …). */\nexport class ExceptionsConfiguration implements ExceptionsConfigurator {\n constructor(private readonly handler: ErrorHandler) {}\n\n report(callback: ReportCallback): this {\n this.handler.reportUsing(callback)\n return this\n }\n\n render(callback: RenderCallback): this {\n this.handler.renderUsing(callback)\n return this\n }\n\n dontReport(...classes: ErrorClass[]): this {\n this.handler.ignore(...classes)\n return this\n }\n\n /** shouldRenderJsonWhen((request) => request.is('api/*')): JSON errors for those requests, whatever they accept. */\n shouldRenderJsonWhen(callback: (request: HttpRequest, error: unknown) => boolean): this {\n this.handler.shouldRenderJsonWhen(callback)\n return this\n }\n}\n\n/** Runs the withExceptions() callbacks against a handler (the provider does this when the handler is built). */\nexport function applyExceptionCallbacks(app: Application, handler: ErrorHandler): void {\n if (!app.bound(ExceptionCallbacks)) return\n const configurator = new ExceptionsConfiguration(handler)\n for (const callback of app.make(ExceptionCallbacks)) callback(configurator)\n}\n","import { HttpKernel, type Application } from '@orieljs/contracts'\nimport { plainServerError } from '../Kernel'\nimport { servePublicFile } from './static'\n\nexport type Runtime = 'node' | 'bun'\n\nexport interface ServeOptions {\n /** Default: PORT, then SERVER_PORT, then 8000 (Laravel's serve). 0 picks a free port. */\n port?: number\n /** Default: 127.0.0.1. */\n hostname?: string\n /** Close gracefully on SIGINT/SIGTERM, then exit. Default: true. */\n signals?: boolean\n /** How long close() waits for in-flight requests before cutting connections (ms). Default: 10000. */\n shutdownTimeout?: number\n /** Default: detected (Bun when globalThis.Bun exists). */\n runtime?: Runtime\n /** Called once listening. Default: prints \"Server running on [url].\" */\n onListen?: (server: RunningServer) => void\n /** Serve existing files from this directory before the app (Laravel's server.php). Default: app.publicPath(); false turns it off. */\n publicPath?: string | false\n}\n\nexport interface ResolvedServeOptions {\n readonly port: number\n readonly hostname: string\n readonly signals: boolean\n readonly shutdownTimeout: number\n /** Where public files are served from, or undefined when turned off. */\n readonly publicPath?: string\n}\n\nexport interface RunningServer {\n readonly runtime: Runtime\n readonly hostname: string\n readonly port: number\n /** 'http://127.0.0.1:8000' */\n readonly url: string\n /** Stops accepting connections, waits for in-flight requests (up to shutdownTimeout), then resolves. */\n close(): Promise<void>\n /** Resolves once the server has closed. */\n readonly closed: Promise<void>\n}\n\n/** HttpKernel.terminate() after the response went out (Laravel's terminable middleware). Never throws. */\nexport async function terminateRequest(app: Application, request: Request, response: Response): Promise<void> {\n try {\n if (app.bound(HttpKernel)) await app.make(HttpKernel).terminate?.(request, response)\n } catch (error) {\n console.error(error)\n }\n}\n\n/** A public file when one matches, else app.handle(), turning a crash outside the kernel into a plain 500. */\nexport async function handleSafely(app: Application, request: Request, publicPath?: string): Promise<Response> {\n try {\n if (publicPath !== undefined) {\n const file = await servePublicFile(publicPath, request)\n if (file !== undefined) return file\n }\n return await app.handle(request)\n } catch (error) {\n console.error(error)\n return plainServerError()\n }\n}\n\n/**\n * SIGINT/SIGTERM → close() → app.shutdown() (database pools, Redis clients, log files) → process.exit(0). The\n * listeners go away when the server closes.\n */\nexport function exitOnSignals(close: () => Promise<void>, closed: Promise<void>, app: Application): void {\n const onSignal = () => {\n void close()\n .then(() => app.shutdown())\n .then(() => process.exit(0))\n }\n process.once('SIGINT', onSignal)\n process.once('SIGTERM', onSignal)\n void closed.then(() => {\n process.off('SIGINT', onSignal)\n process.off('SIGTERM', onSignal)\n })\n}\n\nexport const displayHost = (hostname: string): string => (hostname.includes(':') ? `[${hostname}]` : hostname)\n","import { createReadStream } from 'node:fs'\nimport { stat } from 'node:fs/promises'\nimport { Readable } from 'node:stream'\nimport { relative, resolve, sep } from 'node:path'\nimport { mimeFromExtension } from '../mime'\n\n/**\n * Source files and dotfiles in public/ are never served (public/index.ts is the entry point, not an asset).\n * Tested on every segment of the resolved path, so trailing slashes and dot segments can't hide a name.\n * Names ending in a dot or a space are refused too, since Windows strips those when it opens the file.\n */\nconst HIDDEN_SEGMENT = /^\\.|\\.(ts|tsx|mts|cts)$|[. ]$/i\n\n/**\n * Laravel's server.php for `artisan serve`: a GET or HEAD for a file that exists under public/ is answered\n * with that file, so the built Vite assets (public/build) and other public files work without a web server.\n * Anything else (directories, missing files, other methods) returns undefined and goes to the application.\n */\nexport async function servePublicFile(publicPath: string, request: Request): Promise<Response | undefined> {\n if (request.method !== 'GET' && request.method !== 'HEAD') return undefined\n let pathname: string\n try {\n pathname = decodeURIComponent(new URL(request.url).pathname)\n } catch {\n return undefined\n }\n if (pathname === '/' || pathname.includes('\\0')) return undefined\n const root = resolve(publicPath)\n const file = resolve(root, `.${pathname}`)\n if (!file.startsWith(root + sep)) return undefined\n if (relative(root, file).split(/[\\\\/]/).some((segment) => HIDDEN_SEGMENT.test(segment))) return undefined\n const info = await stat(file).catch(() => undefined)\n if (info === undefined || !info.isFile()) return undefined\n\n const type = mimeFromExtension(file)\n const headers = new Headers({\n 'content-type': type.startsWith('text/') || type === 'application/json' ? `${type}; charset=utf-8` : type,\n 'content-length': String(info.size),\n 'last-modified': info.mtime.toUTCString(),\n })\n // Vite's hashed build output never changes under the same name.\n if (pathname.startsWith('/build/assets/')) headers.set('cache-control', 'public, max-age=31536000, immutable')\n if (request.method === 'HEAD') return new Response(null, { status: 200, headers })\n const body = Readable.toWeb(createReadStream(file)) as unknown as ReadableStream<Uint8Array>\n return new Response(body, { status: 200, headers })\n}\n","import type { Application } from '@orieljs/contracts'\nimport { setClientAddress } from '../clientAddress'\nimport { HttpServerError } from '../errors'\nimport { plainServerError } from '../Kernel'\nimport {\n displayHost,\n exitOnSignals,\n handleSafely,\n terminateRequest,\n type ResolvedServeOptions,\n type RunningServer,\n} from './types'\n\n/** The slice of Bun's API used here (typed locally: there is no Bun lib in the build). */\ninterface BunServer {\n readonly port: number\n stop(closeActiveConnections?: boolean): Promise<void> | void\n requestIP(request: Request): { address: string } | null\n}\ninterface BunRuntime {\n serve(options: {\n port: number\n hostname: string\n fetch(request: Request, server: BunServer): Promise<Response>\n error(error: Error): Response\n }): BunServer\n}\n\nexport function bunRuntime(): BunRuntime | undefined {\n return (globalThis as { Bun?: BunRuntime }).Bun\n}\n\nexport async function serveBun(app: Application, options: ResolvedServeOptions): Promise<RunningServer> {\n const bun = bunRuntime()\n if (bun === undefined) throw new HttpServerError('Bun.serve is not available: the process is not running on Bun.')\n let markClosed: () => void = () => undefined\n const closed = new Promise<void>((resolve) => (markClosed = resolve))\n\n const server = bun.serve({\n port: options.port,\n hostname: options.hostname,\n async fetch(request, current) {\n setClientAddress(request, current.requestIP(request)?.address)\n const response = await handleSafely(app, request, options.publicPath)\n // Bun has no \"response sent\" hook: terminate on the next tick.\n setTimeout(() => void terminateRequest(app, request, response), 0)\n return response\n },\n error(error) {\n console.error(error)\n return plainServerError()\n },\n })\n\n let closing: Promise<void> | undefined\n const close = () =>\n (closing ??= (async () => {\n let timer: ReturnType<typeof setTimeout> | undefined\n const forced = new Promise<void>((resolve) => {\n timer = setTimeout(() => void Promise.resolve(server.stop(true)).then(resolve), options.shutdownTimeout)\n })\n await Promise.race([Promise.resolve(server.stop(false)), forced])\n clearTimeout(timer)\n markClosed()\n })())\n if (options.signals) exitOnSignals(close, closed, app)\n\n return {\n runtime: 'bun',\n hostname: options.hostname,\n port: server.port,\n url: `http://${displayHost(options.hostname)}:${server.port}`,\n close,\n closed,\n }\n}\n","import { createServer, type IncomingMessage, type ServerResponse } from 'node:http'\nimport type { AddressInfo } from 'node:net'\nimport { Readable } from 'node:stream'\nimport { pipeline } from 'node:stream/promises'\nimport type { ReadableStream as NodeReadableStream } from 'node:stream/web'\nimport type { Application } from '@orieljs/contracts'\nimport { setClientAddress } from '../clientAddress'\nimport {\n displayHost,\n exitOnSignals,\n handleSafely,\n terminateRequest,\n type ResolvedServeOptions,\n type RunningServer,\n} from './types'\n\n/**\n * The request's body as a web stream that pulls from `req`. Readable.toWeb(req) is not used: cancelling it (readBody\n * does that for a declared length over the limit) closes its controller while the socket still emits data, which\n * throws out of the adapter and kills the process. Cancelling this one just stops listening; node drops the unread\n * remainder once the response finishes.\n */\nfunction requestBody(req: IncomingMessage): ReadableStream<Uint8Array> {\n let finished = false\n const detach = () => {\n finished = true\n req.off('data', onData)\n req.off('end', onEnd)\n req.off('error', onError)\n req.off('close', onClose)\n }\n let controller!: ReadableStreamDefaultController<Uint8Array>\n const onData = (chunk: Buffer) => {\n if (finished) return\n controller.enqueue(new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength))\n if ((controller.desiredSize ?? 0) <= 0) req.pause()\n }\n const onEnd = () => {\n if (finished) return\n detach()\n controller.close()\n }\n const onError = (error: Error) => {\n if (finished) return\n detach()\n controller.error(error)\n }\n const onClose = () => {\n if (!finished && !req.complete) onError(new Error('The request was aborted.'))\n }\n return new ReadableStream<Uint8Array>(\n {\n start(c) {\n controller = c\n req.on('data', onData)\n req.on('end', onEnd)\n req.on('error', onError)\n req.on('close', onClose)\n req.pause()\n },\n pull() {\n req.resume()\n },\n cancel() {\n detach()\n },\n },\n { highWaterMark: 0 },\n )\n}\n\n/** node:http IncomingMessage → web Request (the body streams; the signal aborts when the client goes away). */\nexport function toWebRequest(req: IncomingMessage, res: ServerResponse, fallbackHost: string): Request {\n // Concatenate rather than resolve: a target such as '//evil.com/x' must stay on this host, not become evil.com.\n const target = req.url ?? '/'\n const url = new URL(`http://${req.headers.host ?? fallbackHost}${target.startsWith('/') ? target : `/${target}`}`)\n const headers = new Headers()\n for (let i = 0; i < req.rawHeaders.length; i += 2) {\n const name = req.rawHeaders[i]!\n if (!name.startsWith(':')) headers.append(name, req.rawHeaders[i + 1]!)\n }\n const method = (req.method ?? 'GET').toUpperCase()\n const controller = new AbortController()\n res.once('close', () => {\n if (!res.writableFinished) controller.abort()\n })\n const init: RequestInit & { duplex?: 'half' } = { method, headers, signal: controller.signal }\n if (method !== 'GET' && method !== 'HEAD') {\n init.body = requestBody(req)\n init.duplex = 'half'\n }\n return new Request(url, init)\n}\n\n/** Web Response → ServerResponse, streaming the body with backpressure. Several Set-Cookie headers stay separate. */\nexport async function writeResponse(res: ServerResponse, response: Response): Promise<void> {\n res.statusCode = response.status\n if (response.statusText !== '') res.statusMessage = response.statusText\n response.headers.forEach((value, name) => {\n if (name !== 'set-cookie') res.setHeader(name, value)\n })\n const cookies = response.headers.getSetCookie()\n if (cookies.length > 0) res.setHeader('set-cookie', cookies)\n if (response.body === null) {\n res.end()\n return\n }\n await pipeline(Readable.fromWeb(response.body as unknown as NodeReadableStream<Uint8Array>), res)\n}\n\nexport async function serveNode(app: Application, options: ResolvedServeOptions): Promise<RunningServer> {\n const fallbackHost = `${displayHost(options.hostname)}:${options.port}`\n const server = createServer((req, res) => {\n void (async () => {\n let request: Request\n try {\n request = toWebRequest(req, res, fallbackHost)\n } catch {\n res.statusCode = 400\n res.end('Bad Request')\n return\n }\n setClientAddress(request, req.socket.remoteAddress)\n const response = await handleSafely(app, request, options.publicPath)\n try {\n await writeResponse(res, response)\n } catch {\n // The client went away mid-response.\n res.destroy()\n }\n await terminateRequest(app, request, response)\n })()\n })\n\n await new Promise<void>((resolve, reject) => {\n server.once('error', reject)\n server.listen(options.port, options.hostname, () => {\n server.off('error', reject)\n resolve()\n })\n })\n\n const address = server.address() as AddressInfo\n const closed = new Promise<void>((resolve) => server.once('close', () => resolve()))\n let closing: Promise<void> | undefined\n const close = () =>\n (closing ??= (async () => {\n const done = new Promise<void>((resolve) => server.close(() => resolve()))\n // Keep-alive connections become idle once their request finishes; close them as that happens.\n server.closeIdleConnections()\n const idle = setInterval(() => server.closeIdleConnections(), 50)\n const force = setTimeout(() => server.closeAllConnections(), options.shutdownTimeout)\n await done\n clearInterval(idle)\n clearTimeout(force)\n })())\n if (options.signals) exitOnSignals(close, closed, app)\n\n return {\n runtime: 'node',\n hostname: options.hostname,\n port: address.port,\n url: `http://${displayHost(options.hostname)}:${address.port}`,\n close,\n closed,\n }\n}\n","import type { Application } from '@orieljs/contracts'\nimport { bunRuntime, serveBun } from './bun'\nimport { serveNode } from './node'\nimport type { ResolvedServeOptions, Runtime, RunningServer, ServeOptions } from './types'\n\nexport function detectRuntime(): Runtime {\n return bunRuntime() !== undefined ? 'bun' : 'node'\n}\n\n/** Boots the app and serves it with node:http or Bun.serve (public/index.ts: `await serve(app)`). */\nexport async function serve(app: Application, options: ServeOptions = {}): Promise<RunningServer> {\n const resolved: ResolvedServeOptions = {\n port: options.port ?? Number(process.env.PORT ?? process.env.SERVER_PORT ?? 8000),\n hostname: options.hostname ?? '127.0.0.1',\n signals: options.signals ?? true,\n shutdownTimeout: options.shutdownTimeout ?? 10_000,\n ...(options.publicPath !== false && { publicPath: options.publicPath ?? app.publicPath() }),\n }\n await app.boot()\n const runtime = options.runtime ?? detectRuntime()\n const server = runtime === 'bun' ? await serveBun(app, resolved) : await serveNode(app, resolved)\n const onListen = options.onListen ?? ((running: RunningServer) => console.log(`Server running on [${running.url}].`))\n onListen(server)\n return server\n}\n","import { existsSync } from 'node:fs'\nimport { mkdir, readFile, writeFile } from 'node:fs/promises'\nimport { dirname } from 'node:path'\nimport {\n Router,\n type Application,\n type CommandContext,\n type ConsoleKernel,\n type MiddlewareReference,\n type Route,\n} from '@orieljs/contracts'\nimport { serve } from './server/serve'\nimport type { RunningServer, ServeOptions } from './server/types'\nimport { serverEnvironment } from './watch/environment'\nimport { watchFiles } from './watch/files'\nimport { claimPort, listenFailure } from './watch/port'\nimport { WatchedServer, type WatchedServerOptions } from './watch/WatchedServer'\n\ninterface Io {\n option(name: string): string | undefined\n flag(name: string): boolean\n info(message: string): void\n line(message: string): void\n warn(message: string): void\n error(message: string): void\n}\n\n/**\n * The closure command's `this` (the contract's CommandContext), with the options normalised: a value option that\n * is absent (undefined, null, false or '') reads as undefined, and a flag is true only when set.\n */\nfunction io(command: CommandContext): Io {\n return {\n option: (name) => {\n const value: unknown = command.option(name)\n return value === undefined || value === null || value === false || value === '' ? undefined : String(value)\n },\n flag: (name) => {\n const value: unknown = command.option(name)\n return value === true || value === 'true' || value === '1'\n },\n info: (message) => command.info(message),\n line: (message) => command.line(message),\n warn: (message) => command.warn(message),\n error: (message) => command.error(message),\n }\n}\n\nexport interface RouteListRow {\n /** 'GET|HEAD' */\n readonly method: string\n readonly uri: string\n readonly name: string | null\n /** 'PostController@show' or 'Closure' */\n readonly action: string\n readonly middleware: string[]\n}\n\ninterface ListableRoute extends Route {\n getActionName?(): string\n gatherMiddleware?(): MiddlewareReference[]\n}\n\nconst middlewareName = (reference: MiddlewareReference): string => (typeof reference === 'string' ? reference : reference.name)\n\n/** One row per route, sorted by URI (Laravel's default --sort=uri; ties keep registration order). */\nexport function routeListRows(routes: readonly Route[]): RouteListRow[] {\n const rows = routes.map((route) => {\n const listable = route as ListableRoute\n return {\n method: route.methods.join('|'),\n uri: route.uri,\n name: route.getName() ?? null,\n action: typeof listable.getActionName === 'function' ? listable.getActionName() : 'Closure',\n middleware: typeof listable.gatherMiddleware === 'function' ? listable.gatherMiddleware().map(middlewareName) : [],\n }\n })\n return rows.sort((a, b) => (a.uri < b.uri ? -1 : a.uri > b.uri ? 1 : 0))\n}\n\nexport interface RouteListFilters {\n method?: string\n name?: string\n path?: string\n /** Comma-separated. */\n exceptPath?: string\n}\n\n/** Laravel's RouteListCommand::filterRoute: substring matches, method compared uppercased. */\nexport function filterRouteList(rows: readonly RouteListRow[], filters: RouteListFilters): RouteListRow[] {\n const excluded = (filters.exceptPath ?? '').split(',').filter((path) => path !== '')\n return rows.filter((row) => {\n if (filters.name !== undefined && !(row.name ?? '').includes(filters.name)) return false\n if (filters.path !== undefined && !row.uri.includes(filters.path)) return false\n if (filters.method !== undefined && !row.method.includes(filters.method.toUpperCase())) return false\n return !excluded.some((path) => row.uri.includes(path))\n })\n}\n\n/**\n * Laravel's route:list layout: the method column padded, the URI, a dotted leader, then `name › action`\n * (closures show only the name), and a right-aligned \"Showing [n] routes\" footer.\n */\nexport function formatRouteList(rows: readonly RouteListRow[], width: number): string[] {\n const methodWidth = Math.max(...rows.map((row) => row.method.length))\n const lines = rows.map((row) => {\n const spaces = ' '.repeat(Math.max(methodWidth + 6 - row.method.length, 0))\n const action = row.action === 'Closure' ? (row.name ?? '') : row.name === null ? row.action : `${row.name} › ${row.action}`\n const used = row.method.length + spaces.length + row.uri.length + action.length + 6 + (action === '' ? 0 : 1)\n const dots = '.'.repeat(Math.max(width - used, 0))\n return ` ${row.method} ${spaces}${row.uri}${dots === '' ? '' : ` ${dots}`}${action === '' ? '' : ` ${action}`}`\n })\n const count = `Showing [${rows.length}] ${rows.length === 1 ? 'route' : 'routes'}`\n return [...lines, '', `${' '.repeat(Math.max(width - count.length - 2, 0))}${count}`]\n}\n\n/** The routes/api.ts that install:api writes (Laravel's api.stub, with the token guard). */\nexport const API_ROUTES_STUB = `import { request, Route } from '@orieljs/framework'\n\nRoute.get('/user', () => request().user()).middleware('auth:token')\n`\n\n/**\n * Adds `api: 'routes/api.ts'` to withRouting() in bootstrap/app.ts: uncomments a commented `// api:` entry,\n * else inserts it after the `web:` entry, else at the start of withRouting({, else adds a withRouting() call\n * before create(). Returns the source unchanged when api is already there, and undefined when it can't tell where.\n * (Function replacers, so a `$` in the file is never read as a replacement pattern.)\n */\nexport function addApiRouting(source: string): string | undefined {\n const code = source.replace(/^[ \\t]*\\/\\/.*$/gm, '')\n if (/withRouting\\(\\s*\\{[^}]*\\bapi\\s*:/.test(code)) return source\n const commented = /^([ \\t]*)\\/\\/\\s*(api:\\s*['\"`][^'\"`\\n]*['\"`],?)[ \\t]*$/m.exec(source)\n if (commented !== null) return source.replace(commented[0], () => `${commented[1]}${commented[2]}`)\n const web = /^([ \\t]*)web:\\s*(['\"`])[^'\"`\\n]*\\2[ \\t]*,?[ \\t]*$/m.exec(source)\n if (web !== null) {\n const line = web[0].trimEnd()\n return source.replace(web[0], () => `${line.endsWith(',') ? line : `${line},`}\\n${web[1]}api: 'routes/api.ts',`)\n }\n const inline = /withRouting\\(\\s*\\{/.exec(source)\n if (inline !== null) return source.replace(inline[0], () => `${inline[0]} api: 'routes/api.ts',`)\n const create = /^([ \\t]*)\\.create\\(\\)/m.exec(source)\n if (create !== null) return source.replace(create[0], () => `${create[1]}.withRouting({ api: 'routes/api.ts' })\\n${create[0]}`)\n return undefined\n}\n\nexport interface HttpCommandOptions {\n /** Replaces serve() (tests). */\n serve?: (app: Application, options: ServeOptions) => Promise<RunningServer>\n /** The terminal width for route:list. Default: process.stdout.columns, else 120. */\n terminalWidth?: () => number\n /** Replaces `serve --watch`'s restarting server (tests). Resolves the command's exit code. */\n watch?: (options: WatchedServerOptions) => Promise<number>\n}\n\n/**\n * `serve --watch`: claims the port once (`--port`, else PORT, SERVER_PORT, 8000; 0 picks a free one), so every\n * restart serves on the same port and a taken port fails at once, then runs `serve` on it in a child process that\n * restarts when the app's files change. The child is this runtime with its flags and script (`node oriel`,\n * `bun oriel`), in this folder, with the environment this process started with, so an edited .env applies.\n */\nasync function serveWatching(app: Application, out: Io, port: string | undefined, run: (options: WatchedServerOptions) => Promise<number>): Promise<number> {\n const hostname = out.option('host') ?? '127.0.0.1'\n const requested = port !== undefined ? Number(port) : Number(process.env.PORT ?? process.env.SERVER_PORT ?? 8000)\n let claimed: number\n try {\n claimed = await claimPort(hostname, requested)\n } catch (error) {\n out.error(listenFailure(hostname, requested, error))\n return 1\n }\n const script = process.argv[1]\n if (script === undefined) {\n out.error(\"serve --watch can't tell which script started this process, so it can't start the server.\")\n return 1\n }\n return run({\n command: [process.execPath, ...process.execArgv, script, 'serve', `--host=${hostname}`, `--port=${claimed}`],\n cwd: process.cwd(),\n env: serverEnvironment(),\n watch: (onChange) =>\n watchFiles(app.basePath(), onChange, { onError: (folder, error) => out.warn(`Unable to watch [${folder}] for changes: ${error.message}`) }),\n info: (message) => out.info(message),\n error: (message) => out.error(message),\n })\n}\n\n/** Registers `serve`, `route:list` and `install:api` as closure commands (PC1). */\nexport function registerHttpCommands(kernel: ConsoleKernel, app: Application, options: HttpCommandOptions = {}): void {\n const serveApp = options.serve ?? serve\n const terminalWidth = options.terminalWidth ?? (() => process.stdout.columns ?? 120)\n const runWatching = options.watch ?? ((watchOptions: WatchedServerOptions) => new WatchedServer(watchOptions).run())\n\n kernel\n .command(\n 'serve {--host=127.0.0.1 : The host address to serve the application on} {--port= : The port to serve the application on} ' +\n '{--watch : Automatically restart the server when the application is modified}',\n async function (this: CommandContext) {\n const out = io(this)\n const port = out.option('port')\n if (port !== undefined && !/^\\d+$/.test(port)) {\n out.error('The --port option must be a number.')\n return 1\n }\n if (out.flag('watch')) return serveWatching(app, out, port, runWatching)\n const server = await serveApp(app, {\n hostname: out.option('host') ?? '127.0.0.1',\n ...(port !== undefined && { port: Number(port) }),\n onListen: (running) => {\n out.info(`Server running on [${running.url}].`)\n out.line('Press Ctrl+C to stop the server')\n },\n })\n await server.closed\n return 0\n },\n )\n .purpose('Serve the application on the Oriel development server')\n\n kernel\n .command(\n 'route:list {--method= : Filter the routes by method} {--name= : Filter the routes by name} ' +\n '{--path= : Only show routes matching the given path pattern} ' +\n '{--except-path= : Do not display the routes matching the given path pattern} ' +\n '{--reverse : Reverse the ordering of the routes} {--json : Output the route list as JSON}',\n function (this: CommandContext) {\n const out = io(this)\n if (!app.bound(Router)) {\n out.error('The router is not available. Is the Routing service provider registered?')\n return 1\n }\n const all = routeListRows(app.make(Router).getRoutes())\n if (all.length === 0) {\n out.error(\"Your application doesn't have any routes.\")\n return 0\n }\n const rows = filterRouteList(all, {\n ...(out.option('method') !== undefined && { method: out.option('method') }),\n ...(out.option('name') !== undefined && { name: out.option('name') }),\n ...(out.option('path') !== undefined && { path: out.option('path') }),\n ...(out.option('except-path') !== undefined && { exceptPath: out.option('except-path') }),\n })\n if (rows.length === 0) {\n out.error(\"Your application doesn't have any routes matching the given criteria.\")\n return 0\n }\n if (out.flag('reverse')) rows.reverse()\n if (out.flag('json')) {\n out.line(JSON.stringify(rows))\n return 0\n }\n for (const line of formatRouteList(rows, terminalWidth())) out.line(line)\n return 0\n },\n )\n .purpose('List all registered routes')\n\n kernel\n .command('install:api {--force : Overwrite any existing API routes file}', async function (this: CommandContext) {\n const out = io(this)\n const routesFile = app.basePath('routes/api.ts')\n if (existsSync(routesFile) && !out.flag('force')) {\n out.error('API routes file already exists.')\n } else {\n await mkdir(dirname(routesFile), { recursive: true })\n await writeFile(routesFile, API_ROUTES_STUB)\n out.info('Published API routes file.')\n }\n\n const bootstrapFile = app.bootstrapPath('app.ts')\n const source = existsSync(bootstrapFile) ? await readFile(bootstrapFile, 'utf8') : undefined\n const updated = source === undefined ? undefined : addApiRouting(source)\n if (updated === undefined) {\n out.warn(\n 'Unable to automatically add API route definition to bootstrap file. ' +\n \"Add api: 'routes/api.ts' to withRouting() in bootstrap/app.ts.\",\n )\n } else if (updated !== source) {\n await writeFile(bootstrapFile, updated)\n }\n\n out.info('API scaffolding installed.')\n return 0\n })\n .purpose('Create an API routes file and prepare the application for API authentication')\n}\n","import { existsSync, readFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport * as util from 'node:util'\n\n/**\n * This process's environment as it was when the framework loaded, which is before `createApplication()` reads `.env`:\n * that never overwrites a variable, so a server started with the current environment would keep every old value.\n */\nconst launchEnvironment: Readonly<NodeJS.ProcessEnv> = Object.freeze({ ...process.env })\n\n/**\n * Every file Bun may read into process.env from the working directory before any code runs, whatever the NODE_ENV:\n * `.env`, `.env.<mode>`, `.env.local` and `.env.<mode>.local`, for the modes development, production and test.\n */\nexport const BUN_ENV_FILES: readonly string[] = [\n '.env',\n '.env.development',\n '.env.production',\n '.env.test',\n '.env.local',\n '.env.development.local',\n '.env.production.local',\n '.env.test.local',\n]\n\nexport interface ServerEnvironmentOptions {\n /** Default: the environment this process started with (above). */\n launched?: NodeJS.ProcessEnv\n /** Default: whether this process runs on Bun. */\n bun?: boolean\n /** Where Bun read its env files from. Default: the working directory. */\n cwd?: string\n /** Default: `util.parseEnv`, which some supported runtimes lack (passing `undefined` stands for that). */\n parseEnv?: ((content: string) => NodeJS.Dict<string>) | undefined\n}\n\n/** `$NAME` and `${NAME}` replaced with their values, as Bun expands an env file. */\nconst expand = (value: string, env: NodeJS.ProcessEnv): string =>\n value.replace(/\\$\\{([A-Za-z_][A-Za-z0-9_]*)\\}|\\$([A-Za-z_][A-Za-z0-9_]*)/g, (_match, braced?: string, bare?: string) => env[braced ?? bare!] ?? '')\n\n/**\n * The environment for each server `serve --watch` starts: the one this process started with, so the server reads\n * `.env` again and an edit applies. On Bun, which loads its env files before any code runs, a variable whose value is\n * the one in such a file (as written, or expanded) is left out too, so the new process loads it again; a variable set\n * to another value (in the shell) stays.\n */\nexport function serverEnvironment(options: ServerEnvironmentOptions = {}): NodeJS.ProcessEnv {\n const launched = options.launched ?? launchEnvironment\n const env: NodeJS.ProcessEnv = { ...launched }\n if (!(options.bun ?? process.versions.bun !== undefined)) return env\n // util.parseEnv is newer than some supported runtimes (a namespace import, so its absence fails nothing at load):\n // without it the env files are not read, and the environment is the launch copy, as on Node.\n const parseEnv = 'parseEnv' in options ? options.parseEnv : (util.parseEnv as typeof util.parseEnv | undefined)\n if (typeof parseEnv !== 'function') return env\n const cwd = options.cwd ?? process.cwd()\n for (const name of BUN_ENV_FILES) {\n const file = join(cwd, name)\n if (!existsSync(file)) continue\n let values: NodeJS.Dict<string>\n try {\n values = parseEnv(readFileSync(file, 'utf8'))\n } catch {\n continue\n }\n for (const [key, raw] of Object.entries(values)) {\n const value = launched[key]\n if (raw !== undefined && value !== undefined && (value === raw || value === expand(raw, launched))) delete env[key]\n }\n }\n return env\n}\n","import { existsSync, statSync, watch as watchPath } from 'node:fs'\nimport { join } from 'node:path'\n\n/**\n * The folders `serve --watch` watches under the app's base path: the server's code, its configuration, the routes,\n * the server-rendered views and the translations. Not `resources/js` or `resources/css` (Vite's), `public`, `storage`,\n * `database` (the SQLite file changes on every write) or `tests`.\n */\nexport const WATCHED_FOLDERS: readonly string[] = ['app', 'bootstrap', 'config', 'lang', 'resources/lang', 'resources/views', 'routes']\n\n/** Files in the base path itself that restart the server, besides `.env` and `.env.*`. */\nexport const WATCHED_ROOT_FILES: readonly string[] = ['package.json', 'tsconfig.json']\n\n/** Build output inside a watched folder, ignored with everything in it: the SSR bundle (`vite build --ssr`) and caches. */\nconst IGNORED_FOLDERS = ['bootstrap/ssr', 'bootstrap/cache']\n\nconst CODE_FILE = /\\.(?:[cm]?[jt]sx?|json)$/\nconst DECLARATION_FILE = /\\.d\\.[cm]?ts$/\n/** Editor swap and backup files: Vim's `.swp` to `.swa` and `.swx`, `~` backups, JetBrains' safe-write copies. */\nconst EDITOR_FILE = /(?:\\.sw[a-px]|~|___jb_(?:tmp|old)___)$/\n\n/** `.env` and `.env.*` (`.env.local`, `.env.testing`, …), except `.env.example` and editor swap and backup files. */\nexport const isEnvironmentFile = (name: string): boolean =>\n (name === '.env' || name.startsWith('.env.')) && name !== '.env.example' && !EDITOR_FILE.test(name)\n\n/**\n * Whether a change to `path` (relative to the base path, `/`-separated) restarts the server: a TypeScript,\n * JavaScript or JSON file in a watched folder (not a `.d.ts`, nothing under a dot-folder, node_modules or the build\n * output, no editor swap or backup file), a name without an extension there (a folder that was moved or removed, but\n * not the build output's own folders), an env file, `package.json` or `tsconfig.json`.\n */\nexport function isWatchedPath(path: string): boolean {\n const segments = path.split('/')\n if (segments.length === 1) return isEnvironmentFile(path) || WATCHED_ROOT_FILES.includes(path)\n if (!WATCHED_FOLDERS.some((folder) => path.startsWith(`${folder}/`))) return false\n if (IGNORED_FOLDERS.some((folder) => path === folder || path.startsWith(`${folder}/`))) return false\n if (segments.some((segment) => segment.startsWith('.') || segment === 'node_modules')) return false\n const name = segments.at(-1)!\n if (DECLARATION_FILE.test(name)) return false\n return CODE_FILE.test(name) || !name.includes('.')\n}\n\n/** The part of a node:fs FSWatcher used here. */\nexport interface WatchHandle {\n close(): void\n on(event: 'error', listener: (error: Error) => void): unknown\n}\n\n/** node:fs watch(), replaceable in tests. */\nexport type WatchFolder = (\n path: string,\n options: { recursive: boolean },\n listener: (event: string, file: string | null) => void,\n) => WatchHandle\n\nexport interface WatchFilesOptions {\n /** Quiet time after the last change before `onChange` runs, in ms. Default 200 (Node's `--watch`). */\n debounce?: number\n /**\n * For this long after the start (ms), a change to a file last modified before the start, or to a path that doesn't\n * exist, is dropped. Default 1000: Node's watcher on macOS reports what was written just before it started, and the\n * watched folder itself under its own name (`app/app`).\n */\n settle?: number\n /** A folder (relative to the base path, `.` for the base path) that could not be watched, or stopped being. */\n onError?: (folder: string, error: Error) => void\n watch?: WatchFolder\n}\n\nexport interface FileWatcher {\n close(): void\n}\n\nconst toSlashes = (file: string): string => file.split('\\\\').join('/')\n\n/**\n * Watches the base path (not recursively: the env files, package.json, tsconfig.json) and each watched folder that\n * exists (recursively, with the runtime's fs.watch), and calls `onChange` with the changed files once no change has\n * come for `debounce` ms. A folder created later is watched from the next start; a file removed in the first second\n * (`settle`) counts only with the next change.\n */\nexport function watchFiles(basePath: string, onChange: (files: string[]) => void, options: WatchFilesOptions = {}): FileWatcher {\n const watch: WatchFolder = options.watch ?? ((path, watchOptions, listener) => watchPath(path, watchOptions, listener))\n const debounce = options.debounce ?? 200\n const onError = options.onError ?? (() => {})\n const changed = new Set<string>()\n let timer: ReturnType<typeof setTimeout> | undefined\n const settle = options.settle ?? 1000\n const startedAt = Date.now()\n /** A change reported in the settle time for something that didn't change since the start (1 ms: Date.now() is whole ms). */\n const reportedLate = (path: string): boolean => {\n if (Date.now() - startedAt >= settle) return false\n try {\n const modified = statSync(join(basePath, path), { throwIfNoEntry: false })?.mtimeMs\n return modified === undefined || modified < startedAt + 1\n } catch {\n return false\n }\n }\n\n const record = (path: string) => {\n if (!isWatchedPath(path) || reportedLate(path)) return\n changed.add(path)\n clearTimeout(timer)\n timer = setTimeout(() => {\n const files = [...changed]\n changed.clear()\n onChange(files)\n }, debounce)\n }\n\n const handles: WatchHandle[] = []\n const start = (folder: string, recursive: boolean, toPath: (file: string | null) => string | undefined) => {\n try {\n const handle = watch(folder === '.' ? basePath : join(basePath, folder), { recursive }, (_event, file) => {\n const path = toPath(file)\n if (path !== undefined) record(path)\n })\n handle.on('error', (error) => onError(folder, error))\n handles.push(handle)\n } catch (error) {\n onError(folder, error as Error)\n }\n }\n\n start('.', false, (file) => (file === null ? undefined : toSlashes(file)))\n for (const folder of WATCHED_FOLDERS) {\n if (existsSync(join(basePath, folder))) start(folder, true, (file) => `${folder}/${file === null ? '' : toSlashes(file)}`)\n }\n\n return {\n close() {\n clearTimeout(timer)\n changed.clear()\n for (const handle of handles) handle.close()\n },\n }\n}\n","import { createServer, type AddressInfo } from 'node:net'\nimport { displayHost } from '../server/types'\n\n/**\n * Listens on the port, then lets it go: the port a server can listen on (a free one for 0). Rejects as listen() does\n * (EADDRINUSE, EACCES, a port out of range). `serve --watch` calls it once, so every restart serves on the same port.\n */\nexport function claimPort(hostname: string, port: number): Promise<number> {\n return new Promise((resolve, reject) => {\n const server = createServer()\n server.once('error', reject)\n try {\n server.listen({ port, host: hostname, exclusive: true }, () => {\n const { port: claimed } = server.address() as AddressInfo\n server.close(() => resolve(claimed))\n })\n } catch (error) {\n reject(error)\n }\n })\n}\n\nconst REASONS: Record<string, string> = {\n EADDRINUSE: 'Address already in use',\n EACCES: 'Permission denied',\n EADDRNOTAVAIL: \"Can't assign requested address\",\n}\n\n/** PHP's built-in server's message, which Laravel's serve shows: `Failed to listen on 127.0.0.1:8000 (reason: Address already in use)`. */\nexport function listenFailure(hostname: string, port: number, error: unknown): string {\n const { code, message } = error as NodeJS.ErrnoException\n return `Failed to listen on ${displayHost(hostname)}:${port} (reason: ${(code !== undefined && REASONS[code]) || message})`\n}\n","import { spawn as spawnProcess, type ChildProcess, type SpawnOptions } from 'node:child_process'\nimport { isEnvironmentFile, type FileWatcher } from './files'\n\n/** node:child_process's spawn(), replaceable in tests. */\nexport type SpawnServer = (command: string, args: string[], options: SpawnOptions) => ChildProcess\n\nexport interface WatchedServerOptions {\n /** The server's command line: the runtime, its flags, the CLI script, then `serve --host=… --port=…`. */\n command: readonly string[]\n cwd: string\n env: NodeJS.ProcessEnv\n /** Starts watching: calls back with the changed files (relative to the base path) once they settle. */\n watch(onChange: (files: string[]) => void): FileWatcher\n info(message: string): void\n error(message: string): void\n /** How long a server may take to stop before it is killed, in ms. Default 15000 (serve gives requests 10 s). */\n stopTimeout?: number\n /** The signals that stop it. Default SIGINT, SIGTERM and SIGHUP. */\n signals?: readonly NodeJS.Signals[]\n spawn?: SpawnServer\n}\n\ninterface Running {\n child: ChildProcess\n /** Resolves once the process has exited (or could not start). */\n exited: Promise<void>\n /** This side asked it to stop: its exit is not reported. */\n stopping: boolean\n /** Killed after stopTimeout (reported once). */\n killed: boolean\n}\n\n/**\n * `serve --watch`: runs `serve` in a child process and starts a new one after every change, on the same port. The\n * old server is stopped (SIGTERM, which serve answers by finishing its requests) and has exited before the next one\n * starts, so the port is free. Changes that come during a restart are read by the server it starts. A server that\n * exits by itself (a syntax error, a crash) is reported and the next change starts one, so this process keeps running.\n * SIGINT, SIGTERM and SIGHUP stop the server and end run(); a second one kills the server at once.\n */\nexport class WatchedServer {\n private running: Running | undefined\n private restarting = false\n private stopping = false\n private finish: (code: number) => void = () => {}\n\n constructor(private readonly options: WatchedServerOptions) {}\n\n /** Starts the server and keeps it current until stopped. Resolves 0 once the last server has exited. */\n run(): Promise<number> {\n const done = new Promise<number>((resolve) => (this.finish = resolve))\n const stopListening = this.listenForSignals()\n const watcher = this.options.watch((files) => void this.changed(files))\n this.start()\n return done.finally(() => {\n watcher.close()\n stopListening()\n })\n }\n\n /** Stops the server and ends run(); called again, kills the server at once. */\n stop(): void {\n if (this.stopping) {\n this.running?.child.kill('SIGKILL')\n return\n }\n this.stopping = true\n void this.stopServer().then(() => this.finish(0))\n }\n\n private async changed(files: string[]): Promise<void> {\n if (this.stopping || this.restarting || files.length === 0) return\n this.restarting = true\n try {\n this.options.info(\n files.some(isEnvironmentFile) ? 'Environment modified. Restarting server...' : `Application change detected in [${files[0]}]. Restarting server...`,\n )\n await this.stopServer()\n if (!this.stopping) this.start()\n } finally {\n this.restarting = false\n }\n }\n\n private start(): void {\n const [command, ...args] = this.options.command\n const child = (this.options.spawn ?? spawnProcess)(command!, args, {\n cwd: this.options.cwd,\n env: this.options.env,\n stdio: ['ignore', 'inherit', 'inherit'],\n })\n const running: Running = { child, stopping: false, killed: false, exited: Promise.resolve() }\n running.exited = new Promise<void>((resolve) => {\n let settled = false\n const settle = (report: string) => {\n if (settled) return\n settled = true\n if (this.running === running) this.running = undefined\n if (!running.stopping && !this.stopping) this.options.error(`${report}. Waiting for changes before restarting...`)\n resolve()\n }\n child.once('exit', (code, signal) => settle(signal !== null ? `The server stopped (signal ${signal})` : `The server stopped (exit code ${code})`))\n // 'error' also comes when a signal can't be sent: only a process that never started has ended with it.\n child.once('error', (error) => {\n if (child.pid === undefined) settle(`The server could not start (${error.message})`)\n })\n })\n this.running = running\n }\n\n /** Sends SIGTERM once and waits for the exit, killing the server after stopTimeout. */\n private async stopServer(): Promise<void> {\n const running = this.running\n if (running === undefined) return\n if (!running.stopping) {\n running.stopping = true\n running.child.kill('SIGTERM')\n }\n const timeout = this.options.stopTimeout ?? 15_000\n const timer = setTimeout(() => {\n if (running.killed) return\n running.killed = true\n this.options.error(`The server did not stop within ${timeout / 1000} seconds and was killed.`)\n running.child.kill('SIGKILL')\n }, timeout)\n try {\n await running.exited\n } finally {\n clearTimeout(timer)\n }\n }\n\n private listenForSignals(): () => void {\n const signals = this.options.signals ?? (['SIGINT', 'SIGTERM', 'SIGHUP'] as const)\n const handler = () => this.stop()\n for (const signal of signals) process.on(signal, handler)\n return () => {\n for (const signal of signals) process.off(signal, handler)\n }\n }\n}\n","import { ConsoleKernel, ExceptionHandler, HttpKernel, Redirector, ResponseFactory, Router } from '@orieljs/contracts'\nimport { ServiceProvider } from '@orieljs/support'\nimport { registerHttpCommands } from './commands'\nimport { ErrorHandler } from './ErrorHandler'\nimport { applyExceptionCallbacks } from './ExceptionsConfiguration'\nimport { HttpRedirector } from './HttpRedirector'\nimport { HttpResponseFactory } from './HttpResponseFactory'\nimport { Kernel } from './Kernel'\nimport { applyMiddlewareCallbacks } from './MiddlewareConfiguration'\n\n/**\n * Binds the HTTP kernel (replacing any kernel bound before, such as Foundation's ClosureKernel), the exception\n * handler, the response factory and the redirector, and merges the `http` config defaults.\n *\n * The HttpRequest is deliberately NOT bound on the application: the kernel creates one per request and puts it in\n * the request scope with scope.instance(). A root `scoped()` binding would make bound(HttpRequest) true everywhere,\n * and that check is how the URL generator, the redirects and the helpers know they are inside a request.\n */\nexport class HttpServiceProvider extends ServiceProvider {\n override register(): void {\n this.mergeConfigFrom(\n {\n trusted_proxies: [],\n max_body_size: 8 * 1024 * 1024,\n max_json_depth: 512,\n csrf_except: [],\n redirect_guests_to: undefined,\n redirect_users_to: undefined,\n },\n 'http',\n )\n this.app.singleton(HttpKernel, () => new Kernel(this.app))\n this.app.singleton(ExceptionHandler, () => {\n const handler = new ErrorHandler(this.app)\n applyExceptionCallbacks(this.app, handler)\n return handler\n })\n this.app.singleton(ResponseFactory, () => new HttpResponseFactory())\n this.app.singleton(Redirector, () => new HttpRedirector())\n }\n\n override boot(): void {\n // After every provider's boot(), so web({ remove }) and alias() overrides see the components' defaults.\n this.app.booted(() => {\n const kernel = this.app.make(HttpKernel)\n if (kernel instanceof Kernel && this.app.bound(Router)) applyMiddlewareCallbacks(this.app, kernel)\n })\n if (this.app.bound(ConsoleKernel)) registerHttpCommands(this.app.make(ConsoleKernel), this.app)\n }\n}\n","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> = { '&': '&', '<': '<', '>': '>', '\"': '"', \"'\": ''' }\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","/** A date the tests travel to: a Date, an ISO string or milliseconds since the epoch. */\nexport type TravelDate = Date | string | number\n\n/** The Date in place before the first travel; travelBack() puts it back. */\nlet original: DateConstructor | undefined\n/** Where the clock stands while travelling (milliseconds since the epoch), like Carbon::setTestNow(). */\nlet testNow: number | undefined\n\nconst realDate = (): DateConstructor => original ?? globalThis.Date\n\n/**\n * Swaps in a Date whose `new Date()`, `Date()` and `Date.now()` read the test time. Everything else (dates with\n * arguments, the statics, instanceof, the prototype) is the original Date's.\n */\nfunction install(): void {\n if (original !== undefined) return\n const Real = (original = globalThis.Date)\n const current = (): number => testNow ?? Real.now()\n const Travelling: DateConstructor = new Proxy(Real, {\n construct: (target, args: unknown[], newTarget) => Reflect.construct(target, args.length === 0 ? [current()] : args, newTarget === Travelling ? target : newTarget) as object,\n apply: (target) => new target(current()).toString(),\n get: (target, property) => (property === 'now' ? current : Reflect.get(target, property, target)),\n })\n globalThis.Date = Travelling\n}\n\nfunction setTestNow(date: TravelDate): Date {\n const time = new (realDate())(date).getTime()\n if (Number.isNaN(time)) throw new TypeError(`Invalid date: ${String(date)}`)\n install()\n testNow = time\n return new (realDate())(time)\n}\n\n/** Runs `callback`, then travels back to the real time: once it returns, or once its promise settles. */\nfunction thenTravelBack<R>(callback: () => R): R {\n let result: R\n try {\n result = callback()\n } catch (error) {\n travelBack()\n throw error\n }\n if (result instanceof Promise) return result.finally(travelBack) as R\n travelBack()\n return result\n}\n\n/**\n * Laravel's travelTo(): the clock stands at `date` (new Date(), Date.now() and now() all read it) until travelBack().\n * With a callback, it runs there and the clock travels back after it; its result is returned.\n */\nexport function travelTo(date: TravelDate): void\nexport function travelTo<R>(date: TravelDate, callback: (date: Date) => R): R\nexport function travelTo<R>(date: TravelDate, callback?: (date: Date) => R): R | void {\n const at = setTestNow(date)\n if (callback) return thenTravelBack(() => callback(at))\n}\n\n/** Laravel's travelBack(): the real clock again. Returns the real time. */\nexport function travelBack(): Date {\n if (original !== undefined) globalThis.Date = original\n original = undefined\n testNow = undefined\n return new Date()\n}\n\n/** Laravel's freezeTime(): holds the clock where it is now. Returns that time, or the callback's result. */\nexport function freezeTime(): Date\nexport function freezeTime<R>(callback: (date: Date) => R): R\nexport function freezeTime<R>(callback?: (date: Date) => R): Date | R {\n const at = new (realDate())(testNow ?? Date.now())\n if (callback) return travelTo(at, callback)\n travelTo(at)\n return at\n}\n\n/** Laravel's freezeSecond(): freezeTime() at the start of the current second. */\nexport function freezeSecond(): Date\nexport function freezeSecond<R>(callback: (date: Date) => R): R\nexport function freezeSecond<R>(callback?: (date: Date) => R): Date | R {\n const at = new (realDate())(testNow ?? Date.now())\n at.setMilliseconds(0)\n if (callback) return travelTo(at, callback)\n travelTo(at)\n return at\n}\n\n/** Laravel's travel(5).minutes(): moves the clock on (a negative value moves it back) from where it stands. */\nexport function travel(value: number): Wormhole {\n return new Wormhole(value)\n}\n\n/**\n * Laravel's Wormhole: each unit moves the clock by `value` of it (months and years overflow as Carbon's do: 31 January\n * plus a month is 3 March), in UTC. With a callback, it runs there, the clock travels back after it, and its result is\n * returned. JavaScript dates hold milliseconds, so there are no microseconds.\n */\nexport class Wormhole {\n constructor(readonly value: number) {}\n\n millisecond(): void\n millisecond<R>(callback: () => R): R\n millisecond<R>(callback?: () => R): R | void {\n return this.milliseconds(callback as () => R)\n }\n\n milliseconds(): void\n milliseconds<R>(callback: () => R): R\n milliseconds<R>(callback?: () => R): R | void {\n return this.#move((date) => date.setTime(date.getTime() + this.value), callback)\n }\n\n second(): void\n second<R>(callback: () => R): R\n second<R>(callback?: () => R): R | void {\n return this.seconds(callback as () => R)\n }\n\n seconds(): void\n seconds<R>(callback: () => R): R\n seconds<R>(callback?: () => R): R | void {\n return this.#move((date) => date.setTime(date.getTime() + this.value * 1000), callback)\n }\n\n minute(): void\n minute<R>(callback: () => R): R\n minute<R>(callback?: () => R): R | void {\n return this.minutes(callback as () => R)\n }\n\n minutes(): void\n minutes<R>(callback: () => R): R\n minutes<R>(callback?: () => R): R | void {\n return this.#move((date) => date.setTime(date.getTime() + this.value * 60_000), callback)\n }\n\n hour(): void\n hour<R>(callback: () => R): R\n hour<R>(callback?: () => R): R | void {\n return this.hours(callback as () => R)\n }\n\n hours(): void\n hours<R>(callback: () => R): R\n hours<R>(callback?: () => R): R | void {\n return this.#move((date) => date.setTime(date.getTime() + this.value * 3_600_000), callback)\n }\n\n day(): void\n day<R>(callback: () => R): R\n day<R>(callback?: () => R): R | void {\n return this.days(callback as () => R)\n }\n\n days(): void\n days<R>(callback: () => R): R\n days<R>(callback?: () => R): R | void {\n return this.#move((date) => date.setUTCDate(date.getUTCDate() + this.value), callback)\n }\n\n week(): void\n week<R>(callback: () => R): R\n week<R>(callback?: () => R): R | void {\n return this.weeks(callback as () => R)\n }\n\n weeks(): void\n weeks<R>(callback: () => R): R\n weeks<R>(callback?: () => R): R | void {\n return this.#move((date) => date.setUTCDate(date.getUTCDate() + this.value * 7), callback)\n }\n\n month(): void\n month<R>(callback: () => R): R\n month<R>(callback?: () => R): R | void {\n return this.months(callback as () => R)\n }\n\n months(): void\n months<R>(callback: () => R): R\n months<R>(callback?: () => R): R | void {\n return this.#move((date) => date.setUTCMonth(date.getUTCMonth() + this.value), callback)\n }\n\n year(): void\n year<R>(callback: () => R): R\n year<R>(callback?: () => R): R | void {\n return this.years(callback as () => R)\n }\n\n years(): void\n years<R>(callback: () => R): R\n years<R>(callback?: () => R): R | void {\n return this.#move((date) => date.setUTCFullYear(date.getUTCFullYear() + this.value), callback)\n }\n\n /** Laravel's Wormhole::back(). */\n static back(): Date {\n return travelBack()\n }\n\n #move<R>(step: (date: Date) => unknown, callback: (() => R) | undefined): R | void {\n const date = new (realDate())(testNow ?? Date.now())\n step(date)\n setTestNow(date)\n if (callback) return thenTravelBack(callback)\n }\n}\n","import { ConsoleKernel, type Application } from '@orieljs/contracts'\nimport { assert } from '../assert'\n\ntype Check = (output: string, lines: string[], exitCode: number) => void\n\n/**\n * Laravel's PendingCommand: `await t.artisan('inspire').expectsOutput('…').assertExitCode(0)`.\n * It runs through ConsoleKernel.call() when awaited (or run()), then checks every expectation against the\n * buffered output (stdout then stderr, as ConsoleKernel.output() returns it) and the exit code.\n *\n * The result must be awaited (or run() called): unlike Laravel, where the command runs when the\n * PendingCommand is destroyed, nothing runs here until then, so an un-awaited `t.artisan(...)` never runs\n * and checks nothing.\n */\nexport class PendingCommand implements PromiseLike<number> {\n private readonly checks: Check[] = []\n private result: Promise<number> | undefined\n\n constructor(\n private readonly app: Application,\n readonly command: string,\n readonly parameters: Record<string, unknown> = {},\n ) {}\n\n /** A line of output equals `line` exactly; with no argument, the command printed something. */\n expectsOutput(line?: string): this {\n this.checks.push((output, lines) => {\n if (line === undefined) assert(output !== '', 'The command was expected to print output, but printed nothing.')\n else assert(lines.includes(line), `Output \"${line}\" was not printed.\\n\\nOutput:\\n${output}`, { actual: output, expected: line })\n })\n return this\n }\n\n /** No line equals `line`; with no argument, the command printed nothing at all. */\n doesntExpectOutput(line?: string): this {\n this.checks.push((output, lines) => {\n if (line === undefined) assert(output === '', `The command printed output unexpectedly:\\n${output}`, { actual: output, expected: '' })\n else assert(!lines.includes(line), `Output \"${line}\" was printed.`)\n })\n return this\n }\n\n expectsOutputToContain(text: string): this {\n this.checks.push((output) => assert(output.includes(text), `Output does not contain \"${text}\".\\n\\nOutput:\\n${output}`, { actual: output, expected: text }))\n return this\n }\n\n doesntExpectOutputToContain(text: string): this {\n this.checks.push((output) => assert(!output.includes(text), `Output \"${text}\" was printed.`))\n return this\n }\n\n assertExitCode(code: number): this {\n this.checks.push((_output, _lines, exitCode) =>\n assert(exitCode === code, `Expected status code ${code} but received ${exitCode}.`, { actual: exitCode, expected: code }),\n )\n return this\n }\n\n assertNotExitCode(code: number): this {\n this.checks.push((_output, _lines, exitCode) => assert(exitCode !== code, `Unexpected status code ${code} was received.`))\n return this\n }\n\n assertSuccessful(): this {\n return this.assertExitCode(0)\n }\n\n assertOk(): this {\n return this.assertSuccessful()\n }\n\n assertFailed(): this {\n return this.assertNotExitCode(0)\n }\n\n /** Runs the command once and checks the expectations; resolves to the exit code. */\n run(): Promise<number> {\n return (this.result ??= this.execute())\n }\n\n then<R1 = number, R2 = never>(\n onfulfilled?: ((value: number) => R1 | PromiseLike<R1>) | null,\n onrejected?: ((reason: unknown) => R2 | PromiseLike<R2>) | null,\n ): Promise<R1 | R2> {\n return this.run().then(onfulfilled, onrejected)\n }\n\n private async execute(): Promise<number> {\n if (!this.app.bound(ConsoleKernel)) throw new Error(`Cannot run [${this.command}]: the Console component (ConsoleKernel) is not registered.`)\n const kernel = this.app.make(ConsoleKernel)\n const exitCode = await kernel.call(this.command, this.parameters)\n const output = kernel.output()\n const lines = output.split('\\n').map((line) => line.replace(/\\r$/, ''))\n for (const check of this.checks) check(output, lines, exitCode)\n return exitCode\n }\n}\n","import { AssertionError } from 'node:assert'\nimport { isDeepStrictEqual } from 'node:util'\n\n/** Fails the current test. `actual`/`expected` make Vitest print a diff. */\nexport function fail(message: string, details: { actual?: unknown; expected?: unknown } = {}): never {\n const error = new AssertionError({ message, actual: details.actual, expected: details.expected, operator: 'fail' })\n // Node's `diff: 'simple'` would be printed by Vitest as the diff itself; Vitest computes its own from actual/expected.\n delete (error as { diff?: unknown }).diff\n Error.captureStackTrace?.(error, fail)\n throw error\n}\n\nexport function assert(condition: unknown, message: string | (() => string), details?: { actual?: unknown; expected?: unknown }): asserts condition {\n if (!condition) fail(typeof message === 'function' ? message() : message, details)\n}\n\n/** Readable form of any value for failure messages. */\nexport function format(value: unknown): string {\n if (typeof value === 'string') return JSON.stringify(value)\n if (typeof value === 'function') return value.name === '' ? '[Function]' : `[Function ${value.name}]`\n try {\n return JSON.stringify(value, (_key, item: unknown) => (typeof item === 'bigint' ? `${item}n` : item)) ?? String(value)\n } catch {\n return String(value)\n }\n}\n\n/** Laravel's e() (Testing can't import @orieljs/view). */\nexport function escapeHtml(value: string): string {\n return value.replace(/[&<>\"']/g, (char) => ({ '&': '&', '<': '<', '>': '>', '\"': '"', \"'\": ''' })[char]!)\n}\n\nexport function stripTags(html: string): string {\n return html.replace(/<[^>]*>/g, '')\n}\n\n/** Deep equality ignoring object key order (Laravel canonicalizes both sides before comparing). */\nexport function equals(a: unknown, b: unknown): boolean {\n return isDeepStrictEqual(canonical(a), canonical(b))\n}\n\nfunction canonical(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(canonical)\n if (typeof value === 'object' && value !== null && Object.getPrototypeOf(value) === Object.prototype) {\n return Object.fromEntries(Object.keys(value).sort().map((key) => [key, canonical((value as Record<string, unknown>)[key])]))\n }\n return value\n}\n\n/** Laravel's assertArraySubset: every key of `subset` exists in `actual` with a matching value (recursively). */\nexport function isSubset(subset: unknown, actual: unknown): boolean {\n if (typeof subset !== 'object' || subset === null) return equals(subset, actual)\n if (typeof actual !== 'object' || actual === null) return false\n if (Array.isArray(subset) !== Array.isArray(actual)) return false\n return Object.entries(subset).every(([key, value]) => Object.hasOwn(actual, key) && isSubset(value, (actual as Record<string, unknown>)[key]))\n}\n\n/** Every object anywhere in the tree. */\nexport function* objectsIn(value: unknown): Generator<Record<string, unknown>> {\n if (typeof value !== 'object' || value === null) return\n if (!Array.isArray(value)) yield value as Record<string, unknown>\n for (const child of Object.values(value)) yield* objectsIn(child)\n}\n\n/** Some object in the tree has `key` with a value equal to `expected` (a JSON fragment pair). */\nexport function containsPair(tree: unknown, key: string, expected: unknown): boolean {\n for (const object of objectsIn(tree)) if (Object.hasOwn(object, key) && isSubset(expected, object[key])) return true\n return false\n}\n\n/** Laravel's JSON structure: `['id', { author: ['name'] }]`, and `'*'` for \"every element\". */\nexport type JsonStructure = Array<string | { [key: string]: JsonStructure }> | { [key: string]: JsonStructure }\n\nexport function assertStructure(structure: JsonStructure, data: unknown, path = ''): void {\n const at = (key: string) => (path === '' ? key : `${path}.${key}`)\n const hasKey = (key: string) => typeof data === 'object' && data !== null && Object.hasOwn(data, key)\n if (Array.isArray(structure)) {\n for (const item of structure) {\n if (typeof item === 'string') assert(hasKey(item), `Failed asserting that the JSON has the key [${at(item)}].`, { actual: data })\n else assertStructure(item, data, path)\n }\n return\n }\n for (const [key, nested] of Object.entries(structure)) {\n if (key === '*') {\n assert(Array.isArray(data) || (typeof data === 'object' && data !== null), `Failed asserting that [${path || 'the JSON'}] is a list.`, { actual: data })\n for (const [index, element] of Object.entries(data as object)) assertStructure(nested, element, at(index))\n continue\n }\n assert(hasKey(key), `Failed asserting that the JSON has the key [${at(key)}].`, { actual: data })\n assertStructure(nested, (data as Record<string, unknown>)[key], at(key))\n }\n}\n","import { DatabaseManager, type ModelInstance, type Row } from '@orieljs/contracts'\nimport * as db from '../Database/assertions'\nimport type { TableOrModel } from '../Database/assertions'\nimport { runCommand } from '../Database/traits'\nimport { MakesHttpRequests } from './MakesHttpRequests'\n\n/** Laravel's InteractsWithDatabase: database assertions and seeding, plus the options RefreshDatabase reads. */\nexport abstract class InteractsWithDatabase extends MakesHttpRequests {\n /** Seed after RefreshDatabase/DatabaseMigrations migrate (Laravel's $seed). */\n seed = false\n /** Seed with this seeder class instead of DatabaseSeeder (Laravel's $seeder). */\n seeder: string | undefined = undefined\n /** Connections RefreshDatabase/DatabaseTransactions wrap in a transaction (undefined = the default connection). */\n connectionsToTransact: Array<string | undefined> = [undefined]\n\n protected get database(): DatabaseManager {\n return this.app.make(DatabaseManager)\n }\n\n async assertDatabaseHas(table: TableOrModel, data: Row, connection?: string): Promise<this> {\n await db.assertDatabaseHas(this.database, table, data, connection)\n return this\n }\n\n async assertDatabaseMissing(table: TableOrModel, data: Row, connection?: string): Promise<this> {\n await db.assertDatabaseMissing(this.database, table, data, connection)\n return this\n }\n\n async assertDatabaseCount(table: TableOrModel, count: number, connection?: string): Promise<this> {\n await db.assertDatabaseCount(this.database, table, count, connection)\n return this\n }\n\n async assertDatabaseEmpty(table: TableOrModel, connection?: string): Promise<this> {\n return this.assertDatabaseCount(table, 0, connection)\n }\n\n async assertModelExists(model: ModelInstance): Promise<this> {\n return this.assertDatabaseHas(model, { [model.getKeyName()]: model.getKey() })\n }\n\n async assertModelMissing(model: ModelInstance): Promise<this> {\n return this.assertDatabaseMissing(model, { [model.getKeyName()]: model.getKey() })\n }\n\n async assertSoftDeleted(table: TableOrModel, data: Row = {}, connection?: string, deletedAtColumn = 'deleted_at'): Promise<this> {\n await db.assertSoftDeleted(this.database, table, data, connection, deletedAtColumn)\n return this\n }\n\n async assertNotSoftDeleted(table: TableOrModel, data: Row = {}, connection?: string, deletedAtColumn = 'deleted_at'): Promise<this> {\n await db.assertNotSoftDeleted(this.database, table, data, connection, deletedAtColumn)\n return this\n }\n\n /** Runs `db:seed` (with a seeder class name, like Laravel's $this->seed(UserSeeder::class)). */\n async runSeeder(seeder?: string): Promise<this> {\n await runCommand(this.app, 'db:seed', seeder === undefined ? {} : { '--class': seeder })\n return this\n }\n}\n","import type { DatabaseConnection, DatabaseManager, ModelInstance, QueryBuilder, Row } from '@orieljs/contracts'\nimport { assert, fail } from '../assert'\n\n/** A table name, or a model (its table, and its connection when it has one). */\nexport type TableOrModel = string | ModelInstance\n\ntype SoftDeletable = ModelInstance & { getDeletedAtColumn?(): string; getConnectionName?(): string | undefined }\n\nconst SHOW = 3\n\nfunction target(db: DatabaseManager, table: TableOrModel, connection?: string): { table: string; connection: DatabaseConnection } {\n if (typeof table === 'string') return { table, connection: db.connection(connection) }\n return { table: table.getTable(), connection: db.connection(connection ?? (table as SoftDeletable).getConnectionName?.()) }\n}\n\n/** where() per attribute; null matches IS NULL (Laravel's where($column, null)). */\nfunction constrain(query: QueryBuilder, data: Row): QueryBuilder {\n for (const [column, value] of Object.entries(data)) {\n if (value === null) query.whereNull(column)\n else query.where(column, value)\n }\n return query\n}\n\nasync function similar(connection: DatabaseConnection, table: string, data: Row): Promise<string> {\n const query = connection.table(table)\n const columns = Object.keys(data)\n if (columns.length > 0) query.select(...columns)\n const rows = (await query.limit(SHOW).get()).all()\n if (rows.length === 0) return 'The table is empty.'\n return `Found similar results: ${JSON.stringify(rows, null, 2)}`\n}\n\nexport async function assertDatabaseHas(db: DatabaseManager, table: TableOrModel, data: Row, connection?: string): Promise<void> {\n const t = target(db, table, connection)\n if ((await constrain(t.connection.table(t.table), data).count()) > 0) return\n fail(`Failed asserting that a row in the table [${t.table}] matches the attributes ${JSON.stringify(data, null, 2)}.\\n\\n${await similar(t.connection, t.table, data)}`)\n}\n\nexport async function assertDatabaseMissing(db: DatabaseManager, table: TableOrModel, data: Row, connection?: string): Promise<void> {\n const t = target(db, table, connection)\n const count = await constrain(t.connection.table(t.table), data).count()\n assert(count === 0, `Failed asserting that a row in the table [${t.table}] does not match the attributes ${JSON.stringify(data, null, 2)}.`)\n}\n\nexport async function assertDatabaseCount(db: DatabaseManager, table: TableOrModel, expected: number, connection?: string): Promise<void> {\n const t = target(db, table, connection)\n const actual = await t.connection.table(t.table).count()\n assert(actual === expected, `Failed asserting that table [${t.table}] matches expected entries count of ${expected}. Entries found: ${actual}.`, { actual, expected })\n}\n\nfunction softDeleteTarget(db: DatabaseManager, table: TableOrModel, data: Row, connection: string | undefined, deletedAtColumn: string) {\n if (typeof table === 'string') return { ...target(db, table, connection), data, column: deletedAtColumn }\n const model = table as SoftDeletable\n return { ...target(db, model, connection), data: { [model.getKeyName()]: model.getKey() }, column: model.getDeletedAtColumn?.() ?? deletedAtColumn }\n}\n\nexport async function assertSoftDeleted(db: DatabaseManager, table: TableOrModel, data: Row = {}, connection?: string, deletedAtColumn = 'deleted_at'): Promise<void> {\n const t = softDeleteTarget(db, table, data, connection, deletedAtColumn)\n const count = await constrain(t.connection.table(t.table), t.data).whereNotNull(t.column).count()\n assert(count > 0, `Failed asserting that any soft deleted row in the table [${t.table}] matches the attributes ${JSON.stringify(t.data, null, 2)}.`)\n}\n\nexport async function assertNotSoftDeleted(db: DatabaseManager, table: TableOrModel, data: Row = {}, connection?: string, deletedAtColumn = 'deleted_at'): Promise<void> {\n const t = softDeleteTarget(db, table, data, connection, deletedAtColumn)\n const count = await constrain(t.connection.table(t.table), t.data).whereNull(t.column).count()\n assert(count > 0, `Failed asserting that any existing row in the table [${t.table}] matches the attributes ${JSON.stringify(t.data, null, 2)}.`)\n}\n","import { ConfigRepository, ConsoleKernel, DatabaseManager, type Application, type DatabaseConnection } from '@orieljs/contracts'\nimport type { InteractsWithApplication, TestTrait } from '../Concerns/InteractsWithApplication'\n\n/** Options a test case may declare (InteractsWithDatabase declares them): Laravel's $seed, $seeder, $connectionsToTransact. */\nexport interface DatabaseTestOptions {\n seed?: boolean\n seeder?: string\n connectionsToTransact?: Array<string | undefined>\n /**\n * Replaces the once-per-process `migrate:fresh` that RefreshDatabase runs on a file or server database, for a test\n * case that must not wipe the whole database. It must leave the schema migrated, and seeded when seed/seeder ask\n * for it. (Laravel's migrateFreshUsing() returns options for migrate:fresh; here it replaces the command.)\n */\n migrateFreshUsing?(): void | Promise<void>\n}\n\ntype DatabaseTest = InteractsWithApplication & DatabaseTestOptions\n\n/** Laravel's RefreshDatabaseState: the schema is migrated once per process (per worker). */\nexport const RefreshDatabaseState = { migrated: false }\n\n/** Runs a console command through the ConsoleKernel contract; a non-zero exit fails the test with its output. */\nexport async function runCommand(app: Application, command: string, parameters: Record<string, unknown> = {}): Promise<void> {\n if (!app.bound(ConsoleKernel)) throw new Error(`Running [${command}] needs the Console component (ConsoleKernel is not bound).`)\n const kernel = app.make(ConsoleKernel)\n const code = await kernel.call(command, parameters)\n if (code !== 0) throw new Error(`[${command}] failed with exit code ${code}:\\n${kernel.output()}`)\n}\n\n/** Laravel's migrateUsing()/migrateFreshUsing(): a --seeder class alone seeds; otherwise --seed when $seed is set. */\nfunction seedOptions(test: DatabaseTest): Record<string, unknown> {\n if (test.seeder !== undefined) return { '--seeder': test.seeder }\n return test.seed === true ? { '--seed': true } : {}\n}\n\n/** Laravel's usingInMemoryDatabase(): the default connection's database is ':memory:'. */\nexport function usingInMemoryDatabase(app: Application): boolean {\n const config = app.make(ConfigRepository)\n const name = config.get<string | undefined>('database.default')\n return name !== undefined && config.get(`database.connections.${name}.database`) === ':memory:'\n}\n\nfunction connectionsOf(test: DatabaseTest): DatabaseConnection[] {\n const db = test.app.make(DatabaseManager)\n return (test.connectionsToTransact ?? [undefined]).map((name) => db.connection(name))\n}\n\n/**\n * Laravel's beginDatabaseTransaction(): a transaction on each connection, held open for the whole test. Teardown\n * rolls each connection back to the level it had before, so a transaction the test left open is undone too.\n */\nasync function beginTransactions(test: DatabaseTest, connections: DatabaseConnection[]): Promise<void> {\n const levels = connections.map((connection) => connection.transactionLevel())\n for (const connection of connections) await connection.beginTransaction()\n test.beforeApplicationDestroyed(async () => {\n for (const [index, connection] of [...connections.entries()].reverse()) await rollBackTo(connection, levels[index] ?? 0)\n })\n}\n\nasync function rollBackTo(connection: DatabaseConnection, level: number): Promise<void> {\n let current = connection.transactionLevel()\n while (current > level) {\n await connection.rollBack()\n const next = connection.transactionLevel()\n if (next >= current) return // the connection didn't unwind (it was closed); don't spin\n current = next\n }\n}\n\n/**\n * Laravel's RefreshDatabase.\n * - In-memory SQLite: every test's new application has an empty database, so it just runs `migrate`.\n * - Otherwise: `migrate:fresh` once per process (or the test's own migrateFreshUsing()), then each test runs inside a\n * transaction that is rolled back.\n */\nexport const RefreshDatabase: TestTrait = {\n async setUp(test: DatabaseTest) {\n if (usingInMemoryDatabase(test.app)) return runCommand(test.app, 'migrate', seedOptions(test))\n if (!RefreshDatabaseState.migrated) {\n if (test.migrateFreshUsing !== undefined) await test.migrateFreshUsing()\n else await runCommand(test.app, 'migrate:fresh', seedOptions(test))\n RefreshDatabaseState.migrated = true\n }\n await beginTransactions(test, connectionsOf(test))\n },\n}\n\n/** Laravel's DatabaseMigrations: `migrate:fresh` before each test, `migrate:rollback` after it. */\nexport const DatabaseMigrations: TestTrait = {\n async setUp(test: DatabaseTest) {\n await runCommand(test.app, 'migrate:fresh', seedOptions(test))\n test.beforeApplicationDestroyed(() => runCommand(test.app, 'migrate:rollback'))\n },\n}\n\n/** Laravel's DatabaseTransactions: each test runs in a transaction that is rolled back (no migrations). */\nexport const DatabaseTransactions: TestTrait = {\n async setUp(test: DatabaseTest) {\n await beginTransactions(test, connectionsOf(test))\n },\n}\n","import { AuthFactory, token, type Authenticatable } from '@orieljs/contracts'\nimport { assert } from '../assert'\nimport { clonePlain } from '../environment'\nimport { HttpClient, type RequestData } from '../Http/HttpClient'\nimport type { TestResponse } from '../TestResponse'\nimport { InteractsWithApplication } from './InteractsWithApplication'\n\ntype Headers = Record<string, string>\n\n/** Laravel's MakesHttpRequests: requests run in-process through the app's HttpKernel. State lasts for one test. */\nexport abstract class MakesHttpRequests extends InteractsWithApplication {\n private client: HttpClient | undefined\n\n /** The current test's HTTP client (created on first use). */\n protected get http(): HttpClient {\n return (this.client ??= this.createHttpClient())\n }\n\n protected createHttpClient(): HttpClient {\n return new HttpClient(this.app)\n }\n\n /** Live.test() runs in this test's request scope (Live reads the same token: no import between the packages). */\n override async setUp(): Promise<void> {\n await super.setUp()\n this.app.instance(token<<T>(run: () => Promise<T>) => Promise<T>>('Testing.RequestScope'), (run) => this.http.withinRequest(run))\n }\n\n override async tearDown(): Promise<void> {\n try {\n await super.tearDown()\n } finally {\n this.client = undefined\n }\n }\n\n withHeaders(headers: Headers): this {\n Object.assign(this.http.headers, headers)\n return this\n }\n\n withHeader(name: string, value: string): this {\n this.http.headers[name] = value\n return this\n }\n\n withToken(token: string, type = 'Bearer'): this {\n return this.withHeader('Authorization', `${type} ${token}`)\n }\n\n withBasicAuth(username: string, password: string): this {\n return this.withToken(Buffer.from(`${username}:${password}`).toString('base64'), 'Basic')\n }\n\n /** Removes the Authorization header, whatever case it was set with (header names are case-insensitive). */\n withoutToken(): this {\n for (const name of Object.keys(this.http.headers)) if (name.toLowerCase() === 'authorization') delete this.http.headers[name]\n return this\n }\n\n /** Cookies are encrypted the way EncryptCookies expects when the app has an Encrypter. */\n withCookies(cookies: Record<string, string>): this {\n for (const [name, value] of Object.entries(cookies)) this.http.cookies.set(name, { value, encrypt: true })\n return this\n }\n\n withCookie(name: string, value: string): this {\n return this.withCookies({ [name]: value })\n }\n\n withUnencryptedCookies(cookies: Record<string, string>): this {\n for (const [name, value] of Object.entries(cookies)) this.http.cookies.set(name, { value, encrypt: false })\n return this\n }\n\n withUnencryptedCookie(name: string, value: string): this {\n return this.withUnencryptedCookies({ [name]: value })\n }\n\n /** Follow redirects (always with GET, like Laravel) and return the final response. */\n followingRedirects(): this {\n this.http.followRedirects = true\n return this\n }\n\n /** Sets the Referer and the session's previous URL, so redirect()->back() goes there. */\n from(url: string): this {\n this.http.previousUrl = url\n return this.withHeader('Referer', url)\n }\n\n /** Puts data in the session for the following requests, over what the stored session holds (Laravel's withSession()). */\n withSession(data: Record<string, unknown>): this {\n const values = clonePlain(data)\n this.http.session = { ...this.http.session, ...values }\n this.http.sessionChanges.push((session) => session.put(clonePlain(values)))\n return this\n }\n\n /** Empties the session, the stored one included, so the next request starts with none (Laravel's flushSession()). */\n flushSession(): this {\n this.http.session = {}\n this.http.sessionChanges.splice(0, Infinity, (session) => session.flush())\n return this\n }\n\n /** Every following request is authenticated as `user` on `guard` (which also becomes the default guard). */\n actingAs(user: Authenticatable, guard?: string): this {\n this.http.users.set(guard, user)\n if (guard !== undefined) this.http.defaultGuard = guard\n return this\n }\n\n be(user: Authenticatable, guard?: string): this {\n return this.actingAs(user, guard)\n }\n\n /** Errors escape from the request instead of being rendered (Laravel's withoutExceptionHandling()). */\n withoutExceptionHandling(): this {\n this.http.handleExceptions = false\n return this\n }\n\n withExceptionHandling(): this {\n this.http.handleExceptions = true\n return this\n }\n\n /** The user is authenticated (after the requests so far: carried session and actingAs). */\n async assertAuthenticated(guard?: string): Promise<this> {\n assert(await this.isAuthenticated(guard), 'The user is not authenticated')\n return this\n }\n\n async assertGuest(guard?: string): Promise<this> {\n assert(!(await this.isAuthenticated(guard)), 'The user is authenticated')\n return this\n }\n\n /** Same identifier and class as `user`. */\n async assertAuthenticatedAs(user: Authenticatable, guard?: string): Promise<this> {\n const current = await this.http.inScope((scope) => scope.make(AuthFactory).guard(guard).user())\n assert(current !== undefined, 'The current user is not authenticated.')\n assert(\n current.constructor === user.constructor && current.getAuthIdentifier() === user.getAuthIdentifier(),\n `The currently authenticated user [${String(current.getAuthIdentifier())}] is not who was expected [${String(user.getAuthIdentifier())}].`,\n )\n return this\n }\n\n protected isAuthenticated(guard?: string): Promise<boolean> {\n return this.http.inScope((scope) => scope.make(AuthFactory).guard(guard).check())\n }\n\n get(uri: string, headers: Headers = {}): Promise<TestResponse> {\n return this.http.request('GET', uri, { headers })\n }\n\n getJson(uri: string, headers: Headers = {}): Promise<TestResponse> {\n return this.http.request('GET', uri, { headers, json: true })\n }\n\n post(uri: string, data: RequestData = {}, headers: Headers = {}): Promise<TestResponse> {\n return this.http.request('POST', uri, { data, headers })\n }\n\n postJson(uri: string, data: RequestData = {}, headers: Headers = {}): Promise<TestResponse> {\n return this.http.request('POST', uri, { data, headers, json: true })\n }\n\n put(uri: string, data: RequestData = {}, headers: Headers = {}): Promise<TestResponse> {\n return this.http.request('PUT', uri, { data, headers })\n }\n\n putJson(uri: string, data: RequestData = {}, headers: Headers = {}): Promise<TestResponse> {\n return this.http.request('PUT', uri, { data, headers, json: true })\n }\n\n patch(uri: string, data: RequestData = {}, headers: Headers = {}): Promise<TestResponse> {\n return this.http.request('PATCH', uri, { data, headers })\n }\n\n patchJson(uri: string, data: RequestData = {}, headers: Headers = {}): Promise<TestResponse> {\n return this.http.request('PATCH', uri, { data, headers, json: true })\n }\n\n delete(uri: string, data: RequestData = {}, headers: Headers = {}): Promise<TestResponse> {\n return this.http.request('DELETE', uri, { data, headers })\n }\n\n deleteJson(uri: string, data: RequestData = {}, headers: Headers = {}): Promise<TestResponse> {\n return this.http.request('DELETE', uri, { data, headers, json: true })\n }\n\n options(uri: string, data: RequestData = {}, headers: Headers = {}): Promise<TestResponse> {\n return this.http.request('OPTIONS', uri, { data, headers })\n }\n\n head(uri: string, headers: Headers = {}): Promise<TestResponse> {\n return this.http.request('HEAD', uri, { headers })\n }\n\n /** A JSON request with any verb; GET/HEAD data goes into the query string. */\n json(method: string, uri: string, data: RequestData = {}, headers: Headers = {}): Promise<TestResponse> {\n return this.http.request(method, uri, { data, headers, json: true })\n }\n\n /** Any verb with form data (Laravel's call()). */\n call(method: string, uri: string, data: RequestData = {}, headers: Headers = {}): Promise<TestResponse> {\n return this.http.request(method, uri, { data, headers })\n }\n}\n","/**\n * Laravel's phpunit.xml <env> block. Applied before every test's application is created; variables that are\n * already set (the shell, CI, vitest.config) win, like phpunit's non-forced <env>.\n */\nexport const TESTING_ENVIRONMENT: Readonly<Record<string, string>> = Object.freeze({\n APP_ENV: 'testing',\n BCRYPT_ROUNDS: '4',\n CACHE_STORE: 'array',\n DB_CONNECTION: 'sqlite',\n DB_DATABASE: ':memory:',\n MAIL_MAILER: 'array',\n QUEUE_CONNECTION: 'sync',\n SESSION_DRIVER: 'array',\n})\n\nexport function applyEnvironment(values: Record<string, string>, env: NodeJS.ProcessEnv = process.env): void {\n for (const [key, value] of Object.entries(values)) env[key] ??= value\n}\n\n/** Copies plain objects and arrays; class instances, functions and other values are kept by reference. */\nexport function clonePlain<T>(value: T): T {\n if (Array.isArray(value)) return value.map((item: unknown) => clonePlain(item)) as T\n if (typeof value === 'object' && value !== null) {\n const proto = Object.getPrototypeOf(value) as unknown\n if (proto !== Object.prototype && proto !== null) return value\n return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, clonePlain(item)])) as T\n }\n return value\n}\n","import {\n AuthFactory,\n ConfigRepository,\n Encrypter,\n ExceptionHandler,\n HttpKernel,\n HttpRequest,\n Session,\n ViewFactory,\n type Application,\n type Authenticatable,\n type Class,\n type Container,\n} from '@orieljs/contracts'\nimport { IncomingRequest } from '@orieljs/http'\nimport { fail } from '../assert'\nimport { clonePlain } from '../environment'\nimport { TestResponse, type ResponseContext } from '../TestResponse'\nimport { cookieHeader, encryptCookie, isExpired, responseCookies } from './cookies'\nimport { actingAsAuthFactory, recordingExceptionHandler, recordingViewFactory } from './recorders'\n\nexport type RequestData = Record<string, unknown>\n\nexport interface RequestOptions {\n data?: RequestData\n headers?: Record<string, string>\n /** Send data as a JSON body (the *Json methods). */\n json?: boolean\n}\n\n/** The address Http's request.ip() reads for requests that didn't come through a server (the Http/Routing protocol). */\nconst CLIENT_ADDRESS = Symbol.for('oriel:http.client-address')\nconst MAX_REDIRECTS = 20\n\n/**\n * Laravel's MakesHttpRequests state for one test: default headers, cookies, the session carried between\n * requests, actingAs users and options, plus the dispatch itself.\n */\nexport class HttpClient {\n readonly headers: Record<string, string> = {}\n /** Cookies to encrypt on send (withCookie) and to send as-is (withUnencryptedCookie, or captured from responses). */\n readonly cookies = new Map<string, { value: string; encrypt: boolean }>()\n /** actingAs() users by guard name (undefined = the default guard). */\n readonly users = new Map<string | undefined, Authenticatable>()\n followRedirects = false\n handleExceptions = true\n /** The guard actingAs(user, guard) made the default. */\n defaultGuard: string | undefined\n /** Session attributes carried from one request to the next (Laravel keeps one session store per test). */\n session: Record<string, unknown> | undefined\n /**\n * withSession() and flushSession() since the last started session: applied to the stored session (the one the\n * session cookie points to) once the next request starts it, so they win over what it holds, as in Laravel.\n */\n sessionChanges: Array<(session: Session) => void> = []\n /** from(url): the session's previous URL for the next request only (Laravel sets it once). */\n previousUrl: string | undefined\n /** Requests whose actingAs users reached the guards (the AuthFactory they went through). */\n private readonly actingAsApplied = new WeakMap<ResponseContext, AuthFactory>()\n\n constructor(protected readonly app: Application) {}\n\n async request(method: string, uri: string, options: RequestOptions = {}): Promise<TestResponse> {\n let response = await this.send(this.buildRequest(method, uri, options))\n if (!this.followRedirects) return response\n for (let hops = 0; isRedirect(response.status); hops++) {\n if (hops >= MAX_REDIRECTS) fail(`Too many redirects (more than ${MAX_REDIRECTS}), last location [${response.headers.get('Location')}].`)\n response = await this.send(this.buildRequest('GET', response.headers.get('Location') ?? '/', {}))\n }\n return response\n }\n\n /** Runs `fn` in a scope prepared like a request's (carried session, actingAs users), e.g. for assertAuthenticated(). */\n async inScope<T>(fn: (scope: Container) => T | Promise<T>): Promise<T> {\n await this.app.boot()\n const scope = this.app.createScope()\n return scope.run(async () => {\n await this.beforeRequest(scope, {})\n return fn(scope)\n })\n }\n\n /**\n * Runs `run` in a request scope like this client's requests have (a request for `method uri` bound, the carried\n * session, actingAs users), then carries the session and the users on, as after a request. Live.test() runs its\n * mount and updates through it.\n */\n async withinRequest<T>(run: () => Promise<T>, method = 'GET', uri = '/'): Promise<T> {\n await this.app.boot()\n const request = this.buildRequest(method, uri, {})\n setClientAddress(request, '127.0.0.1')\n const scope = this.app.createScope()\n const context: ResponseContext = { request, app: this.app, client: this }\n const result = await scope.run(async () => {\n this.beforeRequest(scope, context)\n // No StartSession runs here, so the pending withSession()/flushSession() changes apply now, not on a later request.\n if (context.session !== undefined) this.applyPending(context.session)\n scope.instance(HttpRequest, new IncomingRequest(request))\n // As the auth middleware does: the guard has the session's (or actingAs) user before the component runs. An\n // app whose guard can't be built (no user provider) has nobody to find, as before.\n if (scope.bound(AuthFactory)) {\n try {\n await scope.make(AuthFactory).guard().check()\n } catch {\n // Auth calls in the component, await request().user() among them, report the configuration error.\n }\n }\n return run()\n })\n await scope.run(() => this.afterRequest(scope, context))\n return result\n }\n\n /** Runs the request through the app's real HttpKernel, in a request scope this client owns. */\n protected async send(request: Request): Promise<TestResponse> {\n const app = this.app\n await app.boot()\n setClientAddress(request, '127.0.0.1')\n const scope = app.createScope()\n const context: ResponseContext = { request, app, client: this }\n const response = await scope.run(async () => {\n await this.beforeRequest(scope, context)\n this.previousUrl = undefined\n return scope.make(HttpKernel).handle(request)\n })\n await scope.run(() => this.afterRequest(scope, context))\n this.rememberCookies(response)\n await app.make(HttpKernel).terminate?.(request, response)\n if (!this.handleExceptions && context.exception !== undefined) throw context.exception\n return TestResponse.from(response, context)\n }\n\n /** Prepares the request scope: recorders, the carried session and actingAs users. */\n protected beforeRequest(scope: Container, context: ResponseContext): void {\n const views: NonNullable<ResponseContext['views']> = (context.views = [])\n if (this.app.bound(ViewFactory)) scope.instance(ViewFactory, recordingViewFactory(this.app.make(ViewFactory), views))\n if (this.app.bound(ExceptionHandler)) {\n scope.instance(ExceptionHandler, recordingExceptionHandler(this.app.make(ExceptionHandler), (error) => (context.exception = error)))\n }\n const session = this.scopeSession(scope)\n if (session !== undefined) {\n if (this.session !== undefined) session.put(clonePlain(this.session))\n if (this.sessionChanges.length > 0) this.applyOnStart(session)\n if (this.previousUrl !== undefined) session.setPreviousUrl(this.previousUrl)\n context.session = session\n }\n if ((this.users.size > 0 || this.defaultGuard !== undefined) && this.app.bound(AuthFactory)) {\n const auth = this.app.make(AuthFactory)\n const acting = actingAsAuthFactory(auth, this.users, this.defaultGuard, () => {\n this.actingAsApplied.set(context, auth)\n })\n scope.instance(AuthFactory, acting)\n // Auth also binds its AuthManager class to the same singleton, so inject(AuthManager) must see the users too.\n const manager: unknown = auth.constructor\n if (typeof manager === 'function' && manager !== Object && this.app.bound(manager as Class<AuthFactory>)) {\n scope.instance(manager as Class<AuthFactory>, acting)\n }\n }\n }\n\n /** Keeps the session for the next request, like Laravel's per-test session store, and the guards' users. */\n protected async afterRequest(_scope: Container, context: ResponseContext): Promise<void> {\n if (context.session !== undefined) this.session = clonePlain(context.session.all())\n const auth = this.actingAsApplied.get(context)\n if (auth !== undefined) await this.syncActingAs(auth)\n }\n\n /**\n * Laravel's actingAs() sets the user on the guard once, so a logout (or a login as someone else) in the\n * request sticks. Reads each actingAs guard back and forgets or replaces its user to match.\n */\n protected async syncActingAs(auth: AuthFactory): Promise<void> {\n for (const guard of [...this.users.keys()]) {\n const user = await auth.guard(guard).user()\n if (user === undefined) this.users.delete(guard)\n else this.users.set(guard, user)\n }\n }\n\n /** Applies the pending withSession()/flushSession() changes once the session has loaded what it stored. */\n protected applyOnStart(session: Session): void {\n const start = session.start.bind(session)\n session.start = async () => {\n await start()\n this.applyPending(session)\n }\n }\n\n /** Applies the pending withSession()/flushSession() changes to the session, once. */\n protected applyPending(session: Session): void {\n if (this.sessionChanges.length === 0) return\n for (const change of this.sessionChanges.splice(0)) change(session)\n if (!session.has('_token')) session.regenerateToken()\n }\n\n /** The request's (scoped) Session, created now so the carried attributes are in place before StartSession. */\n protected scopeSession(scope: Container): Session | undefined {\n if (!scope.bound(Session)) return undefined\n try {\n return scope.make(Session)\n } catch {\n return undefined\n }\n }\n\n buildRequest(method: string, uri: string, options: RequestOptions): Request {\n const verb = method.toUpperCase()\n const url = new URL(uri, this.baseUrl())\n const headers = new Headers({ ...this.headers, ...options.headers })\n let body: string | FormData | URLSearchParams | undefined\n const data = options.data ?? {}\n\n if (verb === 'GET' || verb === 'HEAD') {\n for (const [key, value] of flatten(data)) if (typeof value === 'string') url.searchParams.append(key, value)\n } else if (options.json) {\n body = JSON.stringify(data)\n } else if (Object.keys(data).length > 0) {\n const fields = flatten(data)\n if (fields.some(([, value]) => typeof value !== 'string')) {\n const form = new FormData()\n for (const [key, value] of fields) form.append(key, value)\n body = form\n } else {\n body = new URLSearchParams(fields as Array<[string, string]>)\n }\n }\n if (options.json) {\n if (body !== undefined) headers.set('Content-Type', 'application/json')\n headers.set('Accept', 'application/json')\n }\n const cookies = this.cookieHeader()\n if (cookies !== '') headers.set('Cookie', cookies)\n return new Request(url, { method: verb, headers, body })\n }\n\n protected baseUrl(): string {\n const configured = this.app.bound(ConfigRepository) ? this.app.make(ConfigRepository).get<unknown>('app.url') : undefined\n return typeof configured === 'string' && configured !== '' ? configured : 'http://localhost'\n }\n\n protected cookieHeader(): string {\n const encrypter = this.app.bound(Encrypter) ? this.app.make(Encrypter) : undefined\n const values = new Map<string, string>()\n for (const [name, { value, encrypt }] of this.cookies) {\n values.set(name, encrypt && encrypter !== undefined ? encryptCookie(encrypter, name, value) : value)\n }\n return cookieHeader(values)\n }\n\n /** Like a browser: cookies the app sets are sent back on later requests in the same test; deleted ones are dropped. */\n protected rememberCookies(response: Response): void {\n for (const cookie of responseCookies(response)) {\n if (isExpired(cookie)) this.cookies.delete(cookie.name)\n else this.cookies.set(cookie.name, { value: cookie.value, encrypt: false })\n }\n }\n}\n\nfunction isRedirect(status: number): boolean {\n return status >= 300 && status < 400 && status !== 304\n}\n\nfunction setClientAddress(request: Request, address: string): void {\n const g = globalThis as unknown as Record<symbol, WeakMap<Request, string> | undefined>\n ;(g[CLIENT_ADDRESS] ??= new WeakMap<Request, string>()).set(request, address)\n}\n\n/** `{ user: { name: 'a' }, tags: ['x'] }` → `user[name]=a`, `tags[0]=x` (the PHP bracket form Http parses). */\nexport function flatten(data: RequestData, prefix = ''): Array<[string, string | Blob]> {\n const out: Array<[string, string | Blob]> = []\n for (const [key, value] of Object.entries(data)) {\n const name = prefix === '' ? key : `${prefix}[${key}]`\n if (value === undefined) continue\n if (value === null) out.push([name, ''])\n else if (value instanceof Blob) out.push([name, value])\n else if (value instanceof Date) out.push([name, value.toISOString()])\n else if (typeof value === 'object') out.push(...flatten(value as RequestData, name))\n else if (typeof value === 'boolean') out.push([name, value ? '1' : '0'])\n else out.push([name, String(value as string | number | bigint)])\n }\n return out\n}\n","import { Encrypter, UrlGenerator, type Application, type InertiaPage, type Session, type View } from '@orieljs/contracts'\nimport { Arr } from '@orieljs/support'\nimport { assert, assertStructure, containsPair, equals, escapeHtml, fail, format, isSubset, stripTags, type JsonStructure } from './assert'\nimport { AssertableInertia, inertiaPageOf } from './Fluent/AssertableInertia'\nimport { AssertableJson } from './Fluent/AssertableJson'\nimport { decryptCookie, isExpired, responseCookies, type ResponseCookie } from './Http/cookies'\nimport type { HttpClient } from './Http/HttpClient'\n\n/** Field → messages, as Http flashes them per bag: `errors: { [bag]: { field: string[] } }`. */\ntype ErrorMessages = Record<string, string[]>\n/** `'email'`, `['email', 'name']` or `{ email: 'must be valid' }` (message fragments). */\nexport type ExpectedErrors = string | string[] | Record<string, string | string[]>\n\n/** What the HTTP client knows about the request that produced a response. */\nexport interface ResponseContext {\n /** The raw request sent to the kernel (redirect URLs are resolved against it). */\n request?: Request\n /** The application that handled it. */\n app?: Application\n /** The request's session after the response. */\n session?: Session\n /** Views made while handling the request, in order. */\n views?: View[]\n /** The last error the exception handler rendered. */\n exception?: unknown\n /** The client that sent the request (Inertia reloads reuse it, keeping the session and cookies). */\n client?: HttpClient\n}\n\nconst REDIRECTS = new Set([201, 301, 302, 303, 307, 308])\n\n/** Laravel's TestResponse: a Response with its body already read, plus fluent assertions. */\nexport class TestResponse {\n private decoded: { value: unknown } | undefined\n\n constructor(\n readonly baseResponse: Response,\n readonly content: string,\n readonly context: ResponseContext = {},\n ) {}\n\n /** Reads the body once, so every assertion is synchronous. */\n static async from(response: Response, context: ResponseContext = {}): Promise<TestResponse> {\n return new TestResponse(response, await response.text(), context)\n }\n\n get status(): number {\n return this.baseResponse.status\n }\n\n get headers(): Headers {\n return this.baseResponse.headers\n }\n\n /** The error the exception handler rendered for this request, if any. */\n get exception(): unknown {\n return this.context.exception\n }\n\n getContent(): string {\n return this.content\n }\n\n /** The decoded JSON body, or the value at a dot path (`data.0.id`). */\n json<T = unknown>(path?: string): T {\n if (this.decoded === undefined) {\n try {\n this.decoded = { value: JSON.parse(this.content) }\n } catch {\n fail(`Invalid JSON was returned from the route.\\n\\n${this.excerpt()}`)\n }\n }\n return Arr.get<T>(this.decoded.value, path)\n }\n\n dump(path?: string): this {\n console.log(path === undefined ? this.content : this.json(path))\n return this\n }\n\n // Status ------------------------------------------------------------------------------------------------\n\n assertStatus(status: number): this {\n if (this.status !== status) fail(this.statusMessage(`Expected response status code [${status}] but received ${this.status}.`), { actual: this.status, expected: status })\n return this\n }\n\n assertOk(): this { return this.assertStatus(200) }\n assertCreated(): this { return this.assertStatus(201) }\n assertAccepted(): this { return this.assertStatus(202) }\n assertMovedPermanently(): this { return this.assertStatus(301) }\n assertFound(): this { return this.assertStatus(302) }\n assertNotModified(): this { return this.assertStatus(304) }\n assertBadRequest(): this { return this.assertStatus(400) }\n assertUnauthorized(): this { return this.assertStatus(401) }\n assertPaymentRequired(): this { return this.assertStatus(402) }\n assertForbidden(): this { return this.assertStatus(403) }\n assertNotFound(): this { return this.assertStatus(404) }\n assertMethodNotAllowed(): this { return this.assertStatus(405) }\n assertNotAcceptable(): this { return this.assertStatus(406) }\n assertRequestTimeout(): this { return this.assertStatus(408) }\n assertConflict(): this { return this.assertStatus(409) }\n assertGone(): this { return this.assertStatus(410) }\n assertUnsupportedMediaType(): this { return this.assertStatus(415) }\n assertUnprocessable(): this { return this.assertStatus(422) }\n assertTooManyRequests(): this { return this.assertStatus(429) }\n assertInternalServerError(): this { return this.assertStatus(500) }\n assertServiceUnavailable(): this { return this.assertStatus(503) }\n\n /** 204 (or `status`) with an empty body. */\n assertNoContent(status = 204): this {\n this.assertStatus(status)\n assert(this.content === '', 'Response content is not empty.', { actual: this.content, expected: '' })\n return this\n }\n\n assertSuccessful(): this {\n assert(this.status >= 200 && this.status < 300, () => this.statusMessage(`Expected response status code [>=200, <300] but received ${this.status}.`))\n return this\n }\n\n assertClientError(): this {\n assert(this.status >= 400 && this.status < 500, () => this.statusMessage(`Expected response status code [>=400, <500] but received ${this.status}.`))\n return this\n }\n\n assertServerError(): this {\n assert(this.status >= 500 && this.status < 600, () => this.statusMessage(`Expected response status code [>=500, <600] but received ${this.status}.`))\n return this\n }\n\n // Redirects ---------------------------------------------------------------------------------------------\n\n /** A redirect status (201, 301, 302, 303, 307, 308); with `uri`, the Location must match it. */\n assertRedirect(uri?: string): this {\n assert(REDIRECTS.has(this.status), () => this.statusMessage(`Expected response status code [201, 301, 302, 303, 307, 308] but received ${this.status}.`))\n if (uri !== undefined) this.assertLocation(uri)\n return this\n }\n\n assertRedirectContains(uri: string): this {\n this.assertRedirect()\n const location = this.headers.get('Location') ?? ''\n assert(location.includes(uri), `Redirect location [${location}] does not contain [${uri}].`)\n return this\n }\n\n /** Relative and absolute forms of the same URL are equal (both are resolved against the request URL). */\n assertLocation(uri: string): this {\n const actual = this.absolute(this.headers.get('Location') ?? '')\n const expected = this.absolute(uri)\n assert(actual === expected, `Failed asserting that the redirect location [${actual}] equals [${expected}].`, { actual, expected })\n return this\n }\n\n // Headers -----------------------------------------------------------------------------------------------\n\n assertHeader(name: string, value?: string): this {\n const actual = this.headers.get(name)\n assert(actual !== null, `Header [${name}] not present on response.`)\n if (value !== undefined) assert(actual === value, `Header [${name}] was found, but value [${actual}] does not match [${value}].`, { actual, expected: value })\n return this\n }\n\n assertHeaderMissing(name: string): this {\n assert(!this.headers.has(name), `Unexpected header [${name}] is present on response.`)\n return this\n }\n\n /** Content-Disposition: attachment (optionally with this file name). */\n assertDownload(filename?: string): this {\n const disposition = this.headers.get('Content-Disposition') ?? ''\n assert(/^attachment/i.test(disposition), 'Response does not offer a file download.')\n if (filename !== undefined) {\n assert(disposition.includes(`filename=\"${filename}\"`) || disposition.includes(`filename=${filename}`), `Expected file [${filename}] is not present in Content-Disposition header [${disposition}].`)\n }\n return this\n }\n\n // Content -----------------------------------------------------------------------------------------------\n\n assertContent(value: string): this {\n assert(this.content === value, 'Response content does not match.', { actual: this.content, expected: value })\n return this\n }\n\n /** The content contains the value(s); values are HTML-escaped first unless `escape` is false (Laravel). */\n assertSee(value: string | string[], escape = true): this {\n for (const needle of this.needles(value, escape)) {\n assert(this.content.includes(needle), `Failed asserting that the response contains [${needle}].\\n\\n${this.excerpt()}`)\n }\n return this\n }\n\n assertDontSee(value: string | string[], escape = true): this {\n for (const needle of this.needles(value, escape)) {\n assert(!this.content.includes(needle), `Failed asserting that the response does not contain [${needle}].\\n\\n${this.excerpt()}`)\n }\n return this\n }\n\n assertSeeInOrder(values: string[], escape = true): this {\n return this.inOrder(this.content, this.needles(values, escape))\n }\n\n /** Like assertSee, against the content with its tags stripped. */\n assertSeeText(value: string | string[], escape = true): this {\n const text = stripTags(this.content)\n for (const needle of this.needles(value, escape)) {\n assert(text.includes(needle), `Failed asserting that the response text contains [${needle}].\\n\\n${this.excerpt(text)}`)\n }\n return this\n }\n\n assertDontSeeText(value: string | string[], escape = true): this {\n const text = stripTags(this.content)\n for (const needle of this.needles(value, escape)) {\n assert(!text.includes(needle), `Failed asserting that the response text does not contain [${needle}].`)\n }\n return this\n }\n\n assertSeeTextInOrder(values: string[], escape = true): this {\n return this.inOrder(stripTags(this.content), this.needles(values, escape))\n }\n\n // JSON --------------------------------------------------------------------------------------------------\n\n /**\n * The response JSON contains `data` (a subset match: extra keys in the response are fine), or fluent\n * assertions: assertJson(json => json.has('data', 3).etc()).\n */\n assertJson(data: Record<string, unknown> | unknown[] | ((json: AssertableJson) => unknown)): this {\n if (typeof data === 'function') {\n const json = AssertableJson.fromJson(this.json())\n data(json)\n if (!Array.isArray(json.toArray())) json.interacted()\n return this\n }\n const actual = this.json()\n assert(isSubset(data, actual), 'Unable to find the expected JSON subset in the response.', { actual, expected: data })\n return this\n }\n\n // Inertia -----------------------------------------------------------------------------------------------\n\n /**\n * An Inertia page response, with optional fluent assertions over its props. An async callback (reload(),\n * loadDeferredProps()) makes this return a promise: await it.\n */\n assertInertia(callback: (page: AssertableInertia) => Promise<unknown>): Promise<this>\n assertInertia(callback?: (page: AssertableInertia) => unknown): this\n assertInertia(callback?: (page: AssertableInertia) => unknown): this | Promise<this> {\n const page = AssertableInertia.fromTestResponse(this)\n const result = callback?.(page)\n if (typeof (result as PromiseLike<unknown> | undefined)?.then === 'function') return Promise.resolve(result).then(() => this)\n return this\n }\n\n /** The Inertia page object of this response. */\n inertiaPage(): InertiaPage {\n return inertiaPageOf(this)\n }\n\n /** The page props, or one prop by dot path. */\n inertiaProps<T = unknown>(key?: string): T {\n return Arr.get<T>(inertiaPageOf(this).props, key)\n }\n\n /** Inertia flash data waiting in the session for the next page (after a redirect). */\n assertInertiaFlash(key: string, ...expected: [] | [unknown]): this {\n AssertableInertia.assertFlashHas(this.session().get<Record<string, unknown>>('inertia.flash_data', {}), key, ...expected)\n return this\n }\n\n assertInertiaFlashMissing(key: string): this {\n AssertableInertia.assertFlashMissing(this.session().get<Record<string, unknown>>('inertia.flash_data', {}), key)\n return this\n }\n\n /** The response JSON equals `data` exactly (object key order is ignored). */\n assertExactJson(data: unknown): this {\n const actual = this.json()\n assert(equals(actual, data), 'Failed asserting that the response JSON matches exactly.', { actual, expected: data })\n return this\n }\n\n /** The value at `path` equals `expected` (strictly), or passes the predicate. */\n assertJsonPath(path: string, expected: unknown): this {\n assert(Arr.has(this.json(), path), `Failed asserting that the JSON has the path [${path}].`, { actual: this.json() })\n const actual = this.json(path)\n if (typeof expected === 'function') {\n assert((expected as (value: unknown) => unknown)(actual) === true, `Failed asserting that the value at [${path}] passes the given check (got ${format(actual)}).`)\n } else {\n assert(equals(actual, expected), `Failed asserting that the value at [${path}] equals ${format(expected)} (got ${format(actual)}).`, { actual, expected })\n }\n return this\n }\n\n assertJsonMissingPath(path: string): this {\n assert(!Arr.has(this.json(), path), `Failed asserting that the JSON does not have the path [${path}].`)\n return this\n }\n\n /** Each key/value pair appears somewhere in the JSON (Laravel's assertJsonFragment). */\n assertJsonFragment(data: Record<string, unknown>): this {\n const actual = this.json()\n for (const [key, value] of Object.entries(data)) {\n assert(containsPair(actual, key, value), `Unable to find JSON fragment ${format({ [key]: value })} in the response.`, { actual, expected: data })\n }\n return this\n }\n\n /** Passes when at least one pair of `data` is absent (Laravel's assertJsonMissing). */\n assertJsonMissing(data: Record<string, unknown>): this {\n const actual = this.json()\n const allPresent = Object.entries(data).every(([key, value]) => containsPair(actual, key, value))\n assert(!allPresent, `Found unexpected JSON fragment ${format(data)} in the response.`, { actual })\n return this\n }\n\n /** `['id', { author: ['name'] }]`, `{ data: { '*': ['id'] } }`; without a structure, just checks it's JSON. */\n assertJsonStructure(structure?: JsonStructure): this {\n const data = this.json()\n if (structure !== undefined) assertStructure(structure, data)\n return this\n }\n\n /** The JSON (or the value at `key`) has `count` elements. */\n assertJsonCount(count: number, key?: string): this {\n const value = this.json(key)\n const actual = Array.isArray(value) ? value.length : typeof value === 'object' && value !== null ? Object.keys(value).length : -1\n assert(actual === count, `Failed to assert that the response ${key === undefined ? '' : `[${key}] `}count matched the expected ${count} (got ${actual}).`, { actual, expected: count })\n return this\n }\n\n /** assertRedirect() to the URL of a named route (resolved with the app's UrlGenerator). */\n assertRedirectToRoute(name: string, parameters?: unknown): this {\n const app = this.context.app\n assert(app !== undefined && app.bound(UrlGenerator), 'assertRedirectToRoute() needs an application with a UrlGenerator (the Routing component).')\n return this.assertRedirect(app.make(UrlGenerator).route(name, parameters))\n }\n\n // Validation --------------------------------------------------------------------------------------------\n\n /** The JSON body has validation errors for these keys (and messages containing these fragments). */\n assertJsonValidationErrors(errors: ExpectedErrors, responseKey = 'errors'): this {\n const actual = this.json<unknown>(responseKey)\n assert(typeof actual === 'object' && actual !== null, `Failed to find validation errors in the response under [${responseKey}].\\n\\n${this.excerpt()}`)\n this.assertErrorsContain(actual as ErrorMessages, errors, 'response')\n return this\n }\n\n /** No validation errors in the JSON (or none for these keys). */\n assertJsonMissingValidationErrors(keys?: string | string[], responseKey = 'errors'): this {\n if (this.content === '') return this\n const errors = Arr.get<ErrorMessages | undefined>(this.json(), responseKey)\n if (errors === undefined || errors === null) return this\n const unexpected = keys === undefined ? Object.keys(errors) : [keys].flat().filter((key) => Object.hasOwn(errors, key))\n assert(unexpected.length === 0, `Found unexpected validation error(s) for [${unexpected.join(', ')}]: ${format(errors)}`)\n return this\n }\n\n /** No validation errors: JSON responses are checked in the body, others in the session. */\n assertValid(keys?: string | string[], errorBag = 'default', responseKey = 'errors'): this {\n if (this.isJson()) return this.assertJsonMissingValidationErrors(keys, responseKey)\n if (this.context.session?.has('errors') !== true) return this\n return keys === undefined ? this.assertSessionDoesntHaveErrors([], undefined, errorBag) : this.assertSessionDoesntHaveErrors(keys, undefined, errorBag)\n }\n\n /** Validation errors for these keys (message fragments match with \"contains\"): JSON body or session. */\n assertInvalid(errors: ExpectedErrors, errorBag = 'default', responseKey = 'errors'): this {\n if (this.isJson()) return this.assertJsonValidationErrors(errors, responseKey)\n this.assertSessionHas('errors')\n this.assertErrorsContain(this.sessionErrors(errorBag), errors, 'session')\n return this\n }\n\n // Session -----------------------------------------------------------------------------------------------\n\n /** The request's session after the response (flashed data is still there). */\n session(): Session {\n const session = this.context.session\n assert(session !== undefined, 'The response has no session: is the Session component registered?')\n return session\n }\n\n /** A key (with an optional value or predicate), several keys, or a { key: value } record. */\n assertSessionHas(key: string | string[] | Record<string, unknown>, value?: unknown): this {\n if (Array.isArray(key)) {\n for (const k of key) this.assertSessionHas(k)\n return this\n }\n if (typeof key === 'object') return this.assertSessionHasAll(key)\n const session = this.session()\n if (value === undefined) {\n assert(session.has(key), `Session is missing expected key [${key}].`)\n } else if (typeof value === 'function') {\n assert((value as (v: unknown) => unknown)(session.get(key)) === true, `Session value for [${key}] does not pass the given check.`)\n } else {\n assert(equals(session.get(key), value), `Session value for [${key}] does not match.`, { actual: session.get(key), expected: value })\n }\n return this\n }\n\n assertSessionHasAll(bindings: Record<string, unknown>): this {\n for (const [key, value] of Object.entries(bindings)) this.assertSessionHas(key, value)\n return this\n }\n\n assertSessionMissing(key: string | string[], value?: unknown): this {\n const session = this.session()\n for (const k of [key].flat()) {\n if (value === undefined) assert(!session.has(k), `Session has unexpected key [${k}].`)\n else assert(!equals(session.get(k), value), `Session has unexpected value for [${k}].`)\n }\n return this\n }\n\n /** Old input flashed with the redirect (withInput()). */\n assertSessionHasInput(key: string | string[] | Record<string, unknown>, value?: unknown): this {\n const session = this.session()\n const entries: Array<[string, unknown]> =\n typeof key === 'string' ? [[key, value]] : Array.isArray(key) ? key.map((k) => [k, undefined]) : Object.entries(key)\n for (const [k, expected] of entries) {\n const actual = session.getOldInput<unknown>(k)\n assert(actual !== undefined, `Session is missing expected key [${k}] in the old input.`)\n if (expected !== undefined) assert(equals(actual, expected), `Old input [${k}] does not match.`, { actual, expected })\n }\n return this\n }\n\n /**\n * The session has errors in `errorBag`: any at all, these keys, or these exact messages (Laravel's rules).\n * `format` is a ':message' template applied to the actual messages first.\n */\n assertSessionHasErrors(keys: ExpectedErrors = [], format?: string, errorBag = 'default'): this {\n this.assertSessionHas('errors')\n const errors = this.formatted(this.sessionErrors(errorBag), format)\n const expected = typeof keys === 'string' ? [keys] : keys\n if (Array.isArray(expected) && expected.length === 0) {\n assert(Object.keys(errors).length > 0, `Session has no errors in the [${errorBag}] bag.`)\n return this\n }\n for (const [key, messages] of normalizeExpected(expected)) {\n assert(Object.hasOwn(errors, key), `Session missing error: ${key}`, { actual: errors })\n for (const message of messages) {\n assert(errors[key]!.includes(message), `Session error for [${key}] does not include ${format === undefined ? '' : 'the formatted '}message ${JSON.stringify(message)}.`, { actual: errors[key], expected: message })\n }\n }\n return this\n }\n\n assertSessionHasErrorsIn(errorBag: string, keys: ExpectedErrors = [], format?: string): this {\n return this.assertSessionHasErrors(keys, format, errorBag)\n }\n\n /** No errors in any bag. */\n assertSessionHasNoErrors(): this {\n const bags = this.context.session?.get<Record<string, ErrorMessages> | undefined>('errors')\n const found = Object.fromEntries(Object.entries(bags ?? {}).filter(([, messages]) => Object.keys(messages ?? {}).length > 0))\n assert(Object.keys(found).length === 0, `Session has unexpected errors: \\n\\n${JSON.stringify(found, null, 2)}`, { actual: found, expected: {} })\n return this\n }\n\n /** No errors in the bag (or none for these keys). */\n assertSessionDoesntHaveErrors(keys: string | string[] = [], format?: string, errorBag = 'default'): this {\n const errors = this.formatted(this.sessionErrors(errorBag), format)\n const list = [keys].flat()\n if (list.length === 0) {\n assert(Object.keys(errors).length === 0, `Session has unexpected errors: \\n\\n${JSON.stringify(errors, null, 2)}`, { actual: errors, expected: {} })\n return this\n }\n for (const key of list) assert(!Object.hasOwn(errors, key), `Session has unexpected error: ${key}`, { actual: errors[key] })\n return this\n }\n\n // Cookies -----------------------------------------------------------------------------------------------\n\n /** A cookie the response sets (the last Set-Cookie with that name). */\n getCookie(name: string): ResponseCookie | undefined {\n return responseCookies(this.baseResponse).findLast((cookie) => cookie.name === name)\n }\n\n /** The cookie is set; with `value`, its (decrypted, unless `encrypted` is false) value matches. */\n assertCookie(name: string, value?: string, encrypted = true): this {\n const cookie = this.getCookie(name)\n assert(cookie !== undefined, `Cookie [${name}] not present on response.`)\n if (value === undefined) return this\n const actual = encrypted ? this.decrypted(cookie) : cookie.value\n assert(actual === value, `Cookie [${name}] was found, but value [${actual}] does not match [${value}].`, { actual, expected: value })\n return this\n }\n\n assertPlainCookie(name: string, value?: string): this {\n return this.assertCookie(name, value, false)\n }\n\n assertCookieExpired(name: string): this {\n const cookie = this.getCookie(name)\n assert(cookie !== undefined, `Cookie [${name}] not present on response.`)\n assert(isExpired(cookie), `Cookie [${name}] is not expired.`)\n return this\n }\n\n assertCookieNotExpired(name: string): this {\n const cookie = this.getCookie(name)\n assert(cookie !== undefined, `Cookie [${name}] not present on response.`)\n assert(!isExpired(cookie), `Cookie [${name}] is expired.`)\n return this\n }\n\n assertCookieMissing(name: string): this {\n assert(this.getCookie(name) === undefined, `Cookie [${name}] is present on response.`)\n return this\n }\n\n // Views -------------------------------------------------------------------------------------------------\n\n /**\n * The view the route returned. A request can make other views too (a mailable's, an error page), so this is the\n * last view whose rendered HTML is the response body, else the last view made.\n */\n get original(): View | undefined {\n const views = this.context.views ?? []\n return views.findLast((view) => renderedHtml(view) === this.content) ?? views.at(-1)\n }\n\n assertViewIs(name: string): this {\n const view = this.ensureView()\n assert(view.name === name, `Failed asserting that the response view [${view.name}] is [${name}].`, { actual: view.name, expected: name })\n return this\n }\n\n /** The view received `key` (dot paths allowed), optionally with this value or passing this predicate. */\n assertViewHas(key: string | string[] | Record<string, unknown>, value?: unknown): this {\n if (typeof key !== 'string') return this.assertViewHasAll(key)\n const data = this.viewDataOf(this.ensureView())\n assert(Arr.has(data, key), `Failed asserting that the view has key [${key}].`, { actual: Object.keys(data) })\n const actual = Arr.get(data, key)\n if (typeof value === 'function') assert((value as (v: unknown) => unknown)(actual) === true, `View data [${key}] does not pass the given check.`)\n else if (value !== undefined) assert(equals(actual, value), `View data [${key}] does not match the expected value.`, { actual, expected: value })\n return this\n }\n\n assertViewHasAll(bindings: string[] | Record<string, unknown>): this {\n if (Array.isArray(bindings)) for (const key of bindings) this.assertViewHas(key)\n else for (const [key, value] of Object.entries(bindings)) this.assertViewHas(key, value)\n return this\n }\n\n assertViewMissing(key: string): this {\n assert(!Arr.has(this.viewDataOf(this.ensureView()), key), `Failed asserting that the view does not have key [${key}].`)\n return this\n }\n\n /** The data the view received (dot path), or all of it. */\n viewData<T = unknown>(key?: string): T {\n return Arr.get<T>(this.viewDataOf(this.ensureView()), key)\n }\n\n // Internals ---------------------------------------------------------------------------------------------\n\n protected absolute(url: string): string {\n try {\n return new URL(url, this.context.request?.url ?? 'http://localhost').href\n } catch {\n return url\n }\n }\n\n protected excerpt(text: string = this.content): string {\n const limit = 2000\n return text.length > limit ? `${text.slice(0, limit)}…` : text\n }\n\n /** Adds the rendered exception (or the body) to a status failure, like Laravel does. */\n protected statusMessage(message: string): string {\n const error = this.context.exception\n if (error instanceof Error) return `${message}\\n\\nThe following exception occurred during the request:\\n\\n${error.stack ?? error.message}`\n return this.content === '' ? message : `${message}\\n\\n${this.excerpt()}`\n }\n\n protected isJson(): boolean {\n return (this.headers.get('Content-Type') ?? '').includes('json')\n }\n\n protected sessionErrors(errorBag: string): ErrorMessages {\n const bags = this.context.session?.get<Record<string, ErrorMessages> | undefined>('errors')\n return bags?.[errorBag] ?? {}\n }\n\n private formatted(errors: ErrorMessages, template?: string): ErrorMessages {\n if (template === undefined) return errors\n return Object.fromEntries(Object.entries(errors).map(([key, messages]) => [key, messages.map((m) => template.replaceAll(':message', m))]))\n }\n\n /** Laravel's assertInvalid/assertJsonValidationErrors: each key present; each expected fragment contained in a message. */\n private assertErrorsContain(errors: ErrorMessages, expected: ExpectedErrors, where: string): void {\n for (const [key, fragments] of normalizeExpected(expected)) {\n assert(Object.hasOwn(errors, key), `Failed to find a validation error in the ${where} for key: [${key}]`, { actual: errors })\n const messages = [errors[key]].flat() as string[]\n for (const fragment of fragments) {\n assert(messages.some((message) => message.includes(fragment)), `Failed to find a validation error for key and message: [${key}] => [${fragment}]`, { actual: messages, expected: fragment })\n }\n }\n }\n\n private ensureView(): View {\n const view = this.original\n assert(view !== undefined, 'The response is not a view.')\n return view\n }\n\n private viewDataOf(view: View): Record<string, unknown> {\n const source = view as View & { gatherData?(): Record<string, unknown>; getData?(): Record<string, unknown> }\n return source.gatherData?.() ?? source.getData?.() ?? {}\n }\n\n private decrypted(cookie: ResponseCookie): string | undefined {\n const app = this.context.app\n if (app === undefined || !app.bound(Encrypter)) return cookie.value\n return decryptCookie(app.make(Encrypter), cookie.name, cookie.value)\n }\n\n private needles(value: string | string[], escape: boolean): string[] {\n return [value].flat().map((needle) => (escape ? escapeHtml(needle) : needle))\n }\n\n private inOrder(haystack: string, needles: string[]): this {\n let position = 0\n for (const needle of needles) {\n const found = haystack.indexOf(needle, position)\n if (found === -1) fail(`Failed asserting that the response contains ${format(needles)} in that order (missing or out of order: [${needle}]).`)\n position = found + needle.length\n }\n return this\n }\n}\n\nfunction normalizeExpected(expected: ExpectedErrors): Array<[string, string[]]> {\n if (typeof expected === 'string') return [[expected, []]]\n if (Array.isArray(expected)) return expected.map((key) => [key, []])\n return Object.entries(expected).map(([key, messages]) => [key, [messages].flat()])\n}\n\n/** The HTML of the view's last render(), or undefined when it was never rendered (toHtml() throws then). */\nfunction renderedHtml(view: View): string | undefined {\n try {\n return view.toHtml()\n } catch {\n return undefined\n }\n}\n","import { existsSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { ConfigRepository, type Application, type InertiaPage } from '@orieljs/contracts'\nimport { Arr } from '@orieljs/support'\nimport { assert, equals, fail } from '../assert'\nimport type { TestResponse } from '../TestResponse'\nimport { AssertableJson } from './AssertableJson'\n\n/** The page object of a response: the JSON body of an Inertia visit, or the page script of a first visit. */\nexport function inertiaPageOf(response: TestResponse): InertiaPage {\n let page: unknown\n try {\n if (response.headers.has('X-Inertia')) page = JSON.parse(response.content)\n else {\n const match = /<script data-page=\"[^\"]*\" type=\"application\\/json\">([\\s\\S]*?)<\\/script>/.exec(response.content)\n page = match === null ? undefined : JSON.parse(match[1]!)\n }\n } catch {\n page = undefined\n }\n const valid =\n typeof page === 'object' && page !== null && ['component', 'props', 'url', 'version'].every((key) => Object.hasOwn(page as object, key))\n if (!valid) fail('Not a valid Inertia response.')\n return page as InertiaPage\n}\n\n/** Inertia's AssertableInertia: AssertableJson over the page props, plus the page component, url, version and flash. */\nexport class AssertableInertia extends AssertableJson {\n #page: InertiaPage | undefined\n #response: TestResponse | undefined\n\n static fromTestResponse(response: TestResponse): AssertableInertia {\n const page = inertiaPageOf(response)\n const instance = new AssertableInertia(page.props)\n instance.#page = page\n instance.#response = response\n return instance\n }\n\n /** Scopes are plain AssertableJson: the page-level methods only make sense at the root. */\n protected override newScope(props: unknown, path: string): AssertableJson {\n return new AssertableJson(props, path)\n }\n\n get page(): InertiaPage {\n if (this.#page === undefined) fail('This assertion is only available on the page root.')\n return this.#page\n }\n\n /** The component name; the page file must exist unless `shouldExist` is false (inertia.testing.ensure_pages_exist). */\n component(value?: string, shouldExist?: boolean): this {\n const actual = this.page.component\n assert(actual === value, 'Unexpected Inertia page component.', { actual, expected: value })\n const app = this.#app()\n const config = app?.bound(ConfigRepository) ? app.make(ConfigRepository) : undefined\n if (shouldExist === true || (shouldExist === undefined && config?.get<boolean>('inertia.testing.ensure_pages_exist', true) !== false)) {\n const paths = config?.get<string[]>('inertia.pages.paths', []) ?? []\n const extensions = config?.get<string[]>('inertia.pages.extensions', []) ?? []\n const exists = paths.some((path) => extensions.some((extension) => existsSync(join(path, `${value}.${extension}`))))\n if (!exists) fail(`Inertia page component file [${value}] does not exist.`)\n }\n return this\n }\n\n url(value: string): this {\n assert(this.page.url === value, 'Unexpected Inertia page url.', { actual: this.page.url, expected: value })\n return this\n }\n\n version(value: string): this {\n assert(this.page.version === value, 'Unexpected Inertia asset version.', { actual: this.page.version, expected: value })\n return this\n }\n\n /** The flash data has `key` (dot paths allowed), equal to `expected` when given. */\n hasFlash(key: string, ...expected: [] | [unknown]): this {\n AssertableInertia.assertFlashHas(this.page.flash ?? {}, key, ...expected)\n return this\n }\n\n missingFlash(key: string): this {\n AssertableInertia.assertFlashMissing(this.page.flash ?? {}, key)\n return this\n }\n\n static assertFlashHas(flash: Record<string, unknown>, key: string, ...expected: [] | [unknown]): void {\n assert(Arr.has(flash, key), `Inertia Flash Data is missing key [${key}].`)\n if (expected.length > 0) {\n const actual = Arr.get(flash, key)\n assert(equals(actual, expected[0]), `Inertia Flash Data [${key}] does not match expected value.`, { actual, expected: expected[0] })\n }\n }\n\n static assertFlashMissing(flash: Record<string, unknown>, key: string): void {\n assert(!Arr.has(flash, key), `Inertia Flash Data has unexpected key [${key}].`)\n }\n\n /**\n * Requests the page again as a partial reload (only/except) and checks it is the same page. Uses the test's\n * HTTP client, so the session and cookies carry over.\n */\n async reload(callback?: (page: AssertableInertia) => unknown, only?: string | string[], except?: string | string[]): Promise<this> {\n const client = this.#response?.context.client\n if (client === undefined) fail('reload() needs a response from the test HTTP client.')\n const headers: Record<string, string> = {\n 'X-Inertia': 'true',\n 'X-Requested-With': 'XMLHttpRequest',\n 'X-Inertia-Version': this.page.version,\n }\n const onlyList = only === undefined ? undefined : [only].flat().join(',')\n const exceptList = except === undefined ? undefined : [except].flat().join(',')\n if (onlyList !== undefined || exceptList !== undefined) headers['X-Inertia-Partial-Component'] = this.page.component\n if (onlyList !== undefined) headers['X-Inertia-Partial-Data'] = onlyList\n if (exceptList !== undefined) headers['X-Inertia-Partial-Except'] = exceptList\n const response = await client.request('GET', this.page.url, { headers })\n const reloaded = AssertableInertia.fromTestResponse(response)\n reloaded.component(this.page.component, false).url(this.page.url).version(this.page.version)\n await callback?.(reloaded)\n return this\n }\n\n reloadOnly(only: string | string[], callback?: (page: AssertableInertia) => unknown): Promise<this> {\n return this.reload(\n async (page) => {\n page.hasAll(typeof only === 'string' ? only.split(',') : only)\n await callback?.(page)\n },\n only,\n )\n }\n\n reloadExcept(except: string | string[], callback?: (page: AssertableInertia) => unknown): Promise<this> {\n return this.reload(\n async (page) => {\n page.missingAll(typeof except === 'string' ? except.split(',') : except)\n await callback?.(page)\n },\n undefined,\n except,\n )\n }\n\n /** Loads the deferred props of every group (or the given groups) in one partial reload. */\n loadDeferredProps(groupsOrCallback: string | string[] | ((page: AssertableInertia) => unknown), callback?: (page: AssertableInertia) => unknown): Promise<this> {\n const deferred = this.page.deferredProps ?? {}\n const groups = typeof groupsOrCallback === 'function' ? Object.keys(deferred) : [groupsOrCallback].flat()\n const props = groups.flatMap((group) => deferred[group] ?? [])\n return this.reloadOnly(props.join(','), typeof groupsOrCallback === 'function' ? groupsOrCallback : callback)\n }\n\n override toArray(): Record<string, unknown> {\n return {\n component: this.page.component,\n props: this.prop(),\n url: this.page.url,\n version: this.page.version,\n flash: this.page.flash ?? {},\n ...(this.page.encryptHistory === true ? { encryptHistory: true } : {}),\n ...(this.page.clearHistory === true ? { clearHistory: true } : {}),\n }\n }\n\n #app(): Application | undefined {\n return this.#response?.context.app\n }\n}\n","import { Arr } from '@orieljs/support'\nimport { assert, equals, fail, format } from '../assert'\n\ntype Json = unknown\ntype Scope<T extends AssertableJson> = (json: T) => unknown\n\n/** 'string', 'integer', 'double', 'number', 'boolean', 'array' (a list or an object, like PHP), 'object', 'null'. */\nfunction typeOf(value: unknown): string[] {\n if (value === null) return ['null']\n if (Array.isArray(value)) return ['array']\n switch (typeof value) {\n case 'string':\n return ['string']\n case 'boolean':\n return ['boolean']\n case 'number':\n return Number.isInteger(value) ? ['integer', 'number'] : ['double', 'float', 'number']\n case 'object':\n return ['array', 'object']\n default:\n return [typeof value]\n }\n}\n\n/**\n * Laravel's Illuminate\\Testing\\Fluent\\AssertableJson: fluent, scoped assertions over decoded JSON. Inside a scope\n * (has(key, callback), first(), each()) every property must be interacted with, or etc() must be called.\n */\nexport class AssertableJson {\n protected interactedKeys: string[] = []\n\n constructor(\n protected readonly props: Json,\n protected readonly path: string | undefined = undefined,\n ) {}\n\n static fromJson(json: Json): AssertableJson {\n return new AssertableJson(json)\n }\n\n /** A child scope of the same class (subclasses override to keep their extra state out of scopes). */\n protected newScope(props: Json, path: string): AssertableJson {\n return new AssertableJson(props, path)\n }\n\n protected dotPath(key = ''): string {\n if (this.path === undefined) return key\n return key === '' ? this.path : `${this.path}.${key}`\n }\n\n /** The value at `key` in this scope, or the whole scope. */\n protected prop(key?: string): Json {\n if (key !== undefined && this.hasOwnKey(key)) return (this.props as Record<string, unknown>)[key]\n return Arr.get(this.props, key)\n }\n\n /** A literal key of this scope wins over a dot path, like Laravel's Arr::get (keys such as 'items.0.name'). */\n private hasOwnKey(key: string): boolean {\n return typeof this.props === 'object' && this.props !== null && Object.hasOwn(this.props, key)\n }\n\n private exists(key: string): boolean {\n return this.hasOwnKey(key) || Arr.has(this.props, key)\n }\n\n protected interactsWith(key: string | number): void {\n const prop = this.hasOwnKey(String(key)) ? String(key) : String(key).split('.')[0]!\n if (!this.interactedKeys.includes(prop)) this.interactedKeys.push(prop)\n }\n\n /** Every property of the scope was checked (called when a scope ends). */\n interacted(): void {\n const props = this.prop()\n const keys = typeof props === 'object' && props !== null ? Object.keys(props) : []\n const unexpected = keys.filter((key) => !this.interactedKeys.includes(key))\n assert(\n unexpected.length === 0,\n this.path === undefined ? 'Unexpected properties were found on the root level.' : `Unexpected properties were found in scope [${this.path}].`,\n { actual: unexpected, expected: [] },\n )\n }\n\n /** Allow the properties this scope didn't check. */\n etc(): this {\n const props = this.prop()\n this.interactedKeys = typeof props === 'object' && props !== null ? Object.keys(props) : []\n return this\n }\n\n // Has ------------------------------------------------------------------------------------------------------\n\n /** has('key'), has('key', 3), has('key', json => …), has('key', 3, first => …), or has(3) for the root size. */\n has(key: string | number, length?: number | Scope<this>, callback?: Scope<this>): this {\n if (typeof key === 'number' && length === undefined) return this.count(key)\n const name = String(key)\n assert(this.exists(name), `Property [${this.dotPath(name)}] does not exist.`)\n this.interactsWith(name)\n if (callback !== undefined) {\n return this.has(name, (scope: this) => {\n if (typeof length === 'number') scope.count(length)\n scope.first(callback).etc()\n })\n }\n if (typeof length === 'function') return this.scope(name, length)\n if (typeof length === 'number') return this.count(name, length)\n return this\n }\n\n /** hasAll(['a', 'b']) or hasAll({ items: 3 }). */\n hasAll(keys: string | string[] | Record<string, number>): this {\n if (typeof keys === 'string' || Array.isArray(keys)) {\n for (const key of [keys].flat()) this.has(key)\n return this\n }\n for (const [key, length] of Object.entries(keys)) this.has(key, length)\n return this\n }\n\n hasAny(keys: string | string[]): this {\n const list = [keys].flat()\n const present = list.filter((key) => this.exists(key))\n assert(present.length > 0, `None of properties [${list.map((key) => this.dotPath(key)).join(', ')}] exist.`)\n for (const key of present) this.interactsWith(key)\n return this\n }\n\n missing(key: string): this {\n assert(!this.exists(key), `Property [${this.dotPath(key)}] was found while it was expected to be missing.`)\n return this\n }\n\n missingAll(keys: string | string[]): this {\n for (const key of [keys].flat()) this.missing(key)\n return this\n }\n\n /** count(3) checks this scope's size; count('items', 3) a property's. */\n count(key: string | number, length?: number): this {\n if (typeof key === 'number') {\n const size = sizeOf(this.prop())\n assert(size === key, this.path === undefined ? 'Root level does not have the expected size.' : `Property [${this.path}] does not have the expected size.`, { actual: size, expected: key })\n return this\n }\n this.has(key)\n const size = sizeOf(this.prop(key))\n assert(size === length, `Property [${this.dotPath(key)}] does not have the expected size.`, { actual: size, expected: length })\n return this\n }\n\n countBetween(key: string, min: number, max: number): this {\n this.has(key)\n const size = sizeOf(this.prop(key))\n assert(size >= min && size <= max, `Property [${this.dotPath(key)}] size is not between ${min} and ${max}.`, { actual: size })\n return this\n }\n\n // Matching -------------------------------------------------------------------------------------------------\n\n /** where('name', 'Ann'), or where('name', value => value.startsWith('A')). Objects compare ignoring key order. */\n where(key: string, expected: unknown): this {\n this.has(key)\n const actual = this.prop(key)\n if (typeof expected === 'function') {\n assert((expected as (value: unknown) => unknown)(actual), `Property [${this.dotPath(key)}] was marked as invalid using a closure.`)\n return this\n }\n const normalized = toPlain(expected)\n assert(equals(normalized, actual), `Property [${this.dotPath(key)}] does not match the expected value.`, { actual, expected: normalized })\n return this\n }\n\n whereNot(key: string, expected: unknown): this {\n this.has(key)\n const actual = this.prop(key)\n if (typeof expected === 'function') {\n assert(!(expected as (value: unknown) => unknown)(actual), `Property [${this.dotPath(key)}] was marked as invalid using a closure.`)\n return this\n }\n assert(!equals(toPlain(expected), actual), `Property [${this.dotPath(key)}] contains a value that should be missing: [${key}, ${format(expected)}]`)\n return this\n }\n\n whereNull(key: string): this {\n this.has(key)\n const actual = this.prop(key)\n assert(actual === null, `Property [${this.dotPath(key)}] should be null.`, { actual, expected: null })\n return this\n }\n\n whereNotNull(key: string): this {\n this.has(key)\n assert(this.prop(key) !== null, `Property [${this.dotPath(key)}] should not be null.`)\n return this\n }\n\n whereAll(bindings: Record<string, unknown>): this {\n for (const [key, value] of Object.entries(bindings)) this.where(key, value)\n return this\n }\n\n /** whereType('id', 'integer'), whereType('name', 'string|null'), whereType('tags', ['array', 'null']). */\n whereType(key: string, expected: string | string[]): this {\n this.has(key)\n const types = typeof expected === 'string' ? expected.split('|') : expected\n const actual = typeOf(this.prop(key))\n assert(\n types.some((type) => actual.includes(type)),\n `Property [${this.dotPath(key)}] is not of expected type [${types.join('|')}].`,\n { actual: actual[0], expected: types.join('|') },\n )\n return this\n }\n\n whereAllType(bindings: Record<string, string | string[]>): this {\n for (const [key, type] of Object.entries(bindings)) this.whereType(key, type)\n return this\n }\n\n /** The list contains every expected value (or one passing the callback); a string contains the substring. */\n whereContains(key: string, expected: unknown): this {\n this.has(key)\n const actual = this.prop(key)\n if (typeof actual === 'string') {\n assert(actual.includes(String(expected)), `Property [${this.dotPath(key)}] does not contain [${format(expected)}].`)\n return this\n }\n const values = typeof actual === 'object' && actual !== null ? Object.values(actual) : [actual]\n const wanted = Array.isArray(expected) ? expected : [expected]\n const missing = wanted.filter((item) =>\n typeof item === 'function' ? !values.some((value) => (item as (value: unknown) => unknown)(value)) : !values.some((value) => equals(toPlain(item), value)),\n )\n assert(missing.length === 0, `Property [${this.dotPath(key)}] does not contain [${missing.map(format).join(', ')}].`, { actual })\n return this\n }\n\n // Scoping --------------------------------------------------------------------------------------------------\n\n protected scope(key: string, callback: Scope<this>): this {\n const props = this.prop(key)\n const path = this.dotPath(key)\n assert(typeof props === 'object' && props !== null, `Property [${path}] is not scopeable.`)\n const scope = this.newScope(props, path) as this\n callback(scope)\n scope.interacted()\n return this\n }\n\n first(callback: Scope<this>): this {\n const props = this.prop()\n const keys = typeof props === 'object' && props !== null ? Object.keys(props) : []\n if (keys.length === 0) {\n fail(this.path === undefined ? 'Cannot scope directly onto the first element of the root level because it is empty.' : `Cannot scope directly onto the first element of property [${this.path}] because it is empty.`)\n }\n this.interactsWith(keys[0]!)\n return this.scope(keys[0]!, callback)\n }\n\n each(callback: Scope<this>): this {\n const props = this.prop()\n const keys = typeof props === 'object' && props !== null ? Object.keys(props) : []\n if (keys.length === 0) {\n fail(this.path === undefined ? 'Cannot scope directly onto each element of the root level because it is empty.' : `Cannot scope directly onto each element of property [${this.path}] because it is empty.`)\n }\n for (const key of keys) {\n this.interactsWith(key)\n this.scope(key, callback)\n }\n return this\n }\n\n // Helpers --------------------------------------------------------------------------------------------------\n\n when(condition: unknown, callback: (json: this) => unknown, otherwise?: (json: this) => unknown): this {\n if (condition) callback(this)\n else otherwise?.(this)\n return this\n }\n\n dump(key?: string): this {\n console.log(format(this.prop(key)))\n return this\n }\n\n toArray(): Json {\n return this.prop()\n }\n}\n\nfunction sizeOf(value: unknown): number {\n if (Array.isArray(value)) return value.length\n if (typeof value === 'object' && value !== null) return Object.keys(value).length\n if (typeof value === 'string') return value.length\n return 0\n}\n\n/** Expected values go through JSON like the response did: models, collections and dates compare as their JSON. */\nfunction toPlain(value: unknown): unknown {\n return value === undefined ? undefined : (JSON.parse(JSON.stringify(value)) as unknown)\n}\n","import { createHmac } from 'node:crypto'\nimport type { Encrypter } from '@orieljs/contracts'\n\n/** Laravel's CookieValuePrefix: hmac_sha1(name + 'v2', key) + '|' (41 characters), as Auth's EncryptCookies writes it. */\nexport function cookiePrefix(name: string, key: Uint8Array): string {\n return `${createHmac('sha1', key).update(`${name}v2`).digest('hex')}|`\n}\n\n/** What EncryptCookies puts in a browser cookie: encrypt(prefix + value, serialize: false). */\nexport function encryptCookie(encrypter: Encrypter, name: string, value: string): string {\n return encrypter.encrypt(cookiePrefix(name, encrypter.getKey()) + value, false)\n}\n\n/** The plain value of an encrypted cookie, or undefined when it doesn't decrypt or its prefix is wrong. */\nexport function decryptCookie(encrypter: Encrypter, name: string, value: string): string | undefined {\n try {\n const plain = encrypter.decrypt<string>(value, false)\n const prefix = cookiePrefix(name, encrypter.getKey())\n return plain.startsWith(prefix) ? plain.slice(prefix.length) : undefined\n } catch {\n return undefined\n }\n}\n\nexport interface ResponseCookie {\n name: string\n /** URI-decoded, still encrypted if the app encrypted it. */\n value: string\n path?: string\n domain?: string\n maxAge?: number\n expires?: Date\n httpOnly: boolean\n secure: boolean\n sameSite?: string\n}\n\nconst decode = (text: string) => {\n try {\n return decodeURIComponent(text)\n } catch {\n return text\n }\n}\n\nexport function parseSetCookie(header: string): ResponseCookie {\n const [pair = '', ...attributes] = header.split(';')\n const eq = pair.indexOf('=')\n const cookie: ResponseCookie = {\n name: decode(pair.slice(0, eq).trim()),\n value: decode(pair.slice(eq + 1).trim().replace(/^\"(.*)\"$/, '$1')),\n httpOnly: false,\n secure: false,\n }\n for (const attribute of attributes) {\n const at = attribute.indexOf('=')\n const key = (at === -1 ? attribute : attribute.slice(0, at)).trim().toLowerCase()\n const value = at === -1 ? '' : attribute.slice(at + 1).trim()\n if (key === 'path') cookie.path = value\n else if (key === 'domain') cookie.domain = value\n else if (key === 'max-age') cookie.maxAge = Number(value)\n else if (key === 'expires') cookie.expires = new Date(value)\n else if (key === 'httponly') cookie.httpOnly = true\n else if (key === 'secure') cookie.secure = true\n else if (key === 'samesite') cookie.sameSite = value\n }\n return cookie\n}\n\n/** Max-Age <= 0 or an Expires in the past: the server is deleting the cookie. */\nexport function isExpired(cookie: ResponseCookie, now = Date.now()): boolean {\n if (cookie.maxAge !== undefined && !Number.isNaN(cookie.maxAge)) return cookie.maxAge <= 0\n return cookie.expires !== undefined && cookie.expires.getTime() <= now\n}\n\nexport function responseCookies(response: Response): ResponseCookie[] {\n return response.headers.getSetCookie().map(parseSetCookie)\n}\n\nexport function cookieHeader(cookies: Map<string, string>): string {\n return [...cookies].map(([name, value]) => `${encodeURIComponent(name)}=${encodeURIComponent(value)}`).join('; ')\n}\n","import type { AuthFactory, Authenticatable, ExceptionHandler, View, ViewFactory } from '@orieljs/contracts'\n\n/** Forwards every property to `target`, with methods bound to it; `overrides` replace single members. */\nfunction forward<T extends object>(target: T, overrides: Partial<Record<PropertyKey, unknown>>, before?: () => void): T {\n return new Proxy(target, {\n get(object, property) {\n before?.()\n if (Object.hasOwn(overrides, property)) return overrides[property]\n const value: unknown = Reflect.get(object, property, object)\n return typeof value === 'function' ? (value as (...args: unknown[]) => unknown).bind(object) : value\n },\n })\n}\n\n/** The request scope's ViewFactory: records every view made, so TestResponse can assert on it (assertViewIs/Has). */\nexport function recordingViewFactory(factory: ViewFactory, views: View[]): ViewFactory {\n return forward(factory, {\n make(name: string, data?: Record<string, unknown>): View {\n const view = factory.make(name, data)\n views.push(view)\n return view\n },\n })\n}\n\n/**\n * The request scope's ExceptionHandler: records the error it renders (for failure messages and\n * withoutExceptionHandling()), then renders it as usual.\n */\nexport function recordingExceptionHandler(handler: ExceptionHandler, record: (error: unknown) => void): ExceptionHandler {\n return forward(handler, {\n async render(request: unknown, error: unknown): Promise<Response> {\n record(error)\n return handler.render(request, error)\n },\n })\n}\n\n/**\n * The request scope's AuthFactory for actingAs(): the users are put on the scope's guards the first time\n * anything touches auth. That is after the kernel bound HttpRequest, so request.user() sees them too.\n * `onApply` runs when that happens, so the client knows to read the guards back after the request.\n */\nexport function actingAsAuthFactory(\n auth: AuthFactory,\n users: Map<string | undefined, Authenticatable>,\n defaultGuard: string | undefined,\n onApply?: () => void,\n): AuthFactory {\n let applied = false\n const apply = () => {\n if (applied) return\n applied = true\n if (defaultGuard !== undefined) auth.shouldUse(defaultGuard)\n for (const [guard, user] of users) auth.guard(guard).setUser(user)\n onApply?.()\n }\n return forward(auth, {}, apply)\n}\n","import {\n DatabaseManager,\n type Application,\n type ServiceProvider,\n type ServiceProviderClass,\n} from '@orieljs/contracts'\nimport { Container } from '@orieljs/container'\nimport { Application as FoundationApplication, Vite, ViteHtml } from '@orieljs/foundation'\nimport { applyEnvironment, TESTING_ENVIRONMENT } from '../environment'\n\n/** The test runner's per-test hooks. Pass Vitest's: `{ beforeEach, afterEach }`. */\nexport interface TestHooks {\n beforeEach(fn: () => unknown): void\n afterEach(fn: () => unknown): void\n}\n\n/** A Laravel-style trait (RefreshDatabase, …): setUp runs after the app boots; clean-up goes in beforeApplicationDestroyed. */\nexport interface TestTrait {\n setUp(test: InteractsWithApplication): void | Promise<void>\n}\n\nexport interface BootOptions {\n hooks?: TestHooks\n /** Extra traits for this file, like `use RefreshDatabase;`. */\n uses?: TestTrait[]\n}\n\ntype Callback = () => void | Promise<void>\n\nconst globalHooks = (): TestHooks | undefined => {\n const g = globalThis as { beforeEach?: TestHooks['beforeEach']; afterEach?: TestHooks['afterEach'] }\n return typeof g.beforeEach === 'function' && typeof g.afterEach === 'function'\n ? { beforeEach: g.beforeEach, afterEach: g.afterEach }\n : undefined\n}\n\n/**\n * Laravel's TestCase lifecycle: a brand-new application for every test (createApplication() → boot → traits),\n * and a full teardown after it, so no state survives from one test to the next.\n */\nexport abstract class InteractsWithApplication {\n /** Set once in tests/TestCase.ts: `static override hooks = { beforeEach, afterEach }` (from vitest). */\n static hooks?: TestHooks\n\n /** Traits this test case uses (Laravel's `use RefreshDatabase;`). */\n readonly uses: TestTrait[] = []\n\n private application: Application | undefined\n private extraTraits: TestTrait[] = []\n private destroying: Callback[] = []\n\n /**\n * Creates the test case and registers its setUp/tearDown as beforeEach/afterEach hooks.\n * `const t = TestCase.boot()` at the top of a test file (or inside a describe block).\n */\n static boot<T extends InteractsWithApplication>(this: (new () => T) & { hooks?: TestHooks }, options: BootOptions = {}): T {\n const hooks = options.hooks ?? this.hooks ?? globalHooks()\n if (hooks === undefined) {\n throw new Error(\n 'TestCase.boot() needs the test runner hooks: set `static override hooks = { beforeEach, afterEach }` ' +\n '(imported from vitest) in tests/TestCase.ts, or pass { hooks }.',\n )\n }\n const test = new this()\n test.extraTraits = [...(options.uses ?? [])]\n hooks.beforeEach(() => test.setUp())\n hooks.afterEach(() => test.tearDown())\n return test\n }\n\n /** The current test's application. */\n get app(): Application {\n if (this.application === undefined) {\n throw new Error('There is no application outside a test: use it inside test() (after TestCase.boot()).')\n }\n return this.application\n }\n\n /**\n * A fresh application for one test. tests/TestCase.ts overrides this to call bootstrap/app's factory.\n * The default builds one at basePath() with providers(), for package tests with no skeleton.\n */\n createApplication(): Promise<Application> {\n return FoundationApplication.configure({ basePath: this.basePath() }).withProviders(this.providers()).create()\n }\n\n /** Used by the default createApplication(). */\n protected basePath(): string {\n return process.cwd()\n }\n\n /** Used by the default createApplication(). */\n protected providers(): Array<ServiceProvider | ServiceProviderClass> {\n return []\n }\n\n /** The variables applied (unless already set) before each application is created. */\n protected environment(): Record<string, string> {\n return { ...TESTING_ENVIRONMENT }\n }\n\n /** Adjust the fresh app before it boots, e.g. `app.make(ConfigRepository).set('mail.default', 'array')`. */\n protected defineEnvironment(_app: Application): void | Promise<void> {}\n\n async setUp(): Promise<void> {\n applyEnvironment(this.environment())\n const app = await this.createApplication()\n this.application = app\n app.setRunningInConsole(true)\n await this.defineEnvironment(app)\n await app.boot()\n for (const trait of [...this.uses, ...this.extraTraits]) await trait.setUp(this)\n }\n\n async tearDown(): Promise<void> {\n const app = this.application\n if (app === undefined) return\n try {\n for (const callback of this.destroying) await callback()\n if (app.resolved(DatabaseManager)) await disconnectAll(app.make(DatabaseManager))\n } finally {\n this.destroying = []\n this.application = undefined\n const global: unknown = Container.getInstance()\n if (global === app) Container.setInstance(undefined)\n }\n }\n\n /**\n * Laravel's withoutVite(): in this test's requests vite([...]) and viteReactRefresh() render nothing, so feature\n * tests of pages pass before `vite build` has written public/build/manifest.json.\n */\n withoutVite(): this {\n const app = this.app\n app.scoped(Vite, () => new WithoutVite(app))\n return this\n }\n\n /** Runs in tearDown(), before the application is thrown away (in registration order). */\n beforeApplicationDestroyed(callback: Callback): void {\n this.destroying.push(callback)\n }\n}\n\n/** The Vite that withoutVite() swaps in: no tags, no assets, no manifest needed. */\nclass WithoutVite extends Vite {\n override tags(): ViteHtml {\n return new ViteHtml('')\n }\n\n override reactRefresh(): ViteHtml | undefined {\n return undefined\n }\n\n override asset(): string {\n return ''\n }\n\n override content(): string {\n return ''\n }\n\n override manifestHash(): string | undefined {\n return undefined\n }\n\n override preloadedAssets(): Record<string, string[]> {\n return {}\n }\n\n override toHtml(): string {\n return ''\n }\n}\n\n/** Closes every database connection the test opened (Database's disconnectAll() when present, else the default). */\nasync function disconnectAll(db: DatabaseManager): Promise<void> {\n const manager = db as DatabaseManager & { disconnectAll?(): Promise<void> }\n if (typeof manager.disconnectAll === 'function') await manager.disconnectAll()\n else await manager.disconnect()\n}\n","import { PendingCommand } from '../Console/PendingCommand'\nimport { InteractsWithDatabase } from './InteractsWithDatabase'\n\n/** Laravel's InteractsWithConsole: `await t.artisan('cmd', { user: 1, '--queue': 'high' }).assertExitCode(0)`. */\nexport abstract class InteractsWithConsole extends InteractsWithDatabase {\n /** The command runs when the returned PendingCommand is awaited; without `await` it never runs. */\n artisan(command: string, parameters: Record<string, unknown> = {}): PendingCommand {\n return new PendingCommand(this.app, command, parameters)\n }\n}\n","import { freezeSecond, freezeTime, travel, travelBack, travelTo, type TravelDate, type Wormhole } from '../time'\nimport { InteractsWithConsole } from './InteractsWithConsole'\n\n/**\n * Laravel's InteractsWithTime: `t.travelTo(date)`, `t.travel(5).minutes()`, `t.freezeTime()`, `t.travelBack()`.\n * The functions of the same names do the same outside a test case. A test case's tearDown travels back, so each of its\n * tests ends in the real time; with the plain functions, call `travelBack()` in your own `afterEach()` or pass a callback.\n */\nexport abstract class InteractsWithTime extends InteractsWithConsole {\n travelTo(date: TravelDate): void\n travelTo<R>(date: TravelDate, callback: (date: Date) => R): R\n travelTo<R>(date: TravelDate, callback?: (date: Date) => R): R | void {\n return callback ? travelTo(date, callback) : travelTo(date)\n }\n\n travel(value: number): Wormhole {\n return travel(value)\n }\n\n travelBack(): Date {\n return travelBack()\n }\n\n freezeTime(): Date\n freezeTime<R>(callback: (date: Date) => R): R\n freezeTime<R>(callback?: (date: Date) => R): Date | R {\n return callback ? freezeTime(callback) : freezeTime()\n }\n\n freezeSecond(): Date\n freezeSecond<R>(callback: (date: Date) => R): R\n freezeSecond<R>(callback?: (date: Date) => R): Date | R {\n return callback ? freezeSecond(callback) : freezeSecond()\n }\n\n override async tearDown(): Promise<void> {\n try {\n await super.tearDown()\n } finally {\n travelBack()\n }\n }\n}\n","import { InteractsWithTime } from './Concerns/InteractsWithTime'\n\n/**\n * Laravel's TestCase. Extend it in tests/TestCase.ts (override createApplication() and set `static hooks`),\n * then in each file: `const t = TestCase.boot()`, or `TestCase.boot({ uses: [RefreshDatabase] })`.\n */\nexport abstract class TestCase extends InteractsWithTime {}\n","import type { Class, Token } from '@orieljs/contracts'\nimport { currentContainer } from '@orieljs/container'\nimport { facade } from '@orieljs/support'\nimport { equals } from '../assert'\n\n/** What an assertion targets: a class (exact constructor), or a name (a string event, a class name or a registry name). */\nexport type Target<T = unknown> = Class<T> | string\n\n/** A count, or a filter over the recorded items. */\nexport type CountOrFilter<A extends unknown[]> = number | ((...args: A) => boolean)\n\n/** Swaps the fake in through the facade machinery (`facade(token).swap(fake)`: an instance on the current container). */\nexport function install<T extends object, F extends T>(token: Token<T>, fake: F): F {\n facade(token).swap(fake)\n return fake\n}\n\n/** The instance currently bound for `token`, if any (the thing a fake wraps). */\nexport function bound<T>(token: Token<T>): T | undefined {\n const container = currentContainer()\n return container !== undefined && container.bound(token) ? container.make(token) : undefined\n}\n\nexport function nameOf(target: Target | object): string {\n if (typeof target === 'string') return target\n if (typeof target === 'function') return target.name\n return (target as object).constructor.name\n}\n\n/** A recorded object (or string event) matches a target: same constructor, or the same (class) name. */\nexport function matches(item: unknown, target: Target): boolean {\n if (typeof target === 'string') return typeof item === 'string' ? item === target : typeof item === 'object' && item !== null && item.constructor.name === target\n return typeof item === 'object' && item !== null && item.constructor === target\n}\n\nexport function matchesAny(item: unknown, targets: Target[]): boolean {\n return targets.some((target) => matches(item, target))\n}\n\n/** A class or instance in an expected list: classes match by constructor, instances by constructor and equal fields. */\nexport function sameJob(actual: object, expected: Target | object): boolean {\n if (typeof expected === 'function' || typeof expected === 'string') return matches(actual, expected as Target)\n return actual.constructor === expected.constructor && equals({ ...actual }, { ...expected })\n}\n\n/** Bus's ShouldQueue marker (the Queueable base class sets it on its prototype); the same Symbol.for key as Bus's. */\nexport const SHOULD_QUEUE = Symbol.for('oriel:bus.shouldQueue')\nconst QUEUE_OPTIONS = ['connection', 'queue', 'delay', 'tries', 'backoff', 'timeout'] as const\n\ntype Members = Record<PropertyKey, unknown>\n\n/**\n * A copy of Bus's isQueueable(), read on the instance: ShouldQueue's `shouldQueue: true` (own field or prototype),\n * the SHOULD_QUEUE symbol, a value for any ShouldQueue option, or uniqueId()/retryUntil().\n */\nexport function isQueueable(job: unknown): boolean {\n if (typeof job !== 'object' || job === null) return false\n const members = job as Members\n if (members.shouldQueue === true || members[SHOULD_QUEUE] === true) return true\n if (QUEUE_OPTIONS.some((option) => members[option] !== undefined)) return true\n return typeof members.uniqueId === 'function' || typeof members.retryUntil === 'function'\n}\n","import { EventDispatcher, type Class, type Listener } from '@orieljs/contracts'\nimport { Str } from '@orieljs/support'\nimport { assert } from '../assert'\nimport { bound, install, matchesAny, nameOf, type CountOrFilter, type Target } from './support'\n\n/** One dispatch: the event object (or name) and its payload. */\nexport interface DispatchedEvent {\n event: object | string\n payload: unknown[]\n}\n\ntype EventFilter<E> = (event: E, payload: unknown[]) => boolean\n\n/** A listener as assertListening() expects it: a class, a [class, method] pair, a closure, or Function for any closure. */\nexport type ExpectedListener = Listener<never> | readonly [Class<object>, string] | FunctionConstructor\n\n/** What a dispatcher that can list its listeners (Events' Dispatcher) offers. */\ninterface ListsListeners {\n getRawListeners(): ReadonlyMap<unknown, readonly unknown[]>\n}\n\nconst isClass = (value: unknown): value is Class<{ handle?: unknown }> =>\n typeof value === 'function' && typeof (value.prototype as { handle?: unknown } | undefined)?.handle === 'function'\n\n/** A [class, method] pair: a listener class registered on its own is [class, 'handle']. */\nconst asPair = (listener: unknown): [unknown, string] | undefined => {\n if (Array.isArray(listener) && listener.length === 2 && typeof listener[1] === 'string') return [listener[0], listener[1]]\n return isClass(listener) ? [listener, 'handle'] : undefined\n}\n\n/** Laravel's comparison: the same listener, or Closure::class (here Function) for any closure. */\nfunction listenerMatches(registered: unknown, expected: ExpectedListener): boolean {\n if (expected === Function) return typeof registered === 'function' && !isClass(registered)\n const [left, right] = [asPair(registered), asPair(expected)]\n if (left && right) return left[0] === right[0] && left[1] === right[1]\n return registered === expected\n}\n\n/** How the failure message names the listener: the class, Class@method, or Closure. */\nfunction listenerName(listener: ExpectedListener): string {\n const pair = asPair(listener)\n if (pair === undefined) return 'Closure'\n const [owner, method] = pair as [Class<object>, string]\n return Array.isArray(listener) ? `${owner.name}@${method}` : owner.name\n}\n\n/**\n * Laravel's Event::fake(): records dispatched events instead of running listeners. With a list, only those\n * events are faked and everything else reaches the original dispatcher (so model events keep working).\n */\nexport class EventFake implements EventDispatcher {\n readonly events: DispatchedEvent[] = []\n\n constructor(\n readonly dispatcher: EventDispatcher | undefined,\n private readonly eventsToFake: Target[] = [],\n private eventsToDispatch: Target[] = [],\n ) {}\n\n /** Installs the fake (on the current container) and returns it: `const events = EventFake.fake([OrderShipped])`. */\n static fake(eventsToFake: Target | Target[] = []): EventFake {\n return install(EventDispatcher, new EventFake(EventFake.original(), [eventsToFake].flat()))\n }\n\n /** Fakes every event except these. */\n static fakeExcept(eventsToDispatch: Target | Target[]): EventFake {\n return install(EventDispatcher, new EventFake(EventFake.original(), [], [eventsToDispatch].flat()))\n }\n\n private static original(): EventDispatcher | undefined {\n const current = bound(EventDispatcher)\n return current instanceof EventFake ? current.dispatcher : current\n }\n\n except(events: Target | Target[]): this {\n this.eventsToDispatch = [...this.eventsToDispatch, ...[events].flat()]\n return this\n }\n\n // EventDispatcher -----------------------------------------------------------------------------------------\n\n listen<E>(events: Class<E> | string | Array<Class<E> | string>, listener: Listener<E>): void {\n this.dispatcher?.listen(events, listener)\n }\n\n hasListeners(event: Class<unknown> | string): boolean {\n return this.dispatcher?.hasListeners(event) ?? false\n }\n\n async dispatch(event: object | string, payload: unknown[] = []): Promise<unknown[]> {\n if (this.shouldFake(event)) {\n this.events.push({ event, payload })\n return []\n }\n return this.dispatcher?.dispatch(event, payload) ?? []\n }\n\n /** Faked events return undefined (never false), so halting model events such as `saving` still proceed. */\n async until(event: object | string, payload: unknown[] = []): Promise<unknown> {\n if (this.shouldFake(event)) {\n this.events.push({ event, payload })\n return undefined\n }\n return this.dispatcher?.until(event, payload)\n }\n\n subscribe(subscriber: Class<{ subscribe(events: EventDispatcher): void }>): void {\n this.dispatcher?.subscribe(subscriber)\n }\n\n forget(event: Class<unknown> | string): void {\n this.dispatcher?.forget(event)\n }\n\n // Assertions ------------------------------------------------------------------------------------------------\n\n /** Dispatched at least once; a number asserts the exact count; a function filters (event, payload). */\n assertDispatched<E>(event: Class<E> | string, callback?: CountOrFilter<[E, unknown[]]>): void {\n if (typeof callback === 'number') return this.assertDispatchedTimes(event, callback)\n assert(this.dispatched(event, callback).length > 0, `The expected [${nameOf(event)}] event was not dispatched.`)\n }\n\n assertDispatchedTimes<E>(event: Class<E> | string, times = 1): void {\n const count = this.dispatched(event).length\n assert(count === times, `The expected [${nameOf(event)}] event was dispatched ${count} times instead of ${times} times.`, { actual: count, expected: times })\n }\n\n assertNotDispatched<E>(event: Class<E> | string, callback?: EventFilter<E>): void {\n assert(this.dispatched(event, callback).length === 0, `The unexpected [${nameOf(event)}] event was dispatched.`)\n }\n\n assertNothingDispatched(): void {\n const names = this.events.map(({ event }) => nameOf(event))\n assert(names.length === 0, `${names.length} unexpected events were dispatched:\\n\\n- ${names.join('\\n- ')}`)\n }\n\n /**\n * Laravel's assertListening(event, listener): the original dispatcher has that listener for the event (a class, a\n * [class, method] pair, the same closure, or Function for any closure; wildcard listeners count for a string event).\n * With only the event, any listener will do.\n */\n assertListening(event: Class<unknown> | string, listener?: ExpectedListener): void {\n if (listener === undefined) {\n assert(this.hasListeners(event), `Event [${nameOf(event)}] does not have any listeners.`)\n return\n }\n assert(\n this.listenersFor(event).some((registered) => listenerMatches(registered, listener)),\n `Event [${nameOf(event)}] does not have the [${listenerName(listener)}] listener attached to it`,\n )\n }\n\n /** The recorded events (objects, or names for string events) that match. */\n dispatched<E>(event: Class<E> | string, callback?: EventFilter<E>): E[] {\n return this.events\n .filter((record) => matchesAny(record.event, [event]) && (callback === undefined || callback(record.event as E, record.payload)))\n .map((record) => record.event as E)\n }\n\n hasDispatched(event: Class<unknown> | string): boolean {\n return this.dispatched(event).length > 0\n }\n\n /** The original dispatcher's listeners for the event, as registered, wildcard ones included for a string event. */\n private listenersFor(event: Class<unknown> | string): unknown[] {\n const raw = (this.dispatcher as Partial<ListsListeners> | undefined)?.getRawListeners?.()\n if (raw === undefined) return []\n const listeners = [...(raw.get(event) ?? [])]\n if (typeof event !== 'string') return listeners\n for (const [key, list] of raw) {\n if (typeof key === 'string' && key !== event && key.includes('*') && Str.is(key, event)) listeners.push(...list)\n }\n return listeners\n }\n\n private shouldFake(event: object | string): boolean {\n if (matchesAny(event, this.eventsToDispatch)) return false\n return this.eventsToFake.length === 0 || matchesAny(event, this.eventsToFake)\n }\n}\n","import { BusDispatcher, type Batch, type Job, type PendingBatch, type PendingBatchOptions, type PendingChain } from '@orieljs/contracts'\nimport { randomUUID } from 'node:crypto'\nimport { assert, fail } from '../assert'\nimport { bound, install, matchesAny, nameOf, sameJob, type CountOrFilter, type Target } from './support'\n\ntype Filter<J> = (job: J) => boolean\n\n/** What a faked Bus.batch([...]).dispatch() recorded (Laravel's PendingBatchFake): the options Bus would store, plus the jobs. */\nexport interface BatchRecord extends PendingBatchOptions {\n readonly id: string\n readonly jobs: Job[]\n}\n\nclass FakeBatch implements Batch {\n constructor(private readonly record: BatchRecord) {}\n get id(): string { return this.record.id }\n get name(): string { return this.record.name }\n get totalJobs(): number { return this.record.jobs.length }\n get pendingJobs(): number { return this.record.jobs.length }\n readonly failedJobs = 0\n private isCancelled = false\n progress(): number { return 0 }\n finished(): boolean { return false }\n cancelled(): boolean { return this.isCancelled }\n async cancel(): Promise<void> { this.isCancelled = true }\n}\n\n/**\n * Laravel's Bus::fake(): records dispatch/dispatchSync/dispatchAfterResponse, chains and batches instead of\n * running or queueing them. With a list, only those jobs are faked; others go to the original dispatcher.\n */\nexport class BusFake implements BusDispatcher {\n readonly commands: Job[] = []\n readonly commandsSync: Job[] = []\n readonly commandsAfterResponse: Job[] = []\n readonly batches: BatchRecord[] = []\n /** The rest of the chain, by the first job (Bus.chain([a, b, c]) records a with [b, c]). */\n readonly chains = new Map<Job, Job[]>()\n\n constructor(\n readonly dispatcher: BusDispatcher | undefined,\n private readonly jobsToFake: Target[] = [],\n private jobsToDispatch: Target[] = [],\n ) {}\n\n static fake(jobsToFake: Target | Target[] = []): BusFake {\n return install(BusDispatcher, new BusFake(BusFake.original(), [jobsToFake].flat()))\n }\n\n static fakeExcept(jobsToDispatch: Target | Target[]): BusFake {\n return install(BusDispatcher, new BusFake(BusFake.original(), [], [jobsToDispatch].flat()))\n }\n\n private static original(): BusDispatcher | undefined {\n const current = bound(BusDispatcher)\n return current instanceof BusFake ? current.dispatcher : current\n }\n\n except(jobs: Target | Target[]): this {\n this.jobsToDispatch = [...this.jobsToDispatch, ...[jobs].flat()]\n return this\n }\n\n // BusDispatcher ----------------------------------------------------------------------------------------\n\n async dispatch(job: Job): Promise<unknown> {\n if (!this.shouldFake(job)) return this.real().dispatch(job)\n this.commands.push(job)\n return undefined\n }\n\n async dispatchSync(job: Job): Promise<unknown> {\n if (!this.shouldFake(job)) return this.real().dispatchSync(job)\n this.commandsSync.push(job)\n return undefined\n }\n\n dispatchAfterResponse(job: Job): void {\n if (!this.shouldFake(job)) return this.real().dispatchAfterResponse(job)\n this.commandsAfterResponse.push(job)\n }\n\n /**\n * Bus's terminating callback flushes whatever BusDispatcher is bound, which is this fake: forward to the real\n * dispatcher so the after-response jobs it didn't fake still run (Laravel runs them). Faked ones never run.\n */\n async flushAfterResponse(): Promise<void> {\n await (this.dispatcher as { flushAfterResponse?(): Promise<void> } | undefined)?.flushAfterResponse?.()\n }\n\n chain(jobs: Job[]): PendingChain {\n const options: { connection?: string; queue?: string } = {}\n const pending: PendingChain = {\n onConnection: (connection) => {\n options.connection = connection\n return pending\n },\n onQueue: (queue) => {\n options.queue = queue\n return pending\n },\n catch: () => pending,\n dispatch: async () => {\n const [first, ...rest] = jobs\n if (first === undefined) return\n if (!this.shouldFake(first)) return this.real().chain(jobs).dispatch()\n if (options.connection !== undefined) first.connection = options.connection\n if (options.queue !== undefined) first.queue = options.queue\n this.commands.push(first)\n this.chains.set(first, rest)\n },\n }\n return pending\n }\n\n batch(jobs: Job[]): PendingBatch {\n const record: BatchRecord = { id: randomUUID(), jobs, name: '', allowFailures: false, then: [], catch: [], finally: [] }\n const batches = this.batches\n const pending: PendingBatch = {\n name(name) { record.name = name; return pending },\n onConnection(connection) { record.connection = connection; return pending },\n onQueue(queue) { record.queue = queue; return pending },\n allowFailures(allow = true) { record.allowFailures = allow; return pending },\n then(job) { record.then.push(job); return pending },\n catch(job) { record.catch.push(job); return pending },\n finally(job) { record.finally.push(job); return pending },\n async dispatch() {\n batches.push(record)\n return new FakeBatch(record)\n },\n }\n return pending\n }\n\n async findBatch(id: string): Promise<Batch | undefined> {\n const record = this.batches.find((batch) => batch.id === id)\n return record === undefined ? undefined : new FakeBatch(record)\n }\n\n // Assertions ---------------------------------------------------------------------------------------------\n\n /** Dispatched in any way (dispatch, dispatchSync or dispatchAfterResponse); a number asserts the count. */\n assertDispatched<J extends Job>(job: Target<J>, callback?: CountOrFilter<[J]>): void {\n if (typeof callback === 'number') return this.assertDispatchedTimes(job, callback)\n const count = this.dispatched(job, callback).length + this.dispatchedSync(job, callback).length + this.dispatchedAfterResponse(job, callback).length\n assert(count > 0, `The expected [${nameOf(job)}] job was not dispatched.`)\n }\n\n assertDispatchedTimes<J extends Job>(job: Target<J>, times = 1): void {\n const count = this.dispatched(job).length + this.dispatchedSync(job).length + this.dispatchedAfterResponse(job).length\n assert(count === times, `The expected [${nameOf(job)}] job was pushed ${count} times instead of ${times} times.`, { actual: count, expected: times })\n }\n\n assertNotDispatched<J extends Job>(job: Target<J>, callback?: Filter<J>): void {\n const count = this.dispatched(job, callback).length + this.dispatchedSync(job, callback).length + this.dispatchedAfterResponse(job, callback).length\n assert(count === 0, `The unexpected [${nameOf(job)}] job was dispatched.`)\n }\n\n assertNothingDispatched(): void {\n const all = [...this.commands, ...this.commandsSync, ...this.commandsAfterResponse].map((job) => nameOf(job))\n assert(all.length === 0, `The following jobs were dispatched unexpectedly:\\n\\n- ${all.join('\\n- ')}`)\n }\n\n assertDispatchedSync<J extends Job>(job: Target<J>, callback?: CountOrFilter<[J]>): void {\n if (typeof callback === 'number') {\n const count = this.dispatchedSync(job).length\n assert(count === callback, `The expected [${nameOf(job)}] job was synchronously pushed ${count} times instead of ${callback} times.`, { actual: count, expected: callback })\n return\n }\n assert(this.dispatchedSync(job, callback).length > 0, `The expected [${nameOf(job)}] job was not dispatched synchronously.`)\n }\n\n assertNotDispatchedSync<J extends Job>(job: Target<J>, callback?: Filter<J>): void {\n assert(this.dispatchedSync(job, callback).length === 0, `The unexpected [${nameOf(job)}] job was dispatched synchronously.`)\n }\n\n assertDispatchedAfterResponse<J extends Job>(job: Target<J>, callback?: CountOrFilter<[J]>): void {\n if (typeof callback === 'number') {\n const count = this.dispatchedAfterResponse(job).length\n assert(count === callback, `The expected [${nameOf(job)}] job was pushed ${count} times instead of ${callback} times.`, { actual: count, expected: callback })\n return\n }\n assert(this.dispatchedAfterResponse(job, callback).length > 0, `The expected [${nameOf(job)}] job was not dispatched after sending the response.`)\n }\n\n assertNotDispatchedAfterResponse<J extends Job>(job: Target<J>, callback?: Filter<J>): void {\n assert(this.dispatchedAfterResponse(job, callback).length === 0, `The unexpected [${nameOf(job)}] job was dispatched after sending the response.`)\n }\n\n /** `[First, Second, new Third(1)]`: a dispatched First whose chain is exactly the rest (classes or equal instances). */\n assertChained(expectedChain: Array<Target | Job>): void {\n const [first, ...rest] = expectedChain\n if (first === undefined) fail('assertChained() needs at least one job.')\n const candidates = this.commands.filter((job) => sameJob(job, first as Target | Job))\n assert(candidates.length > 0, `The expected [${nameOf(first)}] job was not dispatched.`)\n const found = candidates.some((job) => {\n const chain = this.chains.get(job) ?? []\n return chain.length === rest.length && chain.every((link, index) => sameJob(link, rest[index] as Target | Job))\n })\n assert(found, `The expected chain [${expectedChain.map(nameOf).join(', ')}] was not dispatched.`)\n }\n\n assertDispatchedWithoutChain<J extends Job>(job: Target<J>, callback?: Filter<J>): void {\n const jobs = this.dispatched(job, callback)\n assert(jobs.length > 0, `The expected [${nameOf(job)}] job was not dispatched.`)\n assert(jobs.some((dispatched) => (this.chains.get(dispatched) ?? []).length === 0), `The expected [${nameOf(job)}] job was dispatched with a chain.`)\n }\n\n /** A batch was dispatched that passes the check. */\n assertBatched(callback: (batch: BatchRecord) => boolean): void {\n assert(this.batches.some(callback), 'The expected batch was not dispatched.')\n }\n\n assertBatchCount(count: number): void {\n assert(this.batches.length === count, `${this.batches.length} batches were dispatched instead of ${count}.`, { actual: this.batches.length, expected: count })\n }\n\n assertNothingBatched(): void {\n assert(this.batches.length === 0, 'Batched jobs were dispatched unexpectedly.')\n }\n\n dispatched<J extends Job>(job: Target<J>, callback?: Filter<J>): J[] {\n return filter(this.commands, job, callback)\n }\n\n dispatchedSync<J extends Job>(job: Target<J>, callback?: Filter<J>): J[] {\n return filter(this.commandsSync, job, callback)\n }\n\n dispatchedAfterResponse<J extends Job>(job: Target<J>, callback?: Filter<J>): J[] {\n return filter(this.commandsAfterResponse, job, callback)\n }\n\n hasDispatched<J extends Job>(job: Target<J>): boolean {\n return this.dispatched(job).length > 0\n }\n\n private shouldFake(job: Job): boolean {\n if (matchesAny(job, this.jobsToDispatch)) return false\n return this.jobsToFake.length === 0 || matchesAny(job, this.jobsToFake)\n }\n\n private real(): BusDispatcher {\n if (this.dispatcher === undefined) fail('Bus.fake() was given jobs to fake, but there is no real BusDispatcher for the others.')\n return this.dispatcher\n }\n}\n\nfunction filter<J>(jobs: Job[], target: Target<J>, callback?: Filter<J>): J[] {\n return (jobs.filter((job) => matchesAny(job, [target as Target])) as J[]).filter((job) => callback === undefined || callback(job))\n}\n","import { randomUUID } from 'node:crypto'\nimport { QueueManager, type Job, type Queue, type QueueJob, type QueuePayload } from '@orieljs/contracts'\nimport { assert, fail } from '../assert'\nimport { bound, install, matchesAny, nameOf, sameJob, type CountOrFilter, type Target } from './support'\n\n/** The Queue/Bus protocol key where Bus's PendingChain stores the rest of a chain on the first job. */\nconst CHAIN = Symbol.for('oriel:queue.chain')\n\n/** One push: the job (or raw payload), where it went, and when. */\nexport interface PushedJob {\n job: Job | QueuePayload\n raw: boolean\n connection: string | undefined\n queue: string | undefined\n delay: number | undefined\n}\n\ntype Filter<J> = (job: J, queue: string | undefined, connection: string | undefined) => boolean\n\n/**\n * Laravel's Queue::fake(): records push/later/pushRaw (on any connection) instead of queueing. Jobs that Bus\n * dispatches to a queue land here too, because Bus resolves QueueManager when it queues.\n */\nexport class QueueFake implements QueueManager {\n readonly jobs: PushedJob[] = []\n\n constructor(\n readonly manager: QueueManager | undefined,\n private readonly jobsToFake: Target[] = [],\n private jobsToPush: Target[] = [],\n ) {}\n\n static fake(jobsToFake: Target | Target[] = []): QueueFake {\n return install(QueueManager, new QueueFake(QueueFake.original(), [jobsToFake].flat()))\n }\n\n static fakeExcept(jobsToPush: Target | Target[]): QueueFake {\n return install(QueueManager, new QueueFake(QueueFake.original(), [], [jobsToPush].flat()))\n }\n\n private static original(): QueueManager | undefined {\n const current = bound(QueueManager)\n return current instanceof QueueFake ? current.manager : current\n }\n\n except(jobs: Target | Target[]): this {\n this.jobsToPush = [...this.jobsToPush, ...[jobs].flat()]\n return this\n }\n\n // QueueManager ---------------------------------------------------------------------------------------------\n\n /**\n * A recording view of the connection (pushes remember its name). Its size()/clear() only see the jobs pushed\n * through that connection name (no name: the jobs pushed without one, i.e. through the manager or connection()).\n */\n connection(name?: string): Queue {\n return {\n push: (job, queue) => this.record(name, job, queue, undefined),\n later: (delay, job, queue) => this.record(name, job, queue, delay),\n pushRaw: (payload, queue, delay) => this.recordRaw(name, payload, queue, delay),\n pop: (queue) => this.pop(queue),\n size: async (queue) => this.jobs.filter((pushed) => this.on(pushed, queue, { name })).length,\n clear: async (queue) => this.remove(queue, { name }),\n }\n }\n\n push(job: Job, queue?: string): Promise<string> {\n return this.record(undefined, job, queue, undefined)\n }\n\n later(delaySeconds: number, job: Job, queue?: string): Promise<string> {\n return this.record(undefined, job, queue, delaySeconds)\n }\n\n pushRaw(payload: QueuePayload, queue?: string, delaySeconds?: number): Promise<string> {\n return this.recordRaw(undefined, payload, queue, delaySeconds)\n }\n\n async pop(_queue?: string): Promise<QueueJob | undefined> {\n return undefined\n }\n\n /** Jobs on `queue` (every queue when omitted), whatever connection they were pushed on, like Laravel's fake. */\n async size(queue?: string): Promise<number> {\n return this.jobs.filter((pushed) => this.on(pushed, queue)).length\n }\n\n /** Removes the jobs size() counts and returns how many. */\n async clear(queue?: string): Promise<number> {\n return this.remove(queue)\n }\n\n extend(_driver: string, _factory: (config: Record<string, unknown>) => Queue): void {}\n\n // Assertions ---------------------------------------------------------------------------------------------\n\n /** Pushed at least once; a number asserts the count; a filter gets (job, queue, connection). */\n assertPushed<J extends Job>(job: Target<J>, callback?: CountOrFilter<[J, string | undefined, string | undefined]>): void {\n if (typeof callback === 'number') return this.assertPushedTimes(job, callback)\n assert(this.pushed(job, callback).length > 0, `The expected [${nameOf(job)}] job was not pushed.`)\n }\n\n assertPushedTimes<J extends Job>(job: Target<J>, times = 1): void {\n const count = this.pushed(job).length\n assert(count === times, `The expected [${nameOf(job)}] job was pushed ${count} times instead of ${times} times.`, { actual: count, expected: times })\n }\n\n assertPushedOn<J extends Job>(queue: string, job: Target<J>, callback?: Filter<J>): void {\n this.assertPushed(job, (pushed: J, on: string | undefined, connection: string | undefined) => on === queue && (callback === undefined || callback(pushed, on, connection)))\n }\n\n assertNotPushed<J extends Job>(job: Target<J>, callback?: Filter<J>): void {\n assert(this.pushed(job, callback).length === 0, `The unexpected [${nameOf(job)}] job was pushed.`)\n }\n\n assertNothingPushed(): void {\n const names = this.jobs.map((pushed) => this.nameOf(pushed))\n assert(names.length === 0, `The following jobs were pushed unexpectedly:\\n\\n- ${names.join('\\n- ')}`)\n }\n\n assertCount(expected: number): void {\n assert(this.jobs.length === expected, `Expected ${expected} jobs to be pushed, but found ${this.jobs.length} instead.`, { actual: this.jobs.length, expected })\n }\n\n /** The job was pushed with exactly this chain (Bus stores it on the first job under the protocol key). */\n assertPushedWithChain<J extends Job>(job: Target<J>, expectedChain: Array<Target | Job>, callback?: Filter<J>): void {\n const jobs = this.pushed(job, callback)\n assert(jobs.length > 0, `The expected [${nameOf(job)}] job was not pushed.`)\n const found = jobs.some((pushed) => {\n const chain = chainOf(pushed)\n return chain.length === expectedChain.length && chain.every((link, index) => sameJob(link, expectedChain[index] as Target | Job))\n })\n assert(found, `The expected chain was not pushed with [${nameOf(job)}].`)\n }\n\n assertPushedWithoutChain<J extends Job>(job: Target<J>, callback?: Filter<J>): void {\n const jobs = this.pushed(job, callback)\n assert(jobs.length > 0, `The expected [${nameOf(job)}] job was not pushed.`)\n assert(jobs.some((pushed) => chainOf(pushed).length === 0), `The expected [${nameOf(job)}] job was pushed with a chain.`)\n }\n\n /** Pushed jobs matching the target (raw payloads match by their registry name or display name). */\n pushed<J extends Job>(job: Target<J>, callback?: Filter<J>): J[] {\n return this.jobs\n .filter((pushed) => this.targets(pushed, job) && (callback === undefined || callback(pushed.job as J, pushed.queue, pushed.connection)))\n .map((pushed) => pushed.job as J)\n }\n\n hasPushed<J extends Job>(job: Target<J>): boolean {\n return this.pushed(job).length > 0\n }\n\n // Internals ----------------------------------------------------------------------------------------------\n\n private async record(connection: string | undefined, job: Job, queue: string | undefined, delay: number | undefined): Promise<string> {\n if (!this.shouldFake(job)) {\n const real = this.real().connection(connection)\n return delay === undefined ? real.push(job, queue) : real.later(delay, job, queue)\n }\n this.jobs.push({ job, raw: false, connection, queue, delay })\n return randomUUID()\n }\n\n private async recordRaw(connection: string | undefined, payload: QueuePayload, queue: string | undefined, delay: number | undefined): Promise<string> {\n this.jobs.push({ job: payload, raw: true, connection, queue, delay })\n return payload.uuid\n }\n\n /** The job is on `queue` (any when undefined) and, when `connection` is given, was pushed on that connection name. */\n private on(pushed: PushedJob, queue: string | undefined, connection?: { name: string | undefined }): boolean {\n return (queue === undefined || pushed.queue === queue) && (connection === undefined || pushed.connection === connection.name)\n }\n\n private remove(queue: string | undefined, connection?: { name: string | undefined }): number {\n const before = this.jobs.length\n const kept = this.jobs.filter((pushed) => !this.on(pushed, queue, connection))\n this.jobs.splice(0, this.jobs.length, ...kept)\n return before - kept.length\n }\n\n private targets(pushed: PushedJob, target: Target): boolean {\n if (!pushed.raw) return matchesAny(pushed.job, [target])\n const payload = pushed.job as QueuePayload\n const name = nameOf(target)\n return payload.job === name || payload.displayName === name\n }\n\n private nameOf(pushed: PushedJob): string {\n return pushed.raw ? (pushed.job as QueuePayload).displayName : nameOf(pushed.job)\n }\n\n private shouldFake(job: Job): boolean {\n if (matchesAny(job, this.jobsToPush)) return false\n return this.jobsToFake.length === 0 || matchesAny(job, this.jobsToFake)\n }\n\n private real(): QueueManager {\n if (this.manager === undefined) fail('Queue.fake() was given jobs to fake, but there is no real QueueManager for the others.')\n return this.manager\n }\n}\n\nfunction chainOf(job: Job): Job[] {\n const chain = (job as unknown as Record<symbol, { jobs?: Job[] } | undefined>)[CHAIN]\n return chain?.jobs ?? []\n}\n","import { MailManager, type Address, type Mailable, type Mailer, type MailRecipient, type MailTransport, type PendingMail, type SentMessage } from '@orieljs/contracts'\nimport { assert } from '../assert'\nimport { bound, install, isQueueable, matchesAny, nameOf, type CountOrFilter, type Target } from './support'\n\n/** A mailable the fake saw, with its resolved recipients (PendingMail's, else the envelope's) and subject. */\nexport class MailRecord<M extends Mailable = Mailable> {\n constructor(\n readonly mailable: M,\n readonly mailer: string | undefined,\n readonly to: Address[],\n readonly cc: Address[],\n readonly bcc: Address[],\n readonly subject: string | undefined,\n readonly queued: boolean,\n readonly delay: number | undefined,\n ) {}\n\n hasTo(address: MailRecipient): boolean {\n return includes(this.to, address)\n }\n\n hasCc(address: MailRecipient): boolean {\n return includes(this.cc, address)\n }\n\n hasBcc(address: MailRecipient): boolean {\n return includes(this.bcc, address)\n }\n\n hasSubject(subject: string): boolean {\n return this.subject === subject\n }\n}\n\ntype Filter<M extends Mailable> = (mailable: M, mail: MailRecord<M>) => boolean\ninterface Overrides {\n to: Address[]\n cc: Address[]\n bcc: Address[]\n}\n\n/**\n * Laravel's Mail::fake(): records what would have been sent or queued. Queueable mailables (the Queue/Bus\n * protocol's rule) sent with send() count as queued, like the real Mailer. Nothing is rendered or delivered.\n */\nexport class MailFake implements MailManager {\n readonly records: MailRecord[] = []\n\n constructor(readonly manager: MailManager | undefined = undefined) {}\n\n static fake(): MailFake {\n const current = bound(MailManager)\n return install(MailManager, new MailFake(current instanceof MailFake ? current.manager : current))\n }\n\n // MailManager ----------------------------------------------------------------------------------------------\n\n mailer(name?: string): Mailer {\n return {\n to: (recipients) => this.pending(name, recipients),\n send: (mailable) => this.sendVia(name, mailable, empty()),\n sendNow: (mailable) => this.sendNowVia(name, mailable, empty()),\n queue: (mailable) => this.queueVia(name, mailable, empty(), undefined),\n }\n }\n\n to(recipients: MailRecipient | MailRecipient[]): PendingMail {\n return this.pending(undefined, recipients)\n }\n\n send(mailable: Mailable): Promise<SentMessage | undefined> {\n return this.sendVia(undefined, mailable, empty())\n }\n\n /** Recorded as sent, never queued, like the real sendNow(). */\n sendNow(mailable: Mailable): Promise<SentMessage | undefined> {\n return this.sendNowVia(undefined, mailable, empty())\n }\n\n queue(mailable: Mailable): Promise<void> {\n return this.queueVia(undefined, mailable, empty(), undefined)\n }\n\n extend(_transport: string, _factory: (config: Record<string, unknown>) => MailTransport): void {}\n\n // Assertions ---------------------------------------------------------------------------------------------\n\n /** Sent (not queued) at least once; a number asserts the count; a filter gets (mailable, record). */\n assertSent<M extends Mailable>(mailable: Target<M>, callback?: CountOrFilter<[M, MailRecord<M>]>): void {\n if (typeof callback === 'number') return this.assertSentTimes(mailable, callback)\n const hint = this.queued(mailable).length > 0 ? '\\n\\nThe mailable was queued: did you mean assertQueued()?' : ''\n assert(this.sent(mailable, callback).length > 0, `The expected [${nameOf(mailable)}] mailable was not sent.${hint}`)\n }\n\n assertSentTimes<M extends Mailable>(mailable: Target<M>, times = 1): void {\n const count = this.sent(mailable).length\n assert(count === times, `The expected [${nameOf(mailable)}] mailable was sent ${count} times instead of ${times} times.`, { actual: count, expected: times })\n }\n\n assertNotSent<M extends Mailable>(mailable: Target<M>, callback?: Filter<M>): void {\n assert(this.sent(mailable, callback).length === 0, `The unexpected [${nameOf(mailable)}] mailable was sent.`)\n }\n\n assertNothingSent(): void {\n const names = this.records.filter((record) => !record.queued).map((record) => nameOf(record.mailable))\n assert(names.length === 0, `The following mailables were sent unexpectedly:\\n\\n- ${names.join('\\n- ')}`)\n }\n\n assertSentCount(count: number): void {\n const actual = this.records.filter((record) => !record.queued).length\n assert(actual === count, `The total number of mailables sent was ${actual} instead of ${count}.`, { actual, expected: count })\n }\n\n assertQueued<M extends Mailable>(mailable: Target<M>, callback?: CountOrFilter<[M, MailRecord<M>]>): void {\n if (typeof callback === 'number') {\n const count = this.queued(mailable).length\n assert(count === callback, `The expected [${nameOf(mailable)}] mailable was queued ${count} times instead of ${callback} times.`, { actual: count, expected: callback })\n return\n }\n assert(this.queued(mailable, callback).length > 0, `The expected [${nameOf(mailable)}] mailable was not queued.`)\n }\n\n assertNotQueued<M extends Mailable>(mailable: Target<M>, callback?: Filter<M>): void {\n assert(this.queued(mailable, callback).length === 0, `The unexpected [${nameOf(mailable)}] mailable was queued.`)\n }\n\n assertNothingQueued(): void {\n const names = this.records.filter((record) => record.queued).map((record) => nameOf(record.mailable))\n assert(names.length === 0, `The following mailables were queued unexpectedly:\\n\\n- ${names.join('\\n- ')}`)\n }\n\n assertQueuedCount(count: number): void {\n const actual = this.records.filter((record) => record.queued).length\n assert(actual === count, `The total number of mailables queued was ${actual} instead of ${count}.`, { actual, expected: count })\n }\n\n /** Sent or queued. */\n assertOutgoingCount(count: number): void {\n assert(this.records.length === count, `The total number of outgoing mailables was ${this.records.length} instead of ${count}.`, { actual: this.records.length, expected: count })\n }\n\n assertNothingOutgoing(): void {\n this.assertNothingSent()\n this.assertNothingQueued()\n }\n\n sent<M extends Mailable>(mailable: Target<M>, callback?: Filter<M>): M[] {\n return this.matching(mailable, false, callback)\n }\n\n queued<M extends Mailable>(mailable: Target<M>, callback?: Filter<M>): M[] {\n return this.matching(mailable, true, callback)\n }\n\n hasSent(mailable: Target<Mailable>): boolean {\n return this.sent(mailable).length > 0\n }\n\n hasQueued(mailable: Target<Mailable>): boolean {\n return this.queued(mailable).length > 0\n }\n\n // Internals ----------------------------------------------------------------------------------------------\n\n private pending(mailer: string | undefined, recipients: MailRecipient | MailRecipient[]): PendingMail {\n const overrides: Overrides = { to: addresses(recipients), cc: [], bcc: [] }\n const pending: PendingMail = {\n cc: (cc) => {\n overrides.cc.push(...addresses(cc))\n return pending\n },\n bcc: (bcc) => {\n overrides.bcc.push(...addresses(bcc))\n return pending\n },\n send: (mailable) => this.sendVia(mailer, mailable, overrides),\n sendNow: (mailable) => this.sendNowVia(mailer, mailable, overrides),\n queue: (mailable) => this.queueVia(mailer, mailable, overrides, undefined),\n later: (delay, mailable) => this.queueVia(mailer, mailable, overrides, delay),\n }\n return pending\n }\n\n private async sendVia(mailer: string | undefined, mailable: Mailable, overrides: Overrides): Promise<undefined> {\n await this.record(mailer, mailable, overrides, isQueueable(mailable), undefined)\n return undefined\n }\n\n private async sendNowVia(mailer: string | undefined, mailable: Mailable, overrides: Overrides): Promise<undefined> {\n await this.record(mailer, mailable, overrides, false, undefined)\n return undefined\n }\n\n private async queueVia(mailer: string | undefined, mailable: Mailable, overrides: Overrides, delay: number | undefined): Promise<void> {\n await this.record(mailer, mailable, overrides, true, delay)\n }\n\n private async record(mailer: string | undefined, mailable: Mailable, overrides: Overrides, queued: boolean, delay: number | undefined): Promise<void> {\n const envelope = await mailable.envelope()\n const to = overrides.to.length > 0 ? overrides.to : addresses(envelope.to ?? [])\n const cc = [...addresses(envelope.cc ?? []), ...overrides.cc]\n const bcc = [...addresses(envelope.bcc ?? []), ...overrides.bcc]\n this.records.push(new MailRecord(mailable, mailer, to, cc, bcc, envelope.subject, queued, delay))\n }\n\n private matching<M extends Mailable>(mailable: Target<M>, queued: boolean, callback?: Filter<M>): M[] {\n return (this.records as unknown as Array<MailRecord<M>>)\n .filter((record) => record.queued === queued && matchesAny(record.mailable, [mailable]) && (callback === undefined || callback(record.mailable, record)))\n .map((record) => record.mailable)\n }\n}\n\nfunction empty(): Overrides {\n return { to: [], cc: [], bcc: [] }\n}\n\n/** MailRecipient(s) → Address[] (strings, Address objects, or anything with email + name, such as a User model). */\nexport function addresses(recipients: MailRecipient | MailRecipient[]): Address[] {\n return [recipients].flat().map((recipient) => {\n if (typeof recipient === 'string') return { address: recipient }\n if ('address' in recipient) return recipient.name === undefined ? { address: recipient.address } : { address: recipient.address, name: recipient.name }\n return recipient.name === undefined ? { address: recipient.email } : { address: recipient.email, name: recipient.name }\n })\n}\n\nfunction includes(list: Address[], recipient: MailRecipient): boolean {\n const [wanted] = addresses(recipient)\n return list.some((address) => address.address === wanted!.address && (wanted!.name === undefined || address.name === wanted!.name))\n}\n","import { randomUUID } from 'node:crypto'\nimport { NotificationDispatcher, type Class, type Notifiable, type Notification, type NotificationChannel } from '@orieljs/contracts'\nimport { assert } from '../assert'\nimport { bound, install, matchesAny, nameOf, type CountOrFilter, type Target } from './support'\n\n/** One delivery the fake recorded: to whom, what, and on which channels (the notification's via()). */\nexport interface SentNotification {\n notifiable: Notifiable\n notification: Notification\n channels: string[]\n}\n\ntype Filter<N extends Notification> = (notification: N, channels: string[], notifiable: Notifiable) => boolean\n\n/** Notification.route('mail', 'a@b.c'): an on-demand notifiable (Laravel's AnonymousNotifiable). */\nexport class AnonymousNotifiable implements Notifiable {\n readonly routes = new Map<string, unknown>()\n\n constructor(private readonly dispatcher: NotificationDispatcher) {}\n\n route(channel: string, route: unknown): this {\n this.routes.set(channel, route)\n return this\n }\n\n routeNotificationFor(channel: string): unknown {\n return this.routes.get(channel)\n }\n\n notify(notification: Notification): Promise<void> {\n return this.dispatcher.send(this, notification)\n }\n}\n\n/**\n * 07's toNotifiableList() (Testing can't import Notifications): an array as is; one notifiable when it has\n * routeNotificationFor() (an iterable model is still one notifiable); else any iterable (a Collection, a Set).\n */\nfunction toNotifiableList(notifiables: Notifiable | Iterable<Notifiable>): Notifiable[] {\n if (Array.isArray(notifiables)) return notifiables as Notifiable[]\n if (typeof (notifiables as Partial<Notifiable>).routeNotificationFor === 'function') return [notifiables as Notifiable]\n if (typeof notifiables === 'object' && notifiables !== null && Symbol.iterator in notifiables) {\n return [...(notifiables as Iterable<Notifiable>)]\n }\n return [notifiables as Notifiable]\n}\n\n/** Models are the same notifiable when class and key match (Laravel keys its record by class and getKey()). */\nfunction sameNotifiable(a: Notifiable, b: Notifiable): boolean {\n if (a === b) return true\n const keyOf = (n: Notifiable) => {\n const model = n as Notifiable & { getKey?: () => unknown }\n return typeof model.getKey === 'function' ? model.getKey() : undefined\n }\n const key = keyOf(a)\n return key !== undefined && a.constructor === b.constructor && key === keyOf(b)\n}\n\n/**\n * Laravel's Notification::fake(): records notifications (send, sendNow, on-demand routes) instead of\n * delivering or queueing them. The Notifiable mixin's notify() resolves the dispatcher per call, so it lands here.\n */\nexport class NotificationFake implements NotificationDispatcher {\n readonly notifications: SentNotification[] = []\n\n constructor(readonly dispatcher: NotificationDispatcher | undefined = undefined) {}\n\n static fake(): NotificationFake {\n const current = bound(NotificationDispatcher)\n return install(NotificationDispatcher, new NotificationFake(current instanceof NotificationFake ? current.dispatcher : current))\n }\n\n // NotificationDispatcher -------------------------------------------------------------------------------------\n\n async send(notifiables: Notifiable | Iterable<Notifiable>, notification: Notification): Promise<void> {\n this.record(notifiables, notification)\n }\n\n async sendNow(notifiables: Notifiable | Iterable<Notifiable>, notification: Notification, channels?: string[]): Promise<void> {\n this.record(notifiables, notification, channels)\n }\n\n route(channel: string, route: unknown): AnonymousNotifiable {\n return new AnonymousNotifiable(this).route(channel, route)\n }\n\n /** The Notifications provider calls this in boot(); a fake has no channels to register. */\n extend(_channel: string, _factory: () => NotificationChannel): void {}\n\n // Assertions ---------------------------------------------------------------------------------------------\n\n /** Sent to the notifiable(s); a number asserts the count; a filter gets (notification, channels, notifiable). */\n assertSentTo<N extends Notification>(notifiable: Notifiable | Iterable<Notifiable>, notification: Target<N>, callback?: CountOrFilter<[N, string[], Notifiable]>): void {\n for (const one of toNotifiableList(notifiable)) {\n if (typeof callback === 'number') {\n this.assertSentToTimes(one, notification, callback)\n continue\n }\n assert(this.sent(one, notification, callback).length > 0, `The expected [${nameOf(notification)}] notification was not sent.`)\n }\n }\n\n assertSentToTimes<N extends Notification>(notifiable: Notifiable, notification: Target<N>, times = 1): void {\n const count = this.sent(notifiable, notification).length\n assert(count === times, `Expected [${nameOf(notification)}] to be sent ${times} times, but was sent ${count} times.`, { actual: count, expected: times })\n }\n\n assertNotSentTo<N extends Notification>(notifiable: Notifiable | Iterable<Notifiable>, notification: Target<N>, callback?: Filter<N>): void {\n for (const one of toNotifiableList(notifiable)) {\n assert(this.sent(one, notification, callback).length === 0, `The unexpected [${nameOf(notification)}] notification was sent.`)\n }\n }\n\n /** Sent through Notification.route(...) (an anonymous notifiable). */\n assertSentOnDemand<N extends Notification>(notification: Target<N>, callback?: CountOrFilter<[N, string[], AnonymousNotifiable]>): void {\n const matching = this.notifications.filter(\n (record) =>\n record.notifiable instanceof AnonymousNotifiable &&\n matchesAny(record.notification, [notification]) &&\n (typeof callback !== 'function' || callback(record.notification as N, record.channels, record.notifiable)),\n )\n if (typeof callback === 'number') {\n assert(matching.length === callback, `Expected [${nameOf(notification)}] to be sent on demand ${callback} times, but was sent ${matching.length} times.`)\n return\n }\n assert(matching.length > 0, `The expected [${nameOf(notification)}] notification was not sent on demand.`)\n }\n\n assertNothingSent(): void {\n const names = this.notifications.map((record) => nameOf(record.notification))\n assert(names.length === 0, `Notifications were sent unexpectedly:\\n\\n- ${names.join('\\n- ')}`)\n }\n\n assertNothingSentTo(notifiable: Notifiable): void {\n const count = this.notifications.filter((record) => sameNotifiable(record.notifiable, notifiable)).length\n assert(count === 0, 'Notifications were sent unexpectedly.')\n }\n\n /** Sent this many times in total, to anyone. */\n assertSentTimes(notification: Target<Notification>, times: number): void {\n const count = this.notifications.filter((record) => matchesAny(record.notification, [notification])).length\n assert(count === times, `Expected [${nameOf(notification)}] to be sent ${times} times, but was sent ${count} times.`, { actual: count, expected: times })\n }\n\n assertCount(expected: number): void {\n const actual = this.notifications.length\n assert(actual === expected, `Expected ${expected} notifications to be sent, but ${actual} were sent.`, { actual, expected })\n }\n\n sent<N extends Notification>(notifiable: Notifiable, notification: Target<N> | Class<N>, callback?: Filter<N>): N[] {\n return this.notifications\n .filter(\n (record) =>\n sameNotifiable(record.notifiable, notifiable) &&\n matchesAny(record.notification, [notification as Target]) &&\n (callback === undefined || callback(record.notification as N, record.channels, record.notifiable)),\n )\n .map((record) => record.notification as N)\n }\n\n hasSent(notifiable: Notifiable, notification: Target<Notification>): boolean {\n return this.sent(notifiable, notification).length > 0\n }\n\n private record(notifiables: Notifiable | Iterable<Notifiable>, notification: Notification, channels?: string[]): void {\n notification.id ??= randomUUID()\n for (const notifiable of toNotifiableList(notifiables)) {\n this.notifications.push({ notifiable, notification, channels: channels ?? notification.via(notifiable) })\n }\n }\n}\n","import { randomBytes } from 'node:crypto'\nimport { posix } from 'node:path'\nimport { ConfigRepository, FilesystemManager, type ErrorKind, type Filesystem, type OrielError, type PutOptions, type UploadedFile } from '@orieljs/contracts'\nimport { assert, fail } from '../assert'\nimport { bound, install } from './support'\n\n/**\n * The fake disk's failures, named and worded like Filesystem's PathTraversalError and FileNotFoundError (10).\n * Not an HTTP condition: kind 'Server', so the app reports them and renders a 500, as with a real disk.\n */\nclass FakeDiskError extends Error implements OrielError {\n readonly kind: ErrorKind = 'Server'\n readonly status = 500\n constructor(name: 'PathTraversalError' | 'FileNotFoundError', message: string, readonly path: string) {\n super(message)\n this.name = name\n }\n}\n\ninterface StoredFile {\n bytes: Uint8Array\n visibility: 'public' | 'private'\n mimeType: string | undefined\n modified: Date\n}\n\nconst MIME: Record<string, string> = {\n txt: 'text/plain', html: 'text/html', css: 'text/css', js: 'text/javascript', json: 'application/json', csv: 'text/csv',\n pdf: 'application/pdf', zip: 'application/zip', png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif',\n webp: 'image/webp', svg: 'image/svg+xml', mp3: 'audio/mpeg', mp4: 'video/mp4',\n}\n\n/** By the extension as PHP's pathinfo() reads it: after the last dot of the base name ('.pdf' is a PDF, 'pdf' isn't). */\nexport function guessMimeType(path: string): string | undefined {\n const base = path.slice(path.lastIndexOf('/') + 1)\n const dot = base.lastIndexOf('.')\n const extension = dot === -1 ? '' : base.slice(dot + 1).toLowerCase()\n return Object.hasOwn(MIME, extension) ? MIME[extension] : undefined\n}\n\n/**\n * The type a real disk gives an extension: a copy of Filesystem's table (its mimeFromExtension(); a test keeps the two\n * equal), so the fake disk's mimeType() answers as theirs do. guessMimeType() above stays FakeFile's smaller table.\n */\nconst DISK_TYPES: Record<string, string> = {\n txt: 'text/plain',\n html: 'text/html',\n htm: 'text/html',\n css: 'text/css',\n csv: 'text/csv',\n md: 'text/markdown',\n js: 'text/javascript',\n mjs: 'text/javascript',\n json: 'application/json',\n xml: 'application/xml',\n pdf: 'application/pdf',\n zip: 'application/zip',\n gz: 'application/gzip',\n tar: 'application/x-tar',\n '7z': 'application/x-7z-compressed',\n rar: 'application/vnd.rar',\n epub: 'application/epub+zip',\n rtf: 'application/rtf',\n doc: 'application/msword',\n docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',\n xls: 'application/vnd.ms-excel',\n xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',\n ppt: 'application/vnd.ms-powerpoint',\n pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',\n odt: 'application/vnd.oasis.opendocument.text',\n ods: 'application/vnd.oasis.opendocument.spreadsheet',\n odp: 'application/vnd.oasis.opendocument.presentation',\n png: 'image/png',\n jpg: 'image/jpeg',\n jpeg: 'image/jpeg',\n gif: 'image/gif',\n webp: 'image/webp',\n avif: 'image/avif',\n svg: 'image/svg+xml',\n ico: 'image/x-icon',\n bmp: 'image/bmp',\n tif: 'image/tiff',\n tiff: 'image/tiff',\n heic: 'image/heic',\n heif: 'image/heif',\n mp3: 'audio/mpeg',\n m4a: 'audio/mp4',\n wav: 'audio/wav',\n ogg: 'audio/ogg',\n oga: 'audio/ogg',\n opus: 'audio/ogg',\n flac: 'audio/flac',\n aac: 'audio/aac',\n mp4: 'video/mp4',\n mov: 'video/quicktime',\n webm: 'video/webm',\n ogv: 'video/ogg',\n avi: 'video/x-msvideo',\n woff: 'font/woff',\n woff2: 'font/woff2',\n ttf: 'font/ttf',\n otf: 'font/otf',\n wasm: 'application/wasm',\n}\n\nfunction diskType(extension: string): string | undefined {\n const key = extension.replace(/^\\./, '').toLowerCase()\n return Object.hasOwn(DISK_TYPES, key) ? DISK_TYPES[key] : undefined\n}\n\n/** Laravel's hashName(): 40 random alphanumerics plus the extension. */\nfunction hashName(file: UploadedFile): string {\n const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'\n const name = [...randomBytes(40)].map((byte) => alphabet[byte % alphabet.length]).join('')\n const extension = file.extension()\n return extension === '' ? name : `${name}.${extension}`\n}\n\n/** Disk-relative path without leading/trailing slashes; a `..` that would climb above the root is rejected. */\nfunction normalize(path: string): string {\n const parts: string[] = []\n for (const segment of path.replaceAll('\\\\', '/').split('/')) {\n if (segment === '' || segment === '.') continue\n if (segment !== '..') parts.push(segment)\n else if (parts.pop() === undefined) {\n throw new FakeDiskError('PathTraversalError', `Path traversal detected: \"${path}\" resolves outside the disk root.`, path)\n }\n }\n return parts.join('/')\n}\n\nconst within = (path: string, directory: string) => directory === '' || path.startsWith(`${directory}/`)\n\n/**\n * An in-memory disk implementing the Filesystem contract, with Laravel's fake-disk assertions. (Laravel's fake\n * writes to storage/framework/testing/disks; this one keeps files in memory, so there's nothing to clean up.)\n */\nexport class FakeDisk implements Filesystem {\n /** Stored files by normalized path. */\n readonly stored = new Map<string, StoredFile>()\n /** Directories made explicitly (others exist because files are in them). */\n readonly made = new Set<string>()\n\n constructor(readonly name: string, private readonly urlPrefix = `/storage`) {}\n\n async exists(path: string): Promise<boolean> {\n const key = normalize(path)\n return this.stored.has(key) || this.isDirectory(key)\n }\n\n async missing(path: string): Promise<boolean> {\n return !(await this.exists(path))\n }\n\n async get(path: string): Promise<string> {\n return new TextDecoder().decode(this.read(path).bytes)\n }\n\n async getBytes(path: string): Promise<Uint8Array> {\n return this.read(path).bytes.slice()\n }\n\n async readStream(path: string): Promise<ReadableStream<Uint8Array>> {\n const bytes = this.read(path).bytes.slice()\n return new ReadableStream({\n start(controller) {\n controller.enqueue(bytes)\n controller.close()\n },\n })\n }\n\n async put(path: string, contents: string | Uint8Array | ReadableStream<Uint8Array>, options: PutOptions = {}): Promise<boolean> {\n const key = normalize(path)\n const bytes = typeof contents === 'string' ? new TextEncoder().encode(contents) : contents instanceof Uint8Array ? contents.slice() : await collect(contents)\n this.write(key, bytes, options.mimeType ?? diskType(posix.extname(key)), options)\n return true\n }\n\n putFile(directory: string, file: UploadedFile, options: PutOptions = {}): Promise<string> {\n return this.putFileAs(directory, file, hashName(file), options)\n }\n\n /**\n * The upload's own type, as the S3 disk sends it: its extension(), never the MIME type the client sent as such nor\n * the stored name's type.\n */\n async putFileAs(directory: string, file: UploadedFile, name: string, options: PutOptions = {}): Promise<string> {\n const path = normalize(`${directory}/${name}`)\n this.write(path, new Uint8Array(await file.arrayBuffer()), options.mimeType ?? diskType(file.extension()), options)\n return path\n }\n\n private write(key: string, bytes: Uint8Array, mimeType: string | undefined, options: PutOptions): void {\n this.stored.set(key, { bytes, visibility: options.visibility ?? 'private', mimeType, modified: new Date() })\n }\n\n async delete(paths: string | string[]): Promise<boolean> {\n for (const path of [paths].flat()) this.stored.delete(normalize(path))\n return true\n }\n\n async copy(from: string, to: string): Promise<boolean> {\n const file = this.read(from)\n this.stored.set(normalize(to), { ...file, bytes: file.bytes.slice(), modified: new Date() })\n return true\n }\n\n async move(from: string, to: string): Promise<boolean> {\n await this.copy(from, to)\n this.stored.delete(normalize(from))\n return true\n }\n\n async size(path: string): Promise<number> {\n return this.read(path).bytes.byteLength\n }\n\n async lastModified(path: string): Promise<Date> {\n return this.read(path).modified\n }\n\n async mimeType(path: string): Promise<string | undefined> {\n return this.read(path).mimeType\n }\n\n url(path: string): string {\n return `${this.urlPrefix}/${normalize(path)}`\n }\n\n async temporaryUrl(path: string, expiresAt: Date): Promise<string> {\n return `${this.url(path)}?expiration=${Math.floor(expiresAt.getTime() / 1000)}`\n }\n\n async files(directory = '', recursive = false): Promise<string[]> {\n const dir = normalize(directory)\n return [...this.stored.keys()].filter((path) => within(path, dir) && (recursive || !path.slice(dir === '' ? 0 : dir.length + 1).includes('/'))).sort()\n }\n\n async directories(directory = '', recursive = false): Promise<string[]> {\n const dir = normalize(directory)\n const all = new Set<string>([...this.made])\n for (const path of this.stored.keys()) {\n const parts = path.split('/').slice(0, -1)\n for (let i = 1; i <= parts.length; i++) all.add(parts.slice(0, i).join('/'))\n }\n return [...all].filter((path) => within(path, dir) && path !== dir && (recursive || !path.slice(dir === '' ? 0 : dir.length + 1).includes('/'))).sort()\n }\n\n async makeDirectory(path: string): Promise<boolean> {\n this.made.add(normalize(path))\n return true\n }\n\n async deleteDirectory(path: string): Promise<boolean> {\n const dir = normalize(path)\n for (const file of [...this.stored.keys()]) if (within(file, dir)) this.stored.delete(file)\n for (const directory of [...this.made]) if (directory === dir || within(directory, dir)) this.made.delete(directory)\n return true\n }\n\n /** A virtual absolute path (the files only exist in memory). */\n path(path: string): string {\n return `/fake-disks/${this.name}/${normalize(path)}`\n }\n\n // Assertions (Laravel's FilesystemAdapter test helpers) -----------------------------------------------------\n\n /** The file(s) exist; with `content`, the (single) file has exactly that content. */\n async assertExists(path: string | string[], content?: string): Promise<this> {\n for (const one of [path].flat()) {\n assert(this.stored.has(normalize(one)), `Unable to find a file or directory at path [${one}].`)\n if (content !== undefined) {\n const actual = await this.get(one)\n assert(actual === content, `File or directory [${one}] was found, but content [${actual}] does not match [${content}].`, { actual, expected: content })\n }\n }\n return this\n }\n\n async assertMissing(path: string | string[]): Promise<this> {\n for (const one of [path].flat()) assert(!this.stored.has(normalize(one)), `Found unexpected file or directory at path [${one}].`)\n return this\n }\n\n async assertDirectoryEmpty(path: string): Promise<this> {\n const files = await this.files(path, true)\n assert(files.length === 0, `Directory [${path}] is not empty.`, { actual: files })\n return this\n }\n\n async assertCount(path: string, count: number, recursive = false): Promise<this> {\n const actual = (await this.files(path, recursive)).length\n assert(actual === count, `Expected [${count}] files at [${path}], but found [${actual}].`, { actual, expected: count })\n return this\n }\n\n private read(path: string): StoredFile {\n const file = this.stored.get(normalize(path))\n if (file === undefined) throw new FakeDiskError('FileNotFoundError', `File not found at path: ${path}`, path)\n return file\n }\n\n private isDirectory(key: string): boolean {\n return this.made.has(key) || [...this.stored.keys()].some((path) => key !== '' && path.startsWith(`${key}/`))\n }\n}\n\nasync function collect(stream: ReadableStream<Uint8Array>): Promise<Uint8Array> {\n const chunks: Uint8Array[] = []\n for await (const chunk of stream) chunks.push(chunk)\n const out = new Uint8Array(chunks.reduce((total, chunk) => total + chunk.byteLength, 0))\n let offset = 0\n for (const chunk of chunks) {\n out.set(chunk, offset)\n offset += chunk.byteLength\n }\n return out\n}\n\n/**\n * Laravel's Storage::fake('avatars'): swaps the FilesystemManager for one whose faked disks live in memory\n * (other disks still reach the real manager). Returns the fake disk.\n */\nexport class StorageFake implements FilesystemManager {\n readonly disks = new Map<string, FakeDisk>()\n\n constructor(readonly manager: FilesystemManager | undefined, private readonly defaultDisk: string) {}\n\n static fake(disk?: string): FakeDisk {\n const current = bound(FilesystemManager)\n const config = bound(ConfigRepository)\n const fake = current instanceof StorageFake ? current : install(FilesystemManager, new StorageFake(current, config?.get<string>('filesystems.default', 'local') ?? 'local'))\n const name = disk ?? fake.defaultDisk\n const faked = new FakeDisk(name)\n fake.disks.set(name, faked)\n return faked\n }\n\n disk(name?: string): Filesystem {\n const disk = name ?? this.defaultDisk\n const faked = this.disks.get(disk)\n if (faked !== undefined) return faked\n if (this.manager === undefined) fail(`Disk [${disk}] is not faked and there is no real FilesystemManager.`)\n return this.manager.disk(disk)\n }\n\n extend(driver: string, factory: (config: Record<string, unknown>) => Filesystem): void {\n this.manager?.extend(driver, factory)\n }\n\n exists(path: string) { return this.disk().exists(path) }\n missing(path: string) { return this.disk().missing(path) }\n get(path: string) { return this.disk().get(path) }\n getBytes(path: string) { return this.disk().getBytes(path) }\n readStream(path: string) { return this.disk().readStream(path) }\n put(path: string, contents: string | Uint8Array | ReadableStream<Uint8Array>, options?: PutOptions) { return this.disk().put(path, contents, options) }\n putFile(directory: string, file: UploadedFile, options?: PutOptions) { return this.disk().putFile(directory, file, options) }\n putFileAs(directory: string, file: UploadedFile, name: string, options?: PutOptions) { return this.disk().putFileAs(directory, file, name, options) }\n delete(paths: string | string[]) { return this.disk().delete(paths) }\n copy(from: string, to: string) { return this.disk().copy(from, to) }\n move(from: string, to: string) { return this.disk().move(from, to) }\n size(path: string) { return this.disk().size(path) }\n lastModified(path: string) { return this.disk().lastModified(path) }\n mimeType(path: string) { return this.disk().mimeType(path) }\n url(path: string) { return this.disk().url(path) }\n temporaryUrl(path: string, expiresAt: Date) { return this.disk().temporaryUrl(path, expiresAt) }\n files(directory?: string, recursive?: boolean) { return this.disk().files(directory, recursive) }\n directories(directory?: string, recursive?: boolean) { return this.disk().directories(directory, recursive) }\n makeDirectory(path: string) { return this.disk().makeDirectory(path) }\n deleteDirectory(path: string) { return this.disk().deleteDirectory(path) }\n path(path: string) { return this.disk().path(path) }\n}\n","import { deflateSync } from 'node:zlib'\nimport { guessMimeType } from './Fakes/StorageFake'\n\nconst ascii = (text: string): number[] => [...text].map((char) => char.charCodeAt(0))\nconst u16be = (n: number): number[] => [(n >>> 8) & 0xff, n & 0xff]\nconst u16le = (n: number): number[] => [n & 0xff, (n >>> 8) & 0xff]\nconst u32le = (n: number): number[] => [n & 0xff, (n >>> 8) & 0xff, (n >>> 16) & 0xff, (n >>> 24) & 0xff]\n\nfunction concat(...parts: ArrayLike<number>[]): Uint8Array {\n const out = new Uint8Array(parts.reduce((n, part) => n + part.length, 0))\n let offset = 0\n for (const part of parts) {\n out.set(part, offset)\n offset += part.length\n }\n return out\n}\n\n/** Packs values least significant bit first, as GIF's LZW codes and WebP's lossless bitstream are. */\nclass BitWriter {\n private readonly bytes: number[] = []\n private buffer = 0\n private count = 0\n\n write(value: number, bits: number): void {\n this.buffer |= value << this.count\n this.count += bits\n while (this.count >= 8) {\n this.bytes.push(this.buffer & 0xff)\n this.buffer >>>= 8\n this.count -= 8\n }\n }\n\n finish(): Uint8Array {\n if (this.count > 0) this.bytes.push(this.buffer & 0xff)\n return Uint8Array.from(this.bytes)\n }\n}\n\nconst CRC_TABLE = Array.from({ length: 256 }, (_, n) => {\n let c = n\n for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1\n return c >>> 0\n})\n\nfunction crc32(bytes: Uint8Array): number {\n let crc = 0xffffffff\n for (const byte of bytes) crc = CRC_TABLE[(crc ^ byte) & 0xff]! ^ (crc >>> 8)\n return (crc ^ 0xffffffff) >>> 0\n}\n\nfunction chunk(type: string, data: Uint8Array): Uint8Array {\n const out = new Uint8Array(12 + data.length)\n const view = new DataView(out.buffer)\n view.setUint32(0, data.length)\n out.set(new TextEncoder().encode(type), 4)\n out.set(data, 8)\n view.setUint32(8 + data.length, crc32(out.subarray(4, 8 + data.length)))\n return out\n}\n\n/** A white RGB PNG. */\nfunction png(width: number, height: number): Uint8Array {\n const header = new Uint8Array(13)\n const view = new DataView(header.buffer)\n view.setUint32(0, width)\n view.setUint32(4, height)\n header.set([8, 2, 0, 0, 0], 8) // 8-bit, truecolor, deflate, no filter, no interlace\n const rows = new Uint8Array((width * 3 + 1) * height).fill(255)\n for (let y = 0; y < height; y++) rows[y * (width * 3 + 1)] = 0 // filter byte per row\n return concat([137, 80, 78, 71, 13, 10, 26, 10], chunk('IHDR', header), chunk('IDAT', deflateSync(rows)), chunk('IEND', new Uint8Array()))\n}\n\n/** A Huffman table with a single one-bit code for symbol 0 (DHT). */\nconst oneCodeTable = (tableClass: number): number[] => [0xff, 0xc4, ...u16be(20), tableClass, 1, ...new Array<number>(15).fill(0), 0]\n\n/**\n * A baseline greyscale JPEG in mid-grey: every 8×8 block is a DC difference of 0 then end-of-block, two one-bit codes,\n * so the scan is a run of zero bits (the last byte padded with ones).\n */\nfunction jpeg(width: number, height: number): Uint8Array {\n const bits = Math.ceil(width / 8) * Math.ceil(height / 8) * 2\n const scan = new Uint8Array(Math.ceil(bits / 8))\n const padding = scan.length * 8 - bits\n if (padding > 0) scan[scan.length - 1] = (1 << padding) - 1\n return concat(\n [0xff, 0xd8], // SOI\n [0xff, 0xe0, ...u16be(16), ...ascii('JFIF'), 0, 1, 1, 0, 0, 1, 0, 1, 0, 0], // APP0\n [0xff, 0xdb, ...u16be(67), 0, ...new Array<number>(64).fill(1)], // DQT: table 0, all ones\n [0xff, 0xc0, ...u16be(11), 8, ...u16be(height), ...u16be(width), 1, 1, 0x11, 0], // SOF0: one component\n oneCodeTable(0x00), // DHT: DC table 0\n oneCodeTable(0x10), // DHT: AC table 0\n [0xff, 0xda, ...u16be(8), 1, 1, 0x00, 0, 63, 0], // SOS\n scan,\n [0xff, 0xd9], // EOI\n )\n}\n\n/** GIF's LZW for `pixels` pixels of colour 0, the way common encoders write it (a clear code when the table is full). */\nfunction lzwZeros(pixels: number, minCodeSize: number): Uint8Array {\n const clear = 1 << minCodeSize\n const end = clear + 1\n const out = new BitWriter()\n const table = new Map<number, number>()\n let codeSize = minCodeSize + 1\n let next = end + 1\n let current = 0\n out.write(clear, codeSize)\n for (let i = 1; i < pixels; i++) {\n const key = current << 8 // the current string plus one more pixel of colour 0\n const known = table.get(key)\n if (known !== undefined) {\n current = known\n continue\n }\n out.write(current, codeSize)\n if (next === 4096) {\n out.write(clear, codeSize)\n table.clear()\n codeSize = minCodeSize + 1\n next = end + 1\n } else {\n if (next >= 1 << codeSize) codeSize++\n table.set(key, next++)\n }\n current = 0\n }\n out.write(current, codeSize)\n out.write(end, codeSize)\n return out.finish()\n}\n\n/** A white GIF89a: a two-colour palette and every pixel colour 0. */\nfunction gif(width: number, height: number): Uint8Array {\n const data = lzwZeros(width * height, 2)\n const blocks: number[] = []\n for (let offset = 0; offset < data.length; offset += 255) {\n const block = data.subarray(offset, offset + 255)\n blocks.push(block.length, ...block)\n }\n return concat(\n ascii('GIF89a'),\n [...u16le(width), ...u16le(height), 0x80, 0, 0], // a global palette of two colours\n [0xff, 0xff, 0xff, 0, 0, 0],\n [0x2c, 0, 0, 0, 0, ...u16le(width), ...u16le(height), 0], // the image descriptor\n [2],\n blocks,\n [0, 0x3b], // the end of the data, the trailer\n )\n}\n\n/** A white lossless WebP (VP8L): five one-symbol prefix codes, so the pixels themselves take no bits. */\nfunction webp(width: number, height: number): Uint8Array {\n const bits = new BitWriter()\n bits.write(0x2f, 8)\n bits.write(width - 1, 14)\n bits.write(height - 1, 14)\n bits.write(0, 4) // no alpha hint, version 0\n bits.write(0, 3) // no transform, no colour cache, one prefix code group\n for (const symbol of [255, 255, 255, 255, 0]) {\n // green, red, blue, alpha, distance: a simple code with one 8-bit symbol\n bits.write(1, 1)\n bits.write(0, 1)\n bits.write(1, 1)\n bits.write(symbol, 8)\n }\n const data = bits.finish()\n const padded = data.length % 2 === 0 ? data : concat(data, [0])\n return concat(ascii('RIFF'), u32le(12 + padded.length), ascii('WEBP'), ascii('VP8L'), u32le(data.length), padded)\n}\n\n/** A white 24-bit BMP: bottom-up rows, each padded to four bytes. */\nfunction bmp(width: number, height: number): Uint8Array {\n const row = Math.ceil((width * 3) / 4) * 4\n const out = new Uint8Array(54 + row * height)\n const view = new DataView(out.buffer)\n out.set(ascii('BM'))\n view.setUint32(2, out.length, true)\n view.setUint32(10, 54, true)\n view.setUint32(14, 40, true)\n view.setInt32(18, width, true)\n view.setInt32(22, height, true)\n view.setUint16(26, 1, true)\n view.setUint16(28, 24, true)\n view.setUint32(34, row * height, true)\n for (let y = 0; y < height; y++) out.fill(0xff, 54 + y * row, 54 + y * row + width * 3)\n return out\n}\n\n/** image()'s formats by extension; any other extension gets a JPEG, as Laravel's fakes do. */\nconst IMAGE_FORMATS: Record<string, { type: string; encode: (width: number, height: number) => Uint8Array }> = {\n png: { type: 'image/png', encode: png },\n jpg: { type: 'image/jpeg', encode: jpeg },\n jpeg: { type: 'image/jpeg', encode: jpeg },\n gif: { type: 'image/gif', encode: gif },\n webp: { type: 'image/webp', encode: webp },\n bmp: { type: 'image/bmp', encode: bmp },\n}\n\nconst extensionOf = (name: string): string => (name.includes('.') ? name.slice(name.lastIndexOf('.') + 1).toLowerCase() : '')\n\n/** The types guessMimeType() doesn't name that validation reads by their bytes or as text, so create() can start like them. */\nconst MORE_MIME_TYPES: Record<string, string> = {\n bmp: 'image/bmp',\n avif: 'image/avif',\n xml: 'text/xml',\n htm: 'text/html',\n md: 'text/markdown',\n tsv: 'text/tab-separated-values',\n text: 'text/plain',\n}\n\n/** How create()'s files start for the types validation recognises by their bytes; the rest of the file is padding. */\nconst LEADING_BYTES: Record<string, { bytes: string | number[]; text?: boolean }> = {\n 'image/jpeg': { bytes: [0xff, 0xd8, 0xff, 0xe0, ...u16be(16), ...ascii('JFIF'), 0, 1, 1, 0, 0, 1, 0, 1, 0, 0] },\n 'image/png': { bytes: [137, 80, 78, 71, 13, 10, 26, 10] },\n 'image/gif': { bytes: 'GIF89a' },\n 'image/webp': { bytes: 'RIFF\\0\\0\\0\\0WEBP' },\n 'image/avif': { bytes: [0, 0, 0, 0x14, ...ascii('ftypavif'), 0, 0, 0, 0, ...ascii('avifmif1')] },\n 'image/bmp': { bytes: [...ascii('BM'), 0, 0, 0, 0, 0, 0, 0, 0, 54, 0, 0, 0, 40, 0, 0, 0] },\n 'application/pdf': { bytes: '%PDF-1.4\\n' },\n 'image/svg+xml': { bytes: '<svg xmlns=\"http://www.w3.org/2000/svg\"/>\\n', text: true },\n 'text/html': { bytes: '<!doctype html>\\n', text: true },\n 'text/xml': { bytes: '<?xml version=\"1.0\"?>\\n', text: true },\n}\n\n/**\n * A file of `size` bytes that starts like `type`: text types are padded with spaces, everything else with zeros. It is\n * never empty (an empty file fails mimes), so a type with no leading bytes gets at least one zero byte.\n */\nfunction contentFor(type: string, size: number): Uint8Array {\n const text = type.startsWith('text/') || type === 'application/json'\n const leading = LEADING_BYTES[type] ?? { bytes: text ? '\\n' : [], text }\n const head = typeof leading.bytes === 'string' ? new TextEncoder().encode(leading.bytes) : Uint8Array.from(leading.bytes)\n const out = new Uint8Array(Math.max(size, head.length, 1)).fill(leading.text ? 0x20 : 0)\n out.set(head)\n return out\n}\n\n/** Laravel's UploadedFile::fake(): File objects to post as multipart uploads (t.post(uri, { avatar: file })). */\nexport const FakeFile = {\n /**\n * A file of `kilobytes` KiB typed by `mimeType` or the name's extension. Validation reads a file's bytes, so the\n * file starts like its type (a PDF's `%PDF-`, a PNG's signature, text for text types) and passes `mimes` for its\n * name, as Laravel's fakes do. It is at least its type's leading bytes and never empty, whatever the size asked for.\n * An image made this way has no readable size: use image() for `dimensions`.\n */\n create(name: string, kilobytes = 0, mimeType?: string): File {\n const type = mimeType ?? guessMimeType(name) ?? MORE_MIME_TYPES[extensionOf(name)] ?? 'application/octet-stream'\n return new File([contentFor(type, Math.round(kilobytes * 1024)) as Uint8Array<ArrayBuffer>], name, { type })\n },\n\n /**\n * A real white image of the given size in the format the name's extension asks for: png, jpg/jpeg, gif, webp or\n * bmp (any other name gets a JPEG, as Laravel's fakes do), so image, mimes and dimensions pass on it.\n */\n image(name: string, width = 10, height = 10): File {\n const format = IMAGE_FORMATS[extensionOf(name)] ?? IMAGE_FORMATS.jpeg!\n return new File([format.encode(width, height) as Uint8Array<ArrayBuffer>], name, { type: guessMimeType(name) ?? format.type })\n },\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AGAA,SAAS,YAAY,oBAAoB;AACzC,SAAS,YAAY;AACrB,SAAS,aAAa;ACFtB,SAAS,cAAAA,aAAY,mBAAmB;AACxC,SAAS,QAAAC,aAAY;AACrB,SAAS,qBAAqB;AJE9B,IAAM,OAAO,CAAC,UAA4B,UAAU,OAAO,SAAS,MAAM,QAAQ,KAAK,IAAI,UAAU,OAAO;AAE5G,IAAM,gBAAgB,CA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,EAAE,OAAO,QAAQ,KAAK,IAAI,WAAW,KAAK,QAAQ,KAAK;AACxH,QAAM,MAAM,IAAI,WAAW,KAAK,IAAI,MAAM,KAAK,QAAQ,CAAC,CAAC,EAAE,KAAK,QAAQ,OAAO,KAAO,CAAC;AACvF,MAAI,IAAI,IAAI;AACZ,SAAO;AACT;AAGO,IAAM,WAAW;;;;;;;EAOtB,OAAO,MAAc,YAAY,GAAG,UAAyB;AAC3D,UAAM,OAAO,YAAY,cAAc,IAAI,KAAK,gBAAgB,YAAY,IAAI,CAAC,KAAK;AACtF,WAAO,IAAI,KAAK,CAAC,WAAW,MAAM,KAAK,MAAM,YAAY,IAAI,CAAC,CAA4B,GAAG,MAAM,EAAE,KAAK,CAAC;EAC7G;;;;;EAMA,MAAM,MAAc,QAAQ,IAAI,SAAS,IAAU;AACjD,UAAMW,UAAS,cAAc,YAAY,IAAI,CAAC,KAAK,cAAc;AACjE,WAAO,IAAI,KAAK,CAACA,QAAO,OAAO,OAAO,MAAM,CAA4B,GAAG,MAAM,EAAE,MAAM,cAAc,IAAI,KAAKA,QAAO,KAAK,CAAC;EAC/H;AACF;","names":["existsSync","join","key","join","join","existsSync","readFileSync","join","join","key","existsSync","readFileSync","chunk","url","ConfigRepository","attributes","container","Application","ApplicationToken","ClassRegistry","request","resolve","createReadStream","stat","Readable","existsSync","readFile","existsSync","readFileSync","join","statSync","createServer","response","chunk","container","key","url","request","inject","isPlainObject","matches","Str","token","Session","currentContainer","HttpRequest","UrlGenerator","route","CurrentRoute","ConfigRepository","Router","kind","Redirector","redirect","target","ViewFactory","stat","Readable","createReadStream","resolve","env","parseEnv","join","existsSync","readFileSync","statSync","createServer","readFile","HttpKernel","ExceptionHandler","ResponseFactory","AsyncLocalStorage","randomBytes","existsSync","readdirSync","join","relative","sep","pathToFileURL","existsSync","mkdir","writeFile","dirname","join","relative","sep","key","empty","methods","isPlainObject","Collection","url","UrlGenerator","escapeAttribute","fail","token","inject","Str","request","ValidationFactory","ConfigRepository","target","requestScope","container","currentContainer","LiveManager","redirect","existsSync","readdirSync","sep","pathToFileURL","join","relative","route","expand","values","original","response","AsyncLocalStorage","isRecord","hook","randomBytes","Session","CurrentRoute","ViewFactory","Encrypter","node","dirname","mkdir","writeFile","Router","HttpRequest","live","AssertionError","isDeepStrictEqual","existsSync","join","createHmac","randomUUID","randomUUID","randomBytes","target","fail","AssertionError","escapeHtml","stripTags","isDeepStrictEqual","key","ConsoleKernel","env","clonePlain","size","response","ConfigRepository","existsSync","join","Arr","createHmac","format","url","request","setClientAddress","Encrypter","Application","DatabaseManager","token","AuthFactory","install","container","chainOf","randomUUID","route","randomBytes","chunk"]}
|