@orieljs/framework 0.1.0-alpha.0 → 0.1.0-alpha.1
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/LICENSE +202 -21
- package/NOTICE +9 -0
- package/README.md +4 -0
- package/dist/chunk-AI2RFMBT.js +745 -0
- package/dist/chunk-AI2RFMBT.js.map +1 -0
- package/dist/chunk-BZPCRKFQ.js +2941 -0
- package/dist/chunk-BZPCRKFQ.js.map +1 -0
- package/dist/{chunk-P64C7IEP.js → chunk-K6MAA3RM.js} +5 -1
- package/dist/chunk-K6MAA3RM.js.map +1 -0
- package/dist/chunk-WI7E7Q46.js +474 -0
- package/dist/chunk-WI7E7Q46.js.map +1 -0
- package/dist/contracts.d.ts +138 -43
- package/dist/contracts.js +5 -1
- package/dist/index.d.ts +11303 -325
- package/dist/index.js +20596 -864
- package/dist/index.js.map +1 -1
- package/dist/jsx-runtime-B8J6xq-7.d.ts +350 -0
- package/dist/jsx-runtime.d.ts +1 -0
- package/dist/jsx-runtime.js +13 -0
- package/dist/jsx-runtime.js.map +1 -0
- package/dist/testing.d.ts +1408 -0
- package/dist/testing.js +89 -0
- package/dist/testing.js.map +1 -0
- package/package.json +63 -10
- package/dist/chunk-P64C7IEP.js.map +0 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../Container/Container.ts","../../Container/context.ts","../../Container/describe.ts","../../Container/errors.ts","../../Collections/compare.ts","../../Collections/Collection.ts","../../Collections/LazyCollection.ts","../../Support/Str.ts","../../Support/Arr.ts","../../Support/ServiceProvider.ts","../../Support/Facade.ts","../../Support/ClassRegistry.ts","../../Support/helpers.ts","../../Config/Repository.ts","../../Config/env.ts","../../Config/LoadEnvironment.ts","../../Config/LoadConfiguration.ts","../../Foundation/Application.ts","../../Foundation/ApplicationBuilder.ts","../../Foundation/errors.ts","../../Foundation/Http/ClosureKernel.ts"],"sourcesContent":["import { Container as ContainerToken, type Abstract, type Concrete, type Container as ContainerContract, type Factory } from '@orieljs/contracts'\nimport { building, GLOBAL_KEY, storage } from './context'\nimport { describe } from './describe'\nimport { BindingResolutionError, CircularDependencyError } from './errors'\n\ntype Key = unknown\ntype Lifetime = 'transient' | 'singleton' | 'scoped'\ninterface Binding { lifetime: Lifetime; factory: Factory<unknown> }\ntype Extender = (instance: unknown, c: ContainerContract) => unknown\ntype Callback = (instance: unknown, c: ContainerContract) => void\n\ninterface SharedState {\n bindings: Map<Key, Binding>\n extenders: Map<Key, Extender[]>\n resolving: Map<Key, Callback[]>\n resolved: Set<Key>\n}\n\nconst globals = globalThis as unknown as Record<symbol, Container | undefined>\n\nconst keyOf = (abstract: Abstract<unknown>): Key => (typeof abstract === 'function' ? abstract : abstract.id)\nconst isClass = (fn: unknown): fn is new () => unknown =>\n typeof fn === 'function' && /^class[\\s{]/.test(Function.prototype.toString.call(fn))\n\nexport class Container implements ContainerContract {\n static getInstance(): Container | undefined {\n return globals[GLOBAL_KEY]\n }\n static setInstance(container: Container | undefined): void {\n globals[GLOBAL_KEY] = container\n }\n\n protected readonly shared: SharedState\n protected readonly root: Container\n protected readonly parent: Container | undefined\n protected readonly local = new Map<Key, unknown>()\n\n constructor(parent?: Container) {\n this.parent = parent\n this.root = parent?.root ?? this\n this.shared = parent?.shared ?? { bindings: new Map(), extenders: new Map(), resolving: new Map(), resolved: new Set() }\n // Every container (root or scope) resolves \"the container\" as itself, by token and by class.\n this.local.set(keyOf(ContainerToken), this)\n this.local.set(Container, this)\n }\n\n bind<T>(abstract: Abstract<T>, concrete?: Concrete<T>): void {\n this.#assertRoot('bind')\n this.#addBinding(abstract, concrete, 'transient')\n }\n singleton<T>(abstract: Abstract<T>, concrete?: Concrete<T>): void {\n this.#assertRoot('singleton')\n this.#addBinding(abstract, concrete, 'singleton')\n }\n scoped<T>(abstract: Abstract<T>, concrete?: Concrete<T>): void {\n this.#assertRoot('scoped')\n this.#addBinding(abstract, concrete, 'scoped')\n }\n\n instance<T>(abstract: Abstract<T>, instance: T): T {\n const key = keyOf(abstract)\n this.local.set(key, instance)\n // A scope's instances are its own business: only the root records them in the shared resolved set.\n if (this === this.root) this.shared.resolved.add(key)\n return instance\n }\n\n make<T>(abstract: Abstract<T>): T {\n const key = keyOf(abstract)\n const owner = this.#owning(key)\n if (owner) return owner.local.get(key) as T\n\n const binding = this.shared.bindings.get(key) ?? this.#implicitBinding(abstract)\n if (binding.lifetime === 'scoped' && this === this.root) {\n throw new BindingResolutionError(\n `Scoped binding [${describe(abstract)}] was resolved outside a scope. Resolve it inside app.createScope().run(...), and don't inject scoped services into singletons.`,\n )\n }\n const builder = binding.lifetime === 'singleton' ? this.root : this\n const instance = builder.build(abstract, key, binding)\n\n if (binding.lifetime === 'singleton') this.root.local.set(key, instance)\n if (binding.lifetime === 'scoped') this.local.set(key, instance)\n return instance as T\n }\n\n bound(abstract: Abstract<unknown>): boolean {\n const key = keyOf(abstract)\n return this.shared.bindings.has(key) || this.#owning(key) !== undefined\n }\n\n resolved(abstract: Abstract<unknown>): boolean {\n const key = keyOf(abstract)\n return this.shared.resolved.has(key) || this.#owning(key) !== undefined\n }\n\n extend<T>(abstract: Abstract<T>, extender: (instance: T, container: ContainerContract) => T): void {\n this.#assertRoot('extend')\n const key = keyOf(abstract)\n const list = this.shared.extenders.get(key) ?? []\n list.push(extender as Extender)\n this.shared.extenders.set(key, list)\n if (this.local.has(key)) this.local.set(key, extender(this.local.get(key) as T, this))\n }\n\n resolving<T>(abstract: Abstract<T>, callback: (instance: T, container: ContainerContract) => void): void {\n this.#assertRoot('resolving')\n const key = keyOf(abstract)\n const list = this.shared.resolving.get(key) ?? []\n list.push(callback as Callback)\n this.shared.resolving.set(key, list)\n }\n\n forgetInstance(abstract: Abstract<unknown>): void {\n this.local.delete(keyOf(abstract))\n }\n\n /** Scopes are always plain Containers (never subclasses such as Application). */\n createScope(): Container {\n return new Container(this)\n }\n\n run<R>(fn: () => R): R {\n return storage.run(this, fn)\n }\n\n /** The nearest container in this -> parent scopes -> root that holds an instance for the key. */\n #owning(key: Key): Container | undefined {\n if (this.local.has(key)) return this\n return this.parent === undefined ? undefined : this.parent.#owning(key)\n }\n\n /** Bindings, extenders and callbacks are app-wide state: a request scope must never write them. */\n #assertRoot(method: string): void {\n if (this !== this.root) {\n throw new Error(\n `Cannot register bindings on a request scope (${method}). Register them on the application in a service provider; use instance() for per-request values.`,\n )\n }\n }\n\n #addBinding(abstract: Abstract<unknown>, concrete: Concrete<unknown> | undefined, lifetime: Lifetime): void {\n const key = keyOf(abstract)\n let factory: Factory<unknown>\n if (concrete === undefined) {\n if (typeof abstract !== 'function') throw new TypeError(`bind(${describe(abstract)}) needs a concrete: tokens can't be constructed`)\n factory = () => new (abstract as new () => unknown)()\n } else if (isClass(concrete)) {\n factory = () => new concrete()\n } else {\n factory = concrete as Factory<unknown>\n }\n this.shared.bindings.set(key, { lifetime, factory })\n this.local.delete(key)\n }\n\n #implicitBinding(abstract: Abstract<unknown>): Binding {\n if (typeof abstract === 'function') {\n return { lifetime: 'transient', factory: () => new (abstract as new () => unknown)() }\n }\n throw new BindingResolutionError(\n `Target [${abstract.description}] is not bound. Is its service provider registered in bootstrap/providers.ts?`,\n )\n }\n\n protected build(abstract: Abstract<unknown>, key: Key, binding: Binding): unknown {\n const stackIndex = building.keys.indexOf(key)\n if (stackIndex !== -1) {\n const chain = [...building.names.slice(stackIndex), describe(abstract)]\n throw new CircularDependencyError(chain)\n }\n building.keys.push(key)\n building.names.push(describe(abstract))\n building.containers.push(this)\n try {\n let instance = binding.factory(this)\n for (const extender of this.shared.extenders.get(key) ?? []) instance = extender(instance, this)\n for (const callback of this.shared.resolving.get(key) ?? []) callback(instance, this)\n this.shared.resolved.add(key)\n return instance\n } finally {\n building.keys.pop()\n building.names.pop()\n building.containers.pop()\n }\n }\n}\n","import { AsyncLocalStorage } from 'node:async_hooks'\nimport type { Abstract, Container } from '@orieljs/contracts'\nimport { describe } from './describe'\nimport { ContainerNotAvailableError } from './errors'\n\nconst ALS_KEY = Symbol.for('oriel:container.als')\nexport const GLOBAL_KEY = Symbol.for('oriel:container.instance')\nconst BUILDING_KEY = Symbol.for('oriel:container.building')\nconst g = globalThis as unknown as Record<symbol, unknown>\n\n/** One AsyncLocalStorage per process, even if @orieljs/container is installed twice. */\nexport const storage: AsyncLocalStorage<Container> = (g[ALS_KEY] ??= new AsyncLocalStorage<Container>()) as AsyncLocalStorage<Container>\n\n/** Synchronous build stack. Shared through globalThis so duplicate package copies share the same stack. */\nexport const building = (g[BUILDING_KEY] ??= {\n keys: [] as unknown[],\n names: [] as string[],\n containers: [] as Container[],\n}) as { keys: unknown[]; names: string[]; containers: Container[] }\n\nexport function currentContainer(): Container | undefined {\n return building.containers.at(-1) ?? storage.getStore() ?? (g[GLOBAL_KEY] as Container | undefined)\n}\n\nexport function inject<T>(abstract: Abstract<T>): T {\n const container = currentContainer()\n if (!container) throw new ContainerNotAvailableError(describe(abstract))\n return container.make(abstract)\n}\n","import type { Abstract } from '@orieljs/contracts'\n\nexport function describe(abstract: Abstract<unknown>): string {\n return typeof abstract === 'function' ? abstract.name || '<anonymous class>' : abstract.description\n}\n","import type { OrielError } from '@orieljs/contracts'\n\nexport class BindingResolutionError extends Error implements OrielError {\n readonly kind = 'BindingResolution' as const\n override readonly name = 'BindingResolutionError'\n}\n\nexport class CircularDependencyError extends Error implements OrielError {\n readonly kind = 'CircularDependency' as const\n override readonly name = 'CircularDependencyError'\n constructor(readonly chain: string[]) {\n super(`Circular dependency detected: ${chain.join(' -> ')}`)\n }\n}\n\nexport class ContainerNotAvailableError extends Error implements OrielError {\n readonly kind = 'ContainerNotAvailable' as const\n override readonly name = 'ContainerNotAvailableError'\n constructor(what: string) {\n super(\n `Cannot resolve [${what}]: no container is available. inject(), helpers and facades only work while the ` +\n `application is running (inside a request, job, command, provider or app.run()). ` +\n `Don't call them at module top level.`,\n )\n }\n}\n","export type Operator = '=' | '==' | '===' | '!=' | '!==' | '<>' | '<' | '<=' | '>' | '>='\n\nexport function compare(left: unknown, operator: Operator, right: unknown): boolean {\n switch (operator) {\n case '=':\n case '==':\n return left == right\n case '===':\n return left === right\n case '!=':\n case '<>':\n return left != right\n case '!==':\n return left !== right\n case '<':\n return (left as number) < (right as number)\n case '<=':\n return (left as number) <= (right as number)\n case '>':\n return (left as number) > (right as number)\n case '>=':\n return (left as number) >= (right as number)\n }\n}\n\n/** Ascending comparator: null/undefined last; numbers numerically; everything else by localeCompare. */\nexport function ascending(a: unknown, b: unknown): number {\n const aNil = a === null || a === undefined\n const bNil = b === null || b === undefined\n if (aNil || bNil) return aNil === bNil ? 0 : aNil ? 1 : -1\n if (typeof a === 'number' && typeof b === 'number') return a - b\n if (a instanceof Date && b instanceof Date) return a.getTime() - b.getTime()\n return String(a).localeCompare(String(b))\n}\n","import type { Arrayable, Enumerable } from '@orieljs/contracts'\nimport { ascending, compare, type Operator } from './compare'\n\ntype Getter<T, V = unknown> = (keyof T & string) | ((item: T) => V)\n\nconst read = <T>(item: T, getter: Getter<T>): unknown =>\n typeof getter === 'function' ? getter(item) : (item as Record<string, unknown> | null | undefined)?.[getter]\n\nconst isArrayable = (v: unknown): v is Arrayable =>\n typeof v === 'object' && v !== null && typeof (v as Arrayable).toArray === 'function'\n\nconst numbers = <T>(items: T[], getter?: Getter<T>): number[] =>\n items\n .map((item) => (getter === undefined ? item : read(item, getter)))\n .filter((v): v is number => typeof v === 'number' && !Number.isNaN(v))\n\nexport class Collection<T> implements Enumerable<T> {\n protected readonly items: T[]\n\n constructor(items: Iterable<T> = []) {\n this.items = [...items]\n }\n\n static make<T>(items: Iterable<T> = []): Collection<T> {\n return new Collection(items)\n }\n\n /** Laravel semantics: callback receives 1..n. */\n static times<T>(count: number, callback: (index: number) => T): Collection<T> {\n return new Collection(Array.from({ length: Math.max(0, count) }, (_, i) => callback(i + 1)))\n }\n\n [Symbol.iterator](): Iterator<T> {\n return this.items[Symbol.iterator]()\n }\n\n all(): T[] { return [...this.items] }\n count(): number { return this.items.length }\n isEmpty(): boolean { return this.items.length === 0 }\n isNotEmpty(): boolean { return this.items.length > 0 }\n toArray(): unknown[] { return this.items.map((i) => (isArrayable(i) ? i.toArray() : i)) }\n toJSON(): T[] { return this.all() }\n toJson(): string { return JSON.stringify(this) }\n\n map<U>(callback: (item: T, index: number) => U): Collection<U> {\n return new Collection(this.items.map(callback))\n }\n\n flatMap<U>(callback: (item: T, index: number) => U | U[] | Collection<U>): Collection<U> {\n return new Collection(\n this.items.flatMap((item, i) => {\n const out = callback(item, i)\n return out instanceof Collection ? out.all() : (out as U | U[])\n }) as U[],\n )\n }\n\n filter(callback?: (item: T, index: number) => unknown): Collection<T> {\n return new Collection(this.items.filter(callback ?? ((item) => Boolean(item))))\n }\n\n reject(callback: (item: T, index: number) => unknown): Collection<T> {\n return new Collection(this.items.filter((item, i) => !callback(item, i)))\n }\n\n /** Return false from the callback to stop. */\n each(callback: (item: T, index: number) => unknown): this {\n for (let i = 0; i < this.items.length; i++) if (callback(this.items[i]!, i) === false) break\n return this\n }\n\n reduce<U>(callback: (carry: U, item: T, index: number) => U, initial: U): U {\n return this.items.reduce(callback, initial)\n }\n\n first(): T | undefined\n first<D = undefined>(callback: (item: T, index: number) => unknown, defaultValue?: D): T | D\n first<D>(callback?: (item: T, index: number) => unknown, defaultValue?: D): T | D | undefined {\n if (!callback) return this.items[0]\n const index = this.items.findIndex(callback)\n return index === -1 ? defaultValue : this.items[index]\n }\n\n last(): T | undefined\n last<D = undefined>(callback: (item: T, index: number) => unknown, defaultValue?: D): T | D\n last<D>(callback?: (item: T, index: number) => unknown, defaultValue?: D): T | D | undefined {\n if (!callback) return this.items.at(-1)\n const index = this.items.findLastIndex(callback)\n return index === -1 ? defaultValue : this.items[index]\n }\n\n where(key: Getter<T>, value: unknown): Collection<T>\n where(key: Getter<T>, operator: Operator, value: unknown): Collection<T>\n where(key: Getter<T>, operatorOrValue: unknown, value?: unknown): Collection<T> {\n const [op, expected] = arguments.length === 2 ? (['=', operatorOrValue] as const) : [operatorOrValue as Operator, value]\n return this.filter((item) => compare(read(item, key), op, expected))\n }\n\n firstWhere(key: Getter<T>, value: unknown): T | undefined\n firstWhere(key: Getter<T>, operator: Operator, value: unknown): T | undefined\n firstWhere(key: Getter<T>, operatorOrValue: unknown, value?: unknown): T | undefined {\n const [op, expected] = arguments.length === 2 ? (['=', operatorOrValue] as const) : [operatorOrValue as Operator, value]\n return this.items.find((item) => compare(read(item, key), op, expected))\n }\n\n whereIn(key: Getter<T>, values: readonly unknown[]): Collection<T> {\n const set = new Set(values)\n return this.filter((item) => set.has(read(item, key)))\n }\n\n whereNotIn(key: Getter<T>, values: readonly unknown[]): Collection<T> {\n const set = new Set(values)\n return this.filter((item) => !set.has(read(item, key)))\n }\n\n pluck<K extends keyof T & string>(key: K): Collection<T[K]> {\n return this.map((item) => read(item, key) as T[K])\n }\n\n keyBy(key: Getter<T>): Record<string, T> {\n return Object.fromEntries(this.items.map((item) => [String(read(item, key)), item]))\n }\n\n groupBy(key: Getter<T>): Record<string, Collection<T>> {\n const groups: Record<string, Collection<T>> = {}\n for (const item of this.items) (groups[String(read(item, key))] ??= new Collection<T>()).push(item)\n return groups\n }\n\n mapWithKeys<V>(callback: (item: T, index: number) => readonly [string, V]): Record<string, V> {\n return Object.fromEntries(this.items.map(callback))\n }\n\n sortBy(key: Getter<T>, direction: 'asc' | 'desc' = 'asc'): Collection<T> {\n const sign = direction === 'asc' ? 1 : -1\n return new Collection(\n this.items\n .map((item, index) => ({ item, index, value: read(item, key) }))\n .sort((a, b) => {\n const aNil = a.value === null || a.value === undefined\n const bNil = b.value === null || b.value === undefined\n if (aNil || bNil) return aNil === bNil ? a.index - b.index : aNil ? 1 : -1 // nulls last both ways\n return sign * ascending(a.value, b.value) || a.index - b.index\n })\n .map((x) => x.item),\n )\n }\n\n sortByDesc(key: Getter<T>): Collection<T> {\n return this.sortBy(key, 'desc')\n }\n\n sum(key?: Getter<T>): number { return numbers(this.items, key).reduce((a, b) => a + b, 0) }\n avg(key?: Getter<T>): number | undefined {\n const values = numbers(this.items, key)\n return values.length ? values.reduce((a, b) => a + b, 0) / values.length : undefined\n }\n min(key?: Getter<T>): number | undefined {\n const values = numbers(this.items, key)\n return values.length ? Math.min(...values) : undefined\n }\n max(key?: Getter<T>): number | undefined {\n const values = numbers(this.items, key)\n return values.length ? Math.max(...values) : undefined\n }\n\n unique(key?: Getter<T>): Collection<T> {\n const seen = new Set<unknown>()\n return this.filter((item) => {\n const v = key === undefined ? item : read(item, key)\n if (seen.has(v)) return false\n seen.add(v)\n return true\n })\n }\n\n chunk(size: number): Collection<Collection<T>> {\n if (size <= 0) return new Collection()\n const chunks: Collection<T>[] = []\n for (let i = 0; i < this.items.length; i += size) chunks.push(new Collection(this.items.slice(i, i + size)))\n return new Collection(chunks)\n }\n\n /** Negative count takes from the end. */\n take(count: number): Collection<T> {\n return new Collection(count < 0 ? this.items.slice(count) : this.items.slice(0, count))\n }\n skip(count: number): Collection<T> { return new Collection(this.items.slice(count)) }\n slice(offset: number, length?: number): Collection<T> {\n return new Collection(this.items.slice(offset, length === undefined ? undefined : offset + length))\n }\n values(): Collection<T> { return new Collection(this.items) }\n\n contains(key: keyof T & string, value: unknown): boolean\n contains(callback: (item: T) => boolean): boolean\n contains(value: unknown): boolean\n contains(keyOrValue: unknown, value?: unknown): boolean {\n if (arguments.length === 2) return this.items.some((item) => read(item, keyOrValue as keyof T & string) === value)\n if (typeof keyOrValue === 'function') return this.items.some(keyOrValue as (item: T) => boolean)\n return this.items.includes(keyOrValue as T)\n }\n\n /** Mutates, like Laravel. */\n push(...values: T[]): this {\n this.items.push(...values)\n return this\n }\n\n concat(values: Iterable<T>): Collection<T> {\n return new Collection([...this.items, ...values])\n }\n\n partition(callback: (item: T, index: number) => unknown): [Collection<T>, Collection<T>] {\n return [this.filter(callback), this.reject(callback)]\n }\n\n implode(glue: string): string\n implode(key: keyof T & string, glue: string): string\n implode(keyOrGlue: string, glue?: string): string {\n if (glue === undefined) return this.items.join(keyOrGlue)\n return this.items.map((item) => read(item, keyOrGlue as keyof T & string)).join(glue)\n }\n\n when<U = this>(condition: unknown, callback: (collection: this) => U): U | this {\n return condition ? callback(this) : this\n }\n\n pipe<U>(callback: (collection: this) => U): U { return callback(this) }\n\n tap(callback: (collection: this) => void): this {\n callback(this)\n return this\n }\n}\n\nexport function collect<T>(items: Iterable<T> = []): Collection<T> {\n return new Collection(items)\n}\n","import { Collection } from './Collection'\n\ntype Source<T> = () => AsyncIterable<T> | Iterable<T>\n\n/** Pull-based and async: for DB cursors (Model.lazy()) and large files. */\nexport class LazyCollection<T> implements AsyncIterable<T> {\n constructor(private readonly source: Source<T>) {}\n\n static make<T>(source: Source<T>): LazyCollection<T> {\n return new LazyCollection(source)\n }\n\n async *[Symbol.asyncIterator](): AsyncIterator<T> {\n yield* this.source()\n }\n\n map<U>(callback: (item: T, index: number) => U | Promise<U>): LazyCollection<U> {\n const self = this\n return new LazyCollection(async function* () {\n let i = 0\n for await (const item of self) yield await callback(item, i++)\n })\n }\n\n filter(callback: (item: T, index: number) => unknown): LazyCollection<T> {\n const self = this\n return new LazyCollection(async function* () {\n let i = 0\n for await (const item of self) if (await callback(item, i++)) yield item\n })\n }\n\n take(count: number): LazyCollection<T> {\n const self = this\n return new LazyCollection(async function* () {\n if (count <= 0) return\n let taken = 0\n for await (const item of self) {\n yield item\n if (++taken >= count) return\n }\n })\n }\n\n chunk(size: number): LazyCollection<Collection<T>> {\n const self = this\n return new LazyCollection(async function* () {\n if (size <= 0) return\n let buffer: T[] = []\n for await (const item of self) {\n buffer.push(item)\n if (buffer.length === size) {\n yield new Collection(buffer)\n buffer = []\n }\n }\n if (buffer.length) yield new Collection(buffer)\n })\n }\n\n /** Return false from the callback to stop. */\n async each(callback: (item: T, index: number) => unknown): Promise<void> {\n let i = 0\n for await (const item of this) if ((await callback(item, i++)) === false) return\n }\n\n async first(callback?: (item: T) => unknown): Promise<T | undefined> {\n for await (const item of this) if (!callback || (await callback(item))) return item\n return undefined\n }\n\n async count(): Promise<number> {\n let n = 0\n for await (const item of this) {\n void item\n n++\n }\n return n\n }\n\n async collect(): Promise<Collection<T>> {\n const items: T[] = []\n for await (const item of this) items.push(item)\n return new Collection(items)\n }\n}\n","import { randomBytes, randomUUID } from 'node:crypto'\nimport pluralize from 'pluralize'\n\nconst words = (value: string): string[] =>\n value\n .replace(/([a-z\\d])([A-Z])/g, '$1 $2')\n .replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2')\n .split(/[^A-Za-z\\d]+/)\n .filter(Boolean)\n\nconst ALPHANUM = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'\nconst escapeRegex = (s: string) => s.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\nconst anyOf = (needles: string | string[]) => (Array.isArray(needles) ? needles : [needles]).filter((n) => n !== '')\n\nexport const Str = {\n ucfirst: (v: string) => v.charAt(0).toUpperCase() + v.slice(1),\n lcfirst: (v: string) => v.charAt(0).toLowerCase() + v.slice(1),\n studly: (v: string) => words(v).map((w) => Str.ucfirst(w.toLowerCase())).join(''),\n camel: (v: string) => Str.lcfirst(Str.studly(v)),\n snake: (v: string, delimiter = '_') => words(v).map((w) => w.toLowerCase()).join(delimiter),\n kebab: (v: string) => Str.snake(v, '-'),\n title: (v: string) => v.toLowerCase().replace(/(^|\\s)\\S/g, (m) => m.toUpperCase()),\n slug: (v: string, separator = '-') =>\n v\n .normalize('NFKD')\n .replace(/[̀-ͯ]/g, '')\n .toLowerCase()\n .replace(/[^a-z\\d]+/g, separator)\n .replace(new RegExp(`^${escapeRegex(separator)}+|${escapeRegex(separator)}+$`, 'g'), ''),\n plural: (v: string, count = 2) => pluralize(v, count),\n singular: (v: string) => pluralize.singular(v),\n random: (length = 16) => {\n let out = ''\n while (out.length < length) {\n for (const byte of randomBytes(length)) {\n if (byte < 248 && out.length < length) out += ALPHANUM[byte % 62] // 248 = 62*4, avoids modulo bias\n }\n }\n return out\n },\n uuid: () => randomUUID(),\n /** Wildcard match: `*` matches anything; everything else is literal. */\n is: (pattern: string, value: string) =>\n pattern === value || new RegExp(`^${pattern.split('*').map(escapeRegex).join('.*')}$`, 's').test(value),\n startsWith: (v: string, needles: string | string[]) => anyOf(needles).some((n) => v.startsWith(n)),\n endsWith: (v: string, needles: string | string[]) => anyOf(needles).some((n) => v.endsWith(n)),\n contains: (v: string, needles: string | string[]) => anyOf(needles).some((n) => v.includes(n)),\n after: (v: string, search: string) => (search === '' || !v.includes(search) ? v : v.slice(v.indexOf(search) + search.length)),\n afterLast: (v: string, search: string) =>\n search === '' || !v.includes(search) ? v : v.slice(v.lastIndexOf(search) + search.length),\n before: (v: string, search: string) => (search === '' || !v.includes(search) ? v : v.slice(0, v.indexOf(search))),\n beforeLast: (v: string, search: string) =>\n search === '' || !v.includes(search) ? v : v.slice(0, v.lastIndexOf(search)),\n between: (v: string, from: string, to: string) => Str.beforeLast(Str.after(v, from), to),\n limit: (v: string, limit = 100, end = '...') => (v.length <= limit ? v : v.slice(0, limit).trimEnd() + end),\n start: (v: string, prefix: string) => (v.startsWith(prefix) ? v : prefix + v),\n finish: (v: string, cap: string) => (v.endsWith(cap) ? v : v + cap),\n}\n","type Obj = Record<string, unknown>\nconst FORBIDDEN = new Set(['__proto__', 'prototype', 'constructor'])\nconst isWalkable = (v: unknown): v is Obj => typeof v === 'object' && v !== null\nconst segments = (key: string) => key.split('.')\n\nexport const Arr = {\n get<T = unknown>(target: unknown, key: string | undefined, defaultValue?: T): T {\n if (key === undefined || key === '') return target as T\n let current: unknown = target\n for (const segment of segments(key)) {\n if (!isWalkable(current) || !Object.hasOwn(current, segment)) return defaultValue as T\n current = current[segment]\n }\n return current as T\n },\n\n has(target: unknown, key: string): boolean {\n const missing = Symbol('missing')\n return Arr.get(target, key, missing) !== missing\n },\n\n set(target: Obj, key: string, value: unknown): Obj {\n const parts = segments(key)\n if (parts.some((p) => FORBIDDEN.has(p))) throw new Error(`Refusing to set unsafe key \"${key}\"`)\n let current: Obj = target\n parts.slice(0, -1).forEach((segment) => {\n if (!isWalkable(current[segment])) current[segment] = {}\n current = current[segment] as Obj\n })\n current[parts.at(-1)!] = value\n return target\n },\n\n forget(target: Obj, key: string): void {\n const parts = segments(key)\n const parent = parts.length === 1 ? target : Arr.get<unknown>(target, parts.slice(0, -1).join('.'))\n if (isWalkable(parent)) delete parent[parts.at(-1)!]\n },\n\n dot(target: Obj, prefix = ''): Obj {\n const out: Obj = {}\n for (const [k, v] of Object.entries(target)) {\n const path = prefix + k\n if (isWalkable(v) && Object.keys(v).length > 0) Object.assign(out, Arr.dot(v as Obj, `${path}.`))\n else out[path] = v\n }\n return out\n },\n\n undot(flat: Obj): Obj {\n const out: Obj = {}\n for (const [k, v] of Object.entries(flat)) Arr.set(out, k, v)\n return out\n },\n\n only<T extends Obj>(target: T, keys: string[]): Partial<T> {\n return Object.fromEntries(keys.filter((k) => Object.hasOwn(target, k)).map((k) => [k, target[k]])) as Partial<T>\n },\n\n except<T extends Obj>(target: T, keys: string[]): Partial<T> {\n const skip = new Set(keys)\n return Object.fromEntries(Object.entries(target).filter(([k]) => !skip.has(k))) as Partial<T>\n },\n\n wrap<T>(value: T | T[] | null | undefined): T[] {\n if (value === null || value === undefined) return []\n return Array.isArray(value) ? value : [value]\n },\n\n first<T, D = undefined>(items: readonly T[], predicate?: (item: T, index: number) => boolean, defaultValue?: D): T | D {\n const index = predicate ? items.findIndex(predicate) : items.length > 0 ? 0 : -1\n return index === -1 ? (defaultValue as D) : items[index]!\n },\n\n last<T, D = undefined>(items: readonly T[], predicate?: (item: T, index: number) => boolean, defaultValue?: D): T | D {\n const index = predicate ? items.findLastIndex(predicate) : items.length - 1\n return index === -1 ? (defaultValue as D) : items[index]!\n },\n}\n","import { ConfigRepository, type Application, type ServiceProvider as ServiceProviderContract } from '@orieljs/contracts'\n\nexport abstract class ServiceProvider implements ServiceProviderContract {\n constructor(protected readonly app: Application) {}\n\n register(): void {}\n\n boot(): void | Promise<void> {}\n\n /** Package defaults under `key`; values the app already set win (shallow merge, like Laravel). */\n protected mergeConfigFrom(defaults: Record<string, unknown>, key: string): void {\n const config = this.app.make(ConfigRepository)\n config.set(key, { ...defaults, ...config.get<Record<string, unknown>>(key, {}) })\n }\n}\n","import type { Abstract } from '@orieljs/contracts'\nimport { ContainerNotAvailableError, currentContainer, describe } from '@orieljs/container'\n\nexport interface FacadeStatics<T> {\n getFacadeRoot(): T\n /** Replace the instance in the current container (used by X.fake()). */\n swap(instance: T): void\n}\nexport type Facade<T, X = object> = T & X & FacadeStatics<T>\n\nexport function facade<T extends object, X extends object = object>(abstract: Abstract<T>, extras?: X): Facade<T, X> {\n const container = () => {\n const c = currentContainer()\n if (!c) throw new ContainerNotAvailableError(describe(abstract))\n return c\n }\n const statics: FacadeStatics<T> = {\n getFacadeRoot: () => container().make(abstract),\n swap: (instance) => void container().instance(abstract, instance),\n }\n\n const proxy: Facade<T, X> = new Proxy({} as Facade<T, X>, {\n get(_target, prop) {\n if (typeof prop === 'symbol' || prop === 'then') return undefined\n if (extras && Object.hasOwn(extras, prop)) {\n const extra = (extras as Record<string, unknown>)[prop]\n return typeof extra === 'function' ? extra.bind(proxy) : extra\n }\n if (Object.hasOwn(statics, prop)) return statics[prop as keyof FacadeStatics<T>]\n const root = statics.getFacadeRoot()\n const value = Reflect.get(root, prop, root)\n return typeof value === 'function' ? value.bind(root) : value\n },\n })\n return proxy\n}\n","import type { Class, ClassRegistry as ClassRegistryContract } from '@orieljs/contracts'\n\nexport class ClassRegistry implements ClassRegistryContract {\n private readonly byName = new Map<string, Class<unknown>>()\n private readonly byClass = new Map<Class<unknown>, string>()\n\n register(cls: Class<unknown>, name: string = cls.name): string {\n const existingName = this.byClass.get(cls)\n if (existingName !== undefined) return existingName\n if (!name) throw new Error('Anonymous classes need an explicit name: registry.register(cls, \"Some.Name\")')\n const existing = this.byName.get(name)\n if (existing && existing !== cls) {\n throw new Error(`\"${name}\" is already registered to a different class. Pass an explicit name: register(cls, \"Module.${name}\")`)\n }\n this.byName.set(name, cls)\n this.byClass.set(cls, name)\n return name\n }\n\n nameOf(cls: Class<unknown>): string | undefined {\n return this.byClass.get(cls)\n }\n\n resolve<T = unknown>(name: string): Class<T> {\n const cls = this.byName.get(name)\n if (!cls) throw new Error(`No class registered as \"${name}\". Is it registered by its service provider?`)\n return cls as Class<T>\n }\n\n has(name: string): boolean {\n return this.byName.has(name)\n }\n}\n","import { setTimeout as sleep } from 'node:timers/promises'\nimport { Application, ConfigRepository, type Abstract } from '@orieljs/contracts'\nimport { currentContainer, inject } from '@orieljs/container'\n\nexport { collect } from '@orieljs/collections'\n\n/** Container methods that must act on the current (request) scope rather than on the root application. */\nconst SCOPE_METHODS = new Set<PropertyKey>(['make', 'instance', 'bound', 'resolved', 'forgetInstance', 'createScope', 'run'])\nconst scopedViews = new WeakMap<object, Application>()\n\n/** The application, seen from `scope`: container methods hit the scope, everything else hits the application. */\nfunction viewFrom(scope: object, application: Application): Application {\n let view = scopedViews.get(scope)\n if (view === undefined) {\n view = new Proxy(application, {\n get(target, property) {\n const source: object = SCOPE_METHODS.has(property) ? scope : target\n const member: unknown = Reflect.get(source, property, source)\n return typeof member === 'function' ? member.bind(source) : member\n },\n })\n scopedViews.set(scope, view)\n }\n return view\n}\n\n/**\n * The application, or an abstract resolved from the current container.\n * Inside a request scope, app().make()/instance()/… act on that scope, so app().make(X) sees scoped services.\n */\nexport function app(): Application\nexport function app<T>(abstract: Abstract<T>): T\nexport function app<T>(abstract?: Abstract<T>): T | Application {\n if (abstract !== undefined) return inject(abstract)\n const application = inject(Application)\n const current = currentContainer()\n return current === undefined || current === application ? application : viewFrom(current, application)\n}\n\nexport function config(): ConfigRepository\nexport function config(values: Record<string, unknown>): void\nexport function config<T = unknown>(key: string, defaultValue?: T): T\nexport function config(keyOrValues?: string | Record<string, unknown>, defaultValue?: unknown): unknown {\n const repository = inject(ConfigRepository)\n if (keyOrValues === undefined) return repository\n if (typeof keyOrValues === 'string') return repository.get(keyOrValues, defaultValue)\n repository.set(keyOrValues)\n return undefined\n}\n\nexport const now = (): Date => new Date()\n\nexport const value = <T>(v: T | (() => T)): T => (typeof v === 'function' ? (v as () => T)() : v)\n\nexport function tap<T>(target: T, callback: (target: T) => void): T {\n callback(target)\n return target\n}\n\n/** Calls fn up to `times` times (attempt numbers are 1-based). Rethrows the last error, or the first one `when` rejects. */\nexport async function retry<T>(\n times: number,\n fn: (attempt: number) => T | Promise<T>,\n sleepMs: number | ((attempt: number) => number) = 0,\n when?: (error: unknown) => boolean,\n): Promise<T> {\n for (let attempt = 1; ; attempt++) {\n try {\n return await fn(attempt)\n } catch (error) {\n if (attempt >= times || (when && !when(error))) throw error\n const ms = typeof sleepMs === 'function' ? sleepMs(attempt) : sleepMs\n if (ms > 0) await sleep(ms)\n }\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/** Loads .env (or .env.<APP_ENV> when it exists). Never overwrites existing variables. Returns the file loaded, if any. */\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 for (const [key, value] of Object.entries(parse(readFileSync(file)))) {\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/** Imports config/*.{ts,js,mjs}; each file's default export becomes config[<file name>]. */\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] = 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'\n\ntype LifecycleCallback = (app: ApplicationContract) => void | Promise<void>\n\nexport class Application extends Container implements ApplicationContract {\n readonly version = '0.0.0'\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 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 }\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 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 web?: string\n api?: 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) => (p === undefined ? undefined : isAbsolute(p) ? p : join(this.app.basePath(), p))\n const paths: RoutingPaths = { apiPrefix: options.apiPrefix ?? 'api' }\n if (options.web !== undefined) paths.web = abs(options.web)\n if (options.api !== undefined) paths.api = abs(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 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"],"mappings":";;;;;;;;;;;;ACAA,SAAS,yBAAyB;ACE3B,SAAS,SAAS,UAAqC;AAC5D,SAAO,OAAO,aAAa,aAAa,SAAS,QAAQ,sBAAsB,SAAS;AAC1F;ACFO,IAAM,yBAAN,cAAqC,MAA4B;EAC7D,OAAO;EACE,OAAO;AAC3B;AAEO,IAAM,0BAAN,cAAsC,MAA4B;EAGvE,YAAqB,OAAiB;AACpC,UAAM,iCAAiC,MAAM,KAAK,MAAM,CAAC,EAAE;AADxC,SAAA,QAAA;EAErB;EAFqB;EAFZ,OAAO;EACE,OAAO;AAI3B;AAEO,IAAM,6BAAN,cAAyC,MAA4B;EACjE,OAAO;EACE,OAAO;EACzB,YAAY,MAAc;AACxB;MACE,mBAAmB,IAAI;IAGzB;EACF;AACF;AFpBA,IAAM,UAAU,uBAAO,IAAI,qBAAqB;AACzC,IAAM,aAAa,uBAAO,IAAI,0BAA0B;AAC/D,IAAM,eAAe,u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,QAAQ,EAAE,SAAS,EAAE,gBAAgB,2BAA2B,EAAE,CAAC;AACvH,SAAO,SAAS,KAAK,MAAM;AAC7B;","names":["Container","value","value","app","config","ClassRegistry","currentContainer","ConfigRepository","existsSync","join","value","config","join","join","app","join","Application","Container","ClassRegistry","ConfigRepository","value"]}
|
|
1
|
+
{"version":3,"sources":["../../Auth/errors.ts","../../Auth/events.ts","../../Auth/notifications/ResetPassword.ts","../../Auth/AuthenticatableModel.ts","../../Auth/equals.ts","../../Auth/EloquentUserProvider.ts","../../Auth/guards/SessionGuard.ts","../../Auth/AuthManager.ts","../../Auth/guards/TokenGuard.ts","../../Auth/tokens/PersonalAccessTokens.ts","../../Auth/dates.ts","../../Auth/migrations.ts","../../Auth/Access/Response.ts","../../Auth/Access/Gate.ts","../../Auth/middleware/Authorize.ts","../../Auth/Passwords/DatabaseTokenRepository.ts","../../Auth/Passwords/PasswordBroker.ts","../../Auth/middleware/Authenticate.ts","../../Auth/middleware/RedirectIfAuthenticated.ts","../../Auth/middleware/redirect.ts","../../Auth/middleware/EnsureEmailIsVerified.ts","../../Auth/discoverPolicies.ts","../../Auth/facade.ts","../../Auth/AuthServiceProvider.ts","../../Bus/errors.ts","../../Bus/symbols.ts","../../Bus/UniqueLock.ts","../../Bus/PendingChain.ts","../../Bus/PendingBatch.ts","../../Bus/Dispatcher.ts","../../Bus/PendingDispatch.ts","../../Bus/Dispatchable.ts","../../Bus/helpers.ts","../../Bus/facade.ts","../../Bus/BusServiceProvider.ts","../../Cache/errors.ts","../../Cache/serialize.ts","../../Cache/locks/GenericLock.ts","../../Cache/Repository.ts","../../Cache/stores/MemoryStore.ts","../../Cache/stores/FileStore.ts","../../Cache/insertOrTakeOver.ts","../../Cache/stores/DatabaseStore.ts","../../Cache/locks/DatabaseLock.ts","../../Cache/migrations.ts","../../Cache/stores/RedisStore.ts","../../Cache/locks/RedisLock.ts","../../Cache/stores/RedisRepository.ts","../../Cache/CacheManager.ts","../../Cache/facade.ts","../../Cache/CacheServiceProvider.ts","../../Console/ConsoleServiceProvider.ts","../../Console/commands/AboutCommand.ts","../../Console/Command.ts","../../Console/errors.ts","../../Console/io.ts","../../Console/commands/HelpCommand.ts","../../Console/signature.ts","../../Console/commands/ListCommand.ts","../../Console/commands/make/GeneratorCommand.ts","../../Console/commands/make/stubs.ts","../../Console/commands/make/MakeCastCommand.ts","../../Console/commands/make/MakeCommandCommand.ts","../../Console/commands/make/MakeControllerCommand.ts","../../Console/commands/make/MakeEventCommand.ts","../../Console/commands/make/MakeFactoryCommand.ts","../../Console/commands/make/MakeJobCommand.ts","../../Console/commands/make/MakeListenerCommand.ts","../../Console/commands/make/MakeMailCommand.ts","../../Console/commands/make/MakeMiddlewareCommand.ts","../../Console/commands/make/MakeModelCommand.ts","../../Console/commands/make/MakeNotificationCommand.ts","../../Console/commands/make/MakeObserverCommand.ts","../../Console/commands/make/MakePolicyCommand.ts","../../Console/commands/make/MakeProviderCommand.ts","../../Console/commands/make/MakeRequestCommand.ts","../../Console/commands/make/MakeResourceCommand.ts","../../Console/commands/make/MakeRuleCommand.ts","../../Console/commands/make/MakeSeederCommand.ts","../../Console/commands/make/MakeTestCommand.ts","../../Console/commands/ScheduleListCommand.ts","../../Console/commands/ScheduleRunCommand.ts","../../Console/commands/scheduleEvents.ts","../../Console/commands/ScheduleWorkCommand.ts","../../Console/commands/TestCommand.ts","../../Console/commands/TinkerCommand.ts","../../Console/discover.ts","../../Console/Kernel.ts","../../Console/ClosureCommand.ts","../../Console/suggest.ts","../../Console/Schedule.ts","../../Console/facades.ts","../../Console/runConsole.ts","../../Cookie/serialize.ts","../../Cookie/CookieValuePrefix.ts","../../Cookie/CookieJar.ts","../../Cookie/middleware/AddQueuedCookiesToResponse.ts","../../Cookie/middleware/EncryptCookies.ts","../../Cookie/facade.ts","../../Cookie/CookieServiceProvider.ts","../../Database/errors.ts","../../Database/runtime.ts","../../Database/Connectors/SqliteDatabase.ts","../../Database/Connectors/dialect.ts","../../Database/Query/Expression.ts","../../Database/Query/Builder.ts","../../Database/Pagination/AbstractPaginator.ts","../../Database/Pagination/CursorPaginator.ts","../../Database/Pagination/LengthAwarePaginator.ts","../../Database/Pagination/Paginator.ts","../../Database/Query/Grammar.ts","../../Database/Query/values.ts","../../Database/Connection.ts","../../Database/Schema/Builder.ts","../../Database/Schema/ColumnDefinition.ts","../../Database/Schema/ForeignKeyDefinition.ts","../../Database/Schema/Blueprint.ts","../../Database/Schema/Grammar.ts","../../Database/DatabaseManager.ts","../../Database/facades.ts","../../Database/Eloquent/Model.ts","../../Database/Eloquent/Builder.ts","../../Database/Eloquent/Relations/constraints.ts","../../Database/Eloquent/SoftDeletingScope.ts","../../Database/Eloquent/casts.ts","../../Database/Eloquent/Factories/Factory.ts","../../Database/Eloquent/Relations/BelongsTo.ts","../../Database/Eloquent/Relations/morphMap.ts","../../Database/Eloquent/Relations/Relation.ts","../../Database/Eloquent/Relations/BelongsToMany.ts","../../Database/Eloquent/Relations/HasOneOrMany.ts","../../Database/Eloquent/Relations/MorphTo.ts","../../Database/Eloquent/events.ts","../../Database/Eloquent/Relations/HasMany.ts","../../Database/Eloquent/Relations/HasManyThrough.ts","../../Database/Eloquent/Relations/HasOne.ts","../../Database/Eloquent/Relations/MorphMany.ts","../../Database/Eloquent/Relations/MorphOne.ts","../../Database/Migrations/Migration.ts","../../Database/Migrations/MigrationCreator.ts","../../Database/Migrations/MigrationRepository.ts","../../Database/Migrations/Migrator.ts","../../Database/Seeder.ts","../../Database/Console/commands.ts","../../Database/Types/TypeGenerator.ts","../../Database/ModelRegistry.ts","../../Database/Eloquent/Factories/fake.ts","../../Database/RouteModelResolver.ts","../../Database/DatabaseServiceProvider.ts","../../Encryption/errors.ts","../../Encryption/Encrypter.ts","../../Encryption/KeyGenerateCommand.ts","../../Encryption/facade.ts","../../Encryption/EncryptionServiceProvider.ts","../../Events/CallQueuedListener.ts","../../Events/errors.ts","../../Events/discover.ts","../../Events/facade.ts","../../Events/EventServiceProvider.ts","../../Events/Dispatcher.ts","../../Events/listeners.ts","../../Events/queueable.ts","../../Filesystem/errors.ts","../../Filesystem/facade.ts","../../Filesystem/FilesystemManager.ts","../../Filesystem/LocalFilesystem.ts","../../Filesystem/mime.ts","../../Filesystem/paths.ts","../../Filesystem/S3Filesystem.ts","../../Filesystem/FilesystemServiceProvider.ts","../../Filesystem/StorageLinkCommand.ts","../../Hashing/errors.ts","../../Hashing/info.ts","../../Hashing/BcryptHasher.ts","../../Hashing/coerce.ts","../../Hashing/ArgonHasher.ts","../../Hashing/HashManager.ts","../../Hashing/facade.ts","../../Hashing/HashingServiceProvider.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/bun.ts","../../Http/server/node.ts","../../Http/server/serve.ts","../../Http/commands.ts","../../Http/HttpServiceProvider.ts","../../Log/context.ts","../../Log/errors.ts","../../Log/levels.ts","../../Log/BaseLogger.ts","../../Log/channels.ts","../../Log/DailyRotatingStream.ts","../../Log/writeFailure.ts","../../Log/PinoLogger.ts","../../Log/facade.ts","../../Log/LogManager.ts","../../Log/NullLogger.ts","../../Log/StackLogger.ts","../../Log/LogServiceProvider.ts","../../Mail/errors.ts","../../Mail/address.ts","../../Mail/transports/ArrayTransport.ts","../../Mail/transports/LogTransport.ts","../../Mail/transports/FailoverTransport.ts","../../Mail/transports/SmtpTransport.ts","../../Mail/render.ts","../../Mail/Mailable.ts","../../Mail/symbols.ts","../../Mail/Mailer.ts","../../Mail/QueuedMailSender.ts","../../Mail/Jobs/SendQueuedMailable.ts","../../Mail/MailManager.ts","../../Mail/facade.ts","../../Mail/MailServiceProvider.ts","../../Notifications/errors.ts","../../Notifications/MailMessage.ts","../../Notifications/channels/MailNotificationChannel.ts","../../Notifications/channels/DatabaseNotificationChannel.ts","../../Notifications/migrations.ts","../../Notifications/symbols.ts","../../Notifications/Dispatcher.ts","../../Notifications/Notifiable.ts","../../Notifications/AnonymousNotifiable.ts","../../Notifications/Jobs/SendQueuedNotifications.ts","../../Notifications/Notification.ts","../../Notifications/facade.ts","../../Notifications/NotificationsServiceProvider.ts","../../Pipeline/BasePipeline.ts","../../Pipeline/Hub.ts","../../Pipeline/PipelineServiceProvider.ts","../../Queue/errors.ts","../../Queue/symbols.ts","../../Queue/serialization.ts","../../Queue/payload.ts","../../Queue/jobs/BaseJob.ts","../../Queue/jobs/SyncJob.ts","../../Queue/CallQueuedHandler.ts","../../Queue/middleware/WithoutOverlapping.ts","../../Queue/queues/QueueBase.ts","../../Queue/queues/SyncQueue.ts","../../Queue/queues/NullQueue.ts","../../Queue/QueueManager.ts","../../Queue/jobs/DatabaseJob.ts","../../Queue/queues/DatabaseQueue.ts","../../Queue/queues/RedisQueue.ts","../../Queue/jobs/RedisJob.ts","../../Queue/queues/redisScripts.ts","../../Queue/failed/NullFailedJobProvider.ts","../../Queue/failed/DatabaseFailedJobProvider.ts","../../Queue/migrations.ts","../../Queue/batching/Batch.ts","../../Queue/batching/DatabaseBatchRepository.ts","../../Queue/Worker.ts","../../Queue/console/discoverJobs.ts","../../Queue/console/commands.ts","../../Queue/config.ts","../../Queue/facade.ts","../../Queue/QueueServiceProvider.ts","../../Routing/BaseRouter.ts","../../Routing/dispatch.ts","../../Routing/bindings.ts","../../Routing/errors.ts","../../Routing/middleware.ts","../../Routing/toResponse.ts","../../Routing/RouteDefinition.ts","../../Routing/GroupRegistrar.ts","../../Routing/resource.ts","../../Routing/BaseUrlGenerator.ts","../../Routing/facade.ts","../../Routing/routeFiles.ts","../../Routing/RoutingServiceProvider.ts","../../Session/Store.ts","../../Session/handlers/ArraySessionHandler.ts","../../Session/handlers/FileSessionHandler.ts","../../Session/handlers/DatabaseSessionHandler.ts","../../Session/handlers/CookieSessionHandler.ts","../../Session/handlers/RedisSessionHandler.ts","../../Session/SessionManager.ts","../../Session/errors.ts","../../Session/middleware/StartSession.ts","../../Session/middleware/cookies.ts","../../Session/middleware/VerifyCsrfToken.ts","../../Session/equals.ts","../../Session/ViewErrorBag.ts","../../Session/facade.ts","../../Session/SessionServiceProvider.ts","../../Validation/errors.ts","../../Validation/FormRequest.ts","../../Validation/messages.ts","../../Validation/MessageBag.ts","../../Validation/rules/database.ts","../../Validation/parse.ts","../../Validation/rules/file.ts","../../Validation/rules/format.ts","../../Validation/rules/presence.ts","../../Validation/rules/type.ts","../../Validation/rules/size.ts","../../Validation/registry.ts","../../Validation/Rule.ts","../../Validation/Validator.ts","../../Validation/ValidationFactory.ts","../../Validation/facade.ts","../../Validation/ValidationServiceProvider.ts","../providers.ts","../Application.ts","../facades.ts"],"sourcesContent":["import type { AuthenticationError as AuthenticationErrorContract, OrielError } from '@orieljs/contracts'\n\n/** Laravel's AuthenticationException: 401 JSON, or a redirect to the login page. */\nexport class AuthenticationError extends Error implements AuthenticationErrorContract {\n readonly kind = 'Authentication' as const\n readonly status = 401\n override readonly name = 'AuthenticationError'\n\n constructor(\n message = 'Unauthenticated.',\n readonly guards: string[] = [],\n readonly redirectTo?: string,\n ) {\n super(message)\n }\n}\n\n/** Laravel's AuthorizationException: 403 by default, or the status a policy chose (denyWithStatus/denyAsNotFound). */\nexport class AuthorizationError extends Error implements OrielError {\n readonly kind = 'Authorization' as const\n override readonly name = 'AuthorizationError'\n readonly status: number\n readonly code: string | undefined\n\n constructor(message?: string, status = 403, code?: string) {\n super(message === undefined || message === '' ? 'This action is unauthorized.' : message)\n this.status = status\n this.code = code\n }\n}\n","import type { Authenticatable, Credentials } from '@orieljs/contracts'\n\n/** Fired before credentials are checked. */\nexport class Attempting {\n constructor(readonly guard: string, readonly credentials: Credentials, readonly remember: boolean) {}\n}\n\n/** Fired when credentials are valid, before logging in. */\nexport class Validated {\n constructor(readonly guard: string, readonly user: Authenticatable) {}\n}\n\n/** Fired when an attempt fails. */\nexport class Failed {\n constructor(readonly guard: string, readonly user: Authenticatable | undefined, readonly credentials: Credentials) {}\n}\n\n/** Fired after a user is logged in. */\nexport class Login {\n constructor(readonly guard: string, readonly user: Authenticatable, readonly remember: boolean) {}\n}\n\n/** Fired after a user is logged out. */\nexport class Logout {\n constructor(readonly guard: string, readonly user: Authenticatable | undefined) {}\n}\n\n/** Fired after a password reset. */\nexport class PasswordReset {\n constructor(readonly user: Authenticatable) {}\n}\n","import { ConfigRepository, UrlGenerator, type Notification } from '@orieljs/contracts'\nimport { currentContainer } from '@orieljs/container'\n\n/** What the default toMail() returns: Laravel's reset mail, as plain data (see the plan's notes). */\nexport interface ResetPasswordMail {\n subject: string\n lines: string[]\n actionText: string\n actionUrl: string\n outroLines: string[]\n}\n\n/** The user the notification is for (AuthenticatableModel provides this). */\nexport interface CanResetPassword {\n getEmailForPasswordReset(): string\n}\n\nlet createUrlCallback: ((notifiable: CanResetPassword, token: string) => string) | undefined\nlet toMailCallback: ((notifiable: CanResetPassword, token: string) => unknown) | undefined\n\n/** Laravel's ResetPassword notification (sent by the password broker). */\nexport class ResetPassword implements Notification {\n constructor(readonly token: string) {}\n\n /** Build the reset URL yourself (e.g. for a SPA front end). */\n static createUrlUsing(callback: ((notifiable: CanResetPassword, token: string) => string) | undefined): void {\n createUrlCallback = callback\n }\n\n /** Build the mail yourself (e.g. a MailMessage from the Notifications component). */\n static toMailUsing(callback: ((notifiable: CanResetPassword, token: string) => unknown) | undefined): void {\n toMailCallback = callback\n }\n\n via(): string[] {\n return ['mail']\n }\n\n toMail(notifiable: object): unknown {\n const user = notifiable as CanResetPassword\n if (toMailCallback !== undefined) return toMailCallback(user, this.token)\n const container = currentContainer()\n const config = container?.bound(ConfigRepository) ? container.make(ConfigRepository) : undefined\n const broker = config?.get<string>('auth.defaults.passwords', 'users') ?? 'users'\n const expire = config?.get<number>(`auth.passwords.${broker}.expire`, 60) ?? 60\n const mail: ResetPasswordMail = {\n subject: 'Reset Password Notification',\n lines: ['You are receiving this email because we received a password reset request for your account.'],\n actionText: 'Reset Password',\n actionUrl: this.resetUrl(user),\n outroLines: [\n `This password reset link will expire in ${expire} minutes.`,\n 'If you did not request a password reset, no further action is required.',\n ],\n }\n return mail\n }\n\n resetUrl(notifiable: CanResetPassword): string {\n if (createUrlCallback !== undefined) return createUrlCallback(notifiable, this.token)\n const email = notifiable.getEmailForPasswordReset()\n const container = currentContainer()\n if (container?.bound(UrlGenerator)) {\n const url = container.make(UrlGenerator)\n return url.hasRoute('password.reset')\n ? url.route('password.reset', { token: this.token, email })\n : url.to(`/reset-password/${encodeURIComponent(this.token)}`, { email })\n }\n return `/reset-password/${encodeURIComponent(this.token)}?email=${encodeURIComponent(email)}`\n }\n}\n","import { NotificationDispatcher, type Authenticatable, type MustVerifyEmail, type Notifiable, type Notification } from '@orieljs/contracts'\nimport { currentContainer } from '@orieljs/container'\nimport { ResetPassword } from './notifications/ResetPassword'\n\n/** The part of a model (Contracts/Database ModelInstance) the mixin needs. */\nexport interface AuthModelBase {\n getKey(): unknown\n getKeyName(): string\n getAttribute<T = unknown>(key: string): T\n setAttribute(key: string, value: unknown): unknown\n save(): Promise<boolean>\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type AuthModelConstructor = new (...args: any[]) => AuthModelBase\n\nlet verificationSender: ((user: MustVerifyEmail) => Promise<void>) | undefined\n\n/** Configure how the email verification notification is sent (signed URLs are not in v1's UrlGenerator). */\nexport function sendEmailVerificationUsing(callback: ((user: MustVerifyEmail) => Promise<void>) | undefined): void {\n verificationSender = callback\n}\n\n/** Sends a notification through user.notify() (the Notifications mixin), else the NotificationDispatcher token. */\nexport async function sendNotification(user: unknown, notification: Notification): Promise<void> {\n const notifiable = user as Notifiable & { notify?(notification: Notification): Promise<void> }\n if (typeof notifiable.notify === 'function') return notifiable.notify(notification)\n const container = currentContainer()\n if (container?.bound(NotificationDispatcher)) return container.make(NotificationDispatcher).send(notifiable, notification)\n throw new Error(\n 'Unable to send the notification: give the user model a notify() method (Notifiable) or register the Notifications component.',\n )\n}\n\n/**\n * Laravel's Illuminate\\Foundation\\Auth\\User traits (Authenticatable, CanResetPassword, MustVerifyEmail) as a mixin:\n * `class User extends AuthenticatableModel(Model) {}`. Columns: the primary key, `password`, `remember_token`,\n * `email`, `email_verified_at`.\n */\nexport function AuthenticatableModel<TBase extends AuthModelConstructor>(Base: TBase) {\n return class AuthenticatableUser extends Base implements Authenticatable, MustVerifyEmail {\n getAuthIdentifierName(): string {\n return this.getKeyName()\n }\n\n getAuthIdentifier(): unknown {\n return this.getKey()\n }\n\n getAuthPasswordName(): string {\n return 'password'\n }\n\n getAuthPassword(): string {\n const password = this.getAttribute<unknown>(this.getAuthPasswordName())\n return typeof password === 'string' ? password : ''\n }\n\n getRememberToken(): string | undefined {\n const token = this.getAttribute<unknown>(this.getRememberTokenName())\n return typeof token === 'string' && token !== '' ? token : undefined\n }\n\n setRememberToken(value: string): void {\n this.setAttribute(this.getRememberTokenName(), value)\n }\n\n getRememberTokenName(): string {\n return 'remember_token'\n }\n\n getEmailForPasswordReset(): string {\n return String(this.getAttribute<unknown>('email') ?? '')\n }\n\n sendPasswordResetNotification(token: string): Promise<void> {\n return sendNotification(this, new ResetPassword(token))\n }\n\n hasVerifiedEmail(): boolean {\n const verifiedAt = this.getAttribute<unknown>('email_verified_at')\n return verifiedAt !== null && verifiedAt !== undefined\n }\n\n markEmailAsVerified(): Promise<boolean> {\n this.setAttribute('email_verified_at', new Date())\n return this.save()\n }\n\n getEmailForVerification(): string {\n return String(this.getAttribute<unknown>('email') ?? '')\n }\n\n async sendEmailVerificationNotification(): Promise<void> {\n if (verificationSender === undefined) {\n throw new Error('No email verification sender is configured. Call sendEmailVerificationUsing() in a service provider.')\n }\n await verificationSender(this)\n }\n }\n}\n","import { timingSafeEqual } from 'node:crypto'\n\n/** Constant-time string comparison (PHP's hash_equals). */\nexport function equals(known: string, user: string): boolean {\n const a = Buffer.from(known)\n const b = Buffer.from(user)\n return a.length === b.length && timingSafeEqual(a, b)\n}\n","import type { Authenticatable, Credentials, Hasher, ModelInstance, ModelStatic, UserProvider } from '@orieljs/contracts'\nimport { equals } from './equals'\n\n/**\n * A model class for the provider. Typed loosely on purpose: model statics are usually `this`-generic, so\n * `typeof User` only matches ModelStatic<ModelInstance>. Instances must implement Authenticatable at runtime\n * (e.g. through AuthenticatableModel).\n */\nexport type AuthModel = ModelStatic\n\n/**\n * Laravel's EloquentUserProvider over the ModelStatic contract. Credentials whose key contains \"password\" are never\n * used in the query; they are checked with the Hasher.\n */\nexport class EloquentUserProvider implements UserProvider {\n constructor(\n readonly hasher: Hasher,\n readonly model: AuthModel,\n ) {}\n\n async retrieveById(id: unknown): Promise<Authenticatable | undefined> {\n return ((await this.model.find(id)) ?? undefined) as Authenticatable | undefined\n }\n\n async retrieveByToken(id: unknown, token: string): Promise<Authenticatable | undefined> {\n const user = await this.retrieveById(id)\n const rememberToken = user?.getRememberToken()\n return user !== undefined && rememberToken !== undefined && equals(rememberToken, token) ? user : undefined\n }\n\n async updateRememberToken(user: Authenticatable, token: string): Promise<void> {\n user.setRememberToken(token)\n // Like Laravel, don't touch updated_at just for the remember token.\n const model = user as Authenticatable & Partial<ModelInstance> & { timestamps?: boolean }\n const timestamps = model.timestamps\n if (timestamps !== undefined) model.timestamps = false\n try {\n await model.save?.()\n } finally {\n if (timestamps !== undefined) model.timestamps = timestamps\n }\n }\n\n async retrieveByCredentials(credentials: Credentials): Promise<Authenticatable | undefined> {\n const conditions = Object.entries(credentials).filter(([key]) => !key.includes('password'))\n if (conditions.length === 0) return undefined\n let query = this.model.query()\n for (const [key, value] of conditions) {\n if (Array.isArray(value)) query = query.whereIn(key, value)\n else if (typeof value === 'function') (value as (q: typeof query) => void)(query)\n else query = query.where(key, value)\n }\n return ((await query.first()) ?? undefined) as Authenticatable | undefined\n }\n\n async validateCredentials(user: Authenticatable, credentials: Credentials): Promise<boolean> {\n const plain = credentials.password\n if (typeof plain !== 'string') return false\n return this.hasher.check(plain, user.getAuthPassword())\n }\n\n /** Rehash the stored password when the hasher's settings changed (Laravel 11's rehash_on_login). */\n async rehashPasswordIfRequired(user: Authenticatable, credentials: Credentials, force = false): Promise<void> {\n const plain = credentials.password\n if (typeof plain !== 'string') return\n if (!force && !this.hasher.needsRehash(user.getAuthPassword())) return\n const model = user as Authenticatable & Partial<ModelInstance> & { getAuthPasswordName?(): string }\n model.setAttribute?.(model.getAuthPasswordName?.() ?? 'password', await this.hasher.make(plain))\n await model.save?.()\n }\n\n getModel(): AuthModel {\n return this.model\n }\n}\n","import { createHash } from 'node:crypto'\nimport {\n CookieJar,\n EventDispatcher,\n HttpRequest,\n Session,\n type Authenticatable,\n type Container,\n type Credentials,\n type StatefulGuard,\n type Token,\n type UserProvider,\n} from '@orieljs/contracts'\nimport { BindingResolutionError } from '@orieljs/container'\nimport { Str } from '@orieljs/support'\nimport { Attempting, Failed, Login, Logout, Validated } from '../events'\n\nexport interface SessionGuardOptions {\n /** Minutes the remember-me cookie lasts (default 576000, five years). */\n rememberDuration?: number\n /** Rehash the password after a successful attempt when the hasher's settings changed (hashing.rehash_on_login). */\n rehashOnLogin?: boolean\n}\n\nconst GUARD_HASH = createHash('sha1').update('Oriel\\\\Auth\\\\SessionGuard').digest('hex')\n\n/**\n * Laravel's SessionGuard: the user id lives in the session under `login_<guard>_<sha1>`; \"remember me\" is a\n * `remember_<guard>_<sha1>` cookie holding `id|token|passwordHash`. One instance per request scope.\n */\nexport class SessionGuard implements StatefulGuard {\n #user: Authenticatable | undefined\n #lastAttempted: Authenticatable | undefined\n #loggedOut = false\n #viaRemember = false\n #recallAttempted = false\n\n constructor(\n readonly name: string,\n readonly provider: UserProvider,\n private readonly container: Container,\n private readonly options: SessionGuardOptions = {},\n ) {}\n\n async user<T extends Authenticatable = Authenticatable>(): Promise<T | undefined> {\n if (this.#loggedOut) return undefined\n if (this.#user !== undefined) return this.#user as T\n\n const id = this.#session()?.get<unknown>(this.getName())\n if (id !== undefined && id !== null) this.#user = await this.provider.retrieveById(id)\n\n if (this.#user === undefined) {\n const recaller = this.#request()?.cookie(this.getRecallerName())\n if (recaller !== undefined) {\n const user = await this.#userFromRecaller(recaller)\n if (user !== undefined) {\n this.#user = user\n await this.#updateSession(user.getAuthIdentifier())\n await this.#dispatch(new Login(this.name, user, true))\n }\n }\n }\n return this.#user as T | undefined\n }\n\n /** The user already resolved in this request, without touching the provider (used by request.user()). */\n currentUser(): Authenticatable | undefined {\n return this.#loggedOut ? undefined : this.#user\n }\n\n async id(): Promise<unknown> {\n if (this.#loggedOut) return undefined\n return this.#user?.getAuthIdentifier() ?? this.#session()?.get<unknown>(this.getName()) ?? undefined\n }\n\n async check(): Promise<boolean> {\n return (await this.user()) !== undefined\n }\n\n async guest(): Promise<boolean> {\n return !(await this.check())\n }\n\n async validate(credentials: Credentials): Promise<boolean> {\n this.#lastAttempted = await this.provider.retrieveByCredentials(credentials)\n return this.#hasValidCredentials(this.#lastAttempted, credentials)\n }\n\n async attempt(credentials: Credentials, remember = false): Promise<boolean> {\n await this.#dispatch(new Attempting(this.name, credentials, remember))\n const user = await this.provider.retrieveByCredentials(credentials)\n this.#lastAttempted = user\n if (user !== undefined && (await this.#hasValidCredentials(user, credentials))) {\n if (this.options.rehashOnLogin !== false) {\n await (this.provider as { rehashPasswordIfRequired?(u: Authenticatable, c: Credentials): Promise<void> }).rehashPasswordIfRequired?.(\n user,\n credentials,\n )\n }\n await this.login(user, remember)\n return true\n }\n await this.#dispatch(new Failed(this.name, user, credentials))\n return false\n }\n\n /** Log in for this request only (no session, no cookie). */\n async once(credentials: Credentials): Promise<boolean> {\n await this.#dispatch(new Attempting(this.name, credentials, false))\n if (await this.validate(credentials)) {\n this.setUser(this.#lastAttempted!)\n return true\n }\n return false\n }\n\n async login(user: Authenticatable, remember = false): Promise<void> {\n await this.#updateSession(user.getAuthIdentifier())\n if (remember) {\n if (user.getRememberToken() === undefined) await this.#cycleRememberToken(user)\n this.#queueRecallerCookie(user)\n }\n await this.#dispatch(new Login(this.name, user, remember))\n this.setUser(user)\n }\n\n async loginUsingId(id: unknown, remember = false): Promise<Authenticatable | false> {\n const user = await this.provider.retrieveById(id)\n if (user === undefined) return false\n await this.login(user, remember)\n return user\n }\n\n /** Forgets the user, the session key and the remember cookie, and cycles the remember token. */\n async logout(): Promise<void> {\n const user = await this.user()\n this.#session()?.forget(this.getName())\n const jar = this.#jar()\n if (jar !== undefined && this.#request()?.cookie(this.getRecallerName()) !== undefined) {\n jar.queue(jar.forget(this.getRecallerName()))\n }\n if (user !== undefined && user.getRememberToken() !== undefined) await this.#cycleRememberToken(user)\n await this.#dispatch(new Logout(this.name, user))\n this.#user = undefined\n this.#loggedOut = true\n }\n\n hasUser(): boolean {\n return this.#user !== undefined\n }\n\n setUser(user: Authenticatable): void {\n this.#user = user\n this.#loggedOut = false\n }\n\n /** Whether the user was authenticated by the remember-me cookie. */\n viaRemember(): boolean {\n return this.#viaRemember\n }\n\n getLastAttempted(): Authenticatable | undefined {\n return this.#lastAttempted\n }\n\n /** The session key holding the user id. */\n getName(): string {\n return `login_${this.name}_${GUARD_HASH}`\n }\n\n /** The remember-me cookie name. */\n getRecallerName(): string {\n return `remember_${this.name}_${GUARD_HASH}`\n }\n\n async #hasValidCredentials(user: Authenticatable | undefined, credentials: Credentials): Promise<boolean> {\n const valid = user !== undefined && (await this.provider.validateCredentials(user, credentials))\n if (valid) await this.#dispatch(new Validated(this.name, user))\n return valid\n }\n\n async #userFromRecaller(recaller: string): Promise<Authenticatable | undefined> {\n const segments = recaller.split('|')\n if (this.#recallAttempted || segments.length !== 3 || segments[0] === '' || segments[1] === '') return undefined\n this.#recallAttempted = true\n const user = await this.provider.retrieveByToken(segments[0], segments[1]!)\n this.#viaRemember = user !== undefined\n return user\n }\n\n /** Stores the id and gives the session a new id (fixation), keeping its data and CSRF token. */\n async #updateSession(id: unknown): Promise<void> {\n const session = this.#session()\n if (session === undefined) return\n session.put(this.getName(), id)\n const store = session as Session & { migrate?(destroy?: boolean): Promise<void> }\n if (typeof store.migrate === 'function') await store.migrate(true)\n else await session.regenerate(true)\n }\n\n async #cycleRememberToken(user: Authenticatable): Promise<void> {\n await this.provider.updateRememberToken(user, Str.random(60))\n }\n\n #queueRecallerCookie(user: Authenticatable): void {\n const jar = this.#jar()\n if (jar === undefined) return\n const value = `${String(user.getAuthIdentifier())}|${user.getRememberToken() ?? ''}|${user.getAuthPassword()}`\n jar.queue(jar.make(this.getRecallerName(), value, this.options.rememberDuration ?? 576000))\n }\n\n #session(): Session | undefined {\n return this.#optional(Session)\n }\n\n #request(): HttpRequest | undefined {\n return this.container.bound(HttpRequest) ? this.container.make(HttpRequest) : undefined\n }\n\n #jar(): CookieJar | undefined {\n return this.#optional(CookieJar)\n }\n\n /** A scoped service, or undefined when it isn't bound or we're on the root container (CLI). */\n #optional<T>(token: Token<T>): T | undefined {\n if (!this.container.bound(token)) return undefined\n try {\n return this.container.make(token)\n } catch (error) {\n if (error instanceof BindingResolutionError) return undefined\n throw error\n }\n }\n\n async #dispatch(event: object): Promise<void> {\n if (this.container.bound(EventDispatcher)) await this.container.make(EventDispatcher).dispatch(event)\n }\n}\n","import {\n ConfigRepository,\n Hasher,\n HttpRequest,\n type AuthFactory,\n type Authenticatable,\n type Container,\n type Credentials,\n type Guard,\n type StatefulGuard,\n type UserProvider,\n} from '@orieljs/contracts'\nimport { currentContainer } from '@orieljs/container'\nimport { EloquentUserProvider, type AuthModel } from './EloquentUserProvider'\nimport { SessionGuard } from './guards/SessionGuard'\nimport { TokenGuard } from './guards/TokenGuard'\nimport { TokenRepository } from './tokens/PersonalAccessTokens'\n\nexport type GuardFactory = (name: string, config: Record<string, unknown>) => Guard\nexport type UserProviderFactory = (config: Record<string, unknown>) => UserProvider\n\ninterface ScopeState {\n guards: Map<string, Guard>\n defaultGuard: string | undefined\n resolverInstalled: boolean\n}\n\n/**\n * Laravel's AuthManager. A root singleton, but every container scope (request, job) gets its own guards and its\n * own shouldUse() default, so users never leak between concurrent requests. Guard methods called on the manager\n * (Auth.user(), Auth.attempt(), …) go to the default guard.\n */\nexport class AuthManager implements AuthFactory {\n readonly #customGuards = new Map<string, GuardFactory>()\n readonly #customProviders = new Map<string, UserProviderFactory>()\n readonly #scopes = new WeakMap<Container, ScopeState>()\n\n constructor(private readonly app: Container) {}\n\n guard(name?: string): StatefulGuard | Guard {\n return this.guardIn(this.#container(), name)\n }\n\n /** The guard for an explicit container (scope). */\n guardIn(container: Container, name?: string): StatefulGuard | Guard {\n const state = this.#state(container)\n const guardName = name ?? state.defaultGuard ?? this.getDefaultDriver()\n let guard = state.guards.get(guardName)\n if (guard === undefined) {\n guard = this.#resolve(guardName, container)\n state.guards.set(guardName, guard)\n this.#installUserResolver(container, state)\n }\n return guard\n }\n\n /** Make `name` the default guard for the rest of this request (the `auth:name` middleware calls it). */\n shouldUse(name: string): void {\n this.#state(this.#container()).defaultGuard = name\n }\n\n /** config('auth.defaults.guard'), default 'web'. */\n getDefaultDriver(): string {\n return this.#config().get<string>('auth.defaults.guard', 'web')\n }\n\n extend(driver: string, factory: GuardFactory): void {\n this.#customGuards.set(driver, factory)\n }\n\n provider(driver: string, factory: UserProviderFactory): void {\n this.#customProviders.set(driver, factory)\n }\n\n /** The user provider named in config('auth.providers') (default: auth.defaults.provider ?? 'users'). */\n createUserProvider(name?: string): UserProvider {\n const providerName = name ?? this.#config().get<string>('auth.defaults.provider', 'users')\n const config = this.#config().get<Record<string, unknown> | undefined>(`auth.providers.${providerName}`)\n if (config === undefined) throw new Error(`Authentication user provider [${providerName}] is not defined.`)\n const driver = String(config.driver ?? 'eloquent')\n const custom = this.#customProviders.get(driver)\n if (custom !== undefined) return custom(config)\n if (driver !== 'eloquent') throw new Error(`Authentication user provider [${driver}] is not defined.`)\n if (config.model === undefined || config.model === null) {\n throw new Error(`Authentication user provider [${providerName}] has no model: set auth.providers.${providerName}.model.`)\n }\n return new EloquentUserProvider(this.app.make(Hasher), config.model as AuthModel)\n }\n\n /** Forget the resolved guards of the current scope (tests). */\n forgetGuards(): void {\n this.#scopes.delete(this.#container())\n }\n\n // Guard methods, forwarded to the default guard (Laravel's AuthManager::__call).\n\n user<T extends Authenticatable = Authenticatable>(): Promise<T | undefined> {\n return this.guard().user<T>()\n }\n\n check(): Promise<boolean> {\n return this.guard().check()\n }\n\n guest(): Promise<boolean> {\n return this.guard().guest()\n }\n\n id(): Promise<unknown> {\n return this.guard().id()\n }\n\n validate(credentials: Credentials): Promise<boolean> {\n return this.guard().validate(credentials)\n }\n\n hasUser(): boolean {\n return this.guard().hasUser()\n }\n\n setUser(user: Authenticatable): void {\n this.guard().setUser(user)\n }\n\n async attempt(credentials: Credentials, remember = false): Promise<boolean> {\n return this.#stateful().attempt(credentials, remember)\n }\n\n async once(credentials: Credentials): Promise<boolean> {\n return this.#stateful().once(credentials)\n }\n\n async login(user: Authenticatable, remember = false): Promise<void> {\n return this.#stateful().login(user, remember)\n }\n\n async loginUsingId(id: unknown, remember = false): Promise<Authenticatable | false> {\n return this.#stateful().loginUsingId(id, remember)\n }\n\n async logout(): Promise<void> {\n return this.#stateful().logout()\n }\n\n viaRemember(): boolean {\n const guard = this.guard() as Guard & { viaRemember?(): boolean }\n return guard.viaRemember?.() ?? false\n }\n\n #resolve(name: string, container: Container): Guard {\n const config = this.#config().get<Record<string, unknown> | undefined>(`auth.guards.${name}`)\n if (config === undefined) throw new Error(`Auth guard [${name}] is not defined.`)\n const driver = String(config.driver)\n const custom = this.#customGuards.get(driver)\n if (custom !== undefined) return custom(name, config)\n const provider = this.createUserProvider(config.provider as string | undefined)\n if (driver === 'session') {\n return new SessionGuard(name, provider, container, {\n rememberDuration: (config.remember as number | undefined) ?? 576000,\n rehashOnLogin: this.#config().get<boolean>('hashing.rehash_on_login', true),\n })\n }\n if (driver === 'token') {\n return new TokenGuard(name, provider, container, this.app.make(TokenRepository), {\n expiration: this.#resolveExpiration(name, config.expiration),\n })\n }\n throw new Error(`Auth driver [${driver}] for guard [${name}] is not defined.`)\n }\n\n /**\n * Accepts a number or a numeric string (env() returns strings), so the rolling expiry is not silently disabled by\n * an ordinary config value. null/undefined means no rolling expiry; anything else that isn't finite is rejected.\n */\n #resolveExpiration(guard: string, expiration: unknown): number | null {\n if (expiration === null || expiration === undefined) return null\n const coerced = Number(expiration)\n if (!Number.isFinite(coerced)) {\n throw new Error(`Auth guard [${guard}]: [expiration] must be a number, got ${JSON.stringify(expiration)}.`)\n }\n return coerced\n }\n\n /** request.user() resolves synchronously from the guards of the request's scope (Laravel's user resolver). */\n #installUserResolver(container: Container, state: ScopeState): void {\n if (state.resolverInstalled || !container.bound(HttpRequest)) return\n state.resolverInstalled = true\n container.make(HttpRequest).setUserResolver((guard?: string) => {\n const resolved = this.guardIn(container, guard) as Guard & { currentUser?(): Authenticatable | undefined }\n return resolved.currentUser?.()\n })\n }\n\n #stateful(): StatefulGuard {\n const guard = this.guard()\n if (typeof (guard as Partial<StatefulGuard>).attempt !== 'function') {\n throw new Error('The default guard does not support attempt(), login() or logout() (it is not a stateful guard).')\n }\n return guard as StatefulGuard\n }\n\n #state(container: Container): ScopeState {\n let state = this.#scopes.get(container)\n if (state === undefined) {\n state = { guards: new Map(), defaultGuard: undefined, resolverInstalled: false }\n this.#scopes.set(container, state)\n }\n return state\n }\n\n #container(): Container {\n return currentContainer() ?? this.app\n }\n\n #config(): ConfigRepository {\n return this.app.make(ConfigRepository)\n }\n}\n","import { HttpRequest, type Authenticatable, type Container, type Credentials, type Guard, type UserProvider } from '@orieljs/contracts'\nimport { tokenableType, type PersonalAccessToken, type TokenRepository } from '../tokens/PersonalAccessTokens'\n\nexport interface TokenGuardOptions {\n /** Minutes a token lives after creation (null/undefined: until expires_at, or forever). */\n expiration?: number | null\n clock?: () => Date\n}\n\n/**\n * Sanctum's personal-access-token guard (`auth:token`): `Authorization: Bearer <id>|<secret>`. The token must exist,\n * match (constant-time SHA-256 comparison), be unexpired and belong to a user of the provider's model.\n */\nexport class TokenGuard implements Guard {\n #user: Authenticatable | undefined\n #token: PersonalAccessToken | undefined\n #resolved = false\n\n constructor(\n readonly name: string,\n readonly provider: UserProvider,\n private readonly container: Container,\n private readonly tokens: TokenRepository,\n private readonly options: TokenGuardOptions = {},\n ) {}\n\n async user<T extends Authenticatable = Authenticatable>(): Promise<T | undefined> {\n if (this.#user !== undefined || this.#resolved) return this.#user as T | undefined\n this.#resolved = true\n const bearer = this.container.bound(HttpRequest) ? this.container.make(HttpRequest).bearerToken() : undefined\n if (bearer === undefined || bearer === '') return undefined\n const found = await this.#authenticate(bearer)\n if (found === undefined) return undefined\n await this.tokens.touch(found.token)\n ;(found.user as Authenticatable & { withAccessToken?(token: PersonalAccessToken): unknown }).withAccessToken?.(found.token)\n this.#user = found.user\n this.#token = found.token\n return found.user as T\n }\n\n /** The user already resolved in this request (used by request.user()). */\n currentUser(): Authenticatable | undefined {\n return this.#user\n }\n\n /** The token the request authenticated with. */\n currentAccessToken(): PersonalAccessToken | undefined {\n return this.#token\n }\n\n async id(): Promise<unknown> {\n return (await this.user())?.getAuthIdentifier()\n }\n\n async check(): Promise<boolean> {\n return (await this.user()) !== undefined\n }\n\n async guest(): Promise<boolean> {\n return !(await this.check())\n }\n\n /** `{ token: '<id>|<secret>' }` is valid when it would authenticate someone. */\n async validate(credentials: Credentials): Promise<boolean> {\n return typeof credentials.token === 'string' && (await this.#authenticate(credentials.token)) !== undefined\n }\n\n hasUser(): boolean {\n return this.#user !== undefined\n }\n\n setUser(user: Authenticatable): void {\n this.#user = user\n this.#resolved = true\n }\n\n async #authenticate(plainText: string): Promise<{ user: Authenticatable; token: PersonalAccessToken } | undefined> {\n const token = await this.tokens.findToken(plainText)\n if (token === undefined || !this.#isValid(token)) return undefined\n const user = await this.provider.retrieveById(token.tokenableId)\n if (user === undefined || tokenableType(user) !== token.tokenableType) return undefined\n return { user, token }\n }\n\n #isValid(token: PersonalAccessToken): boolean {\n const now = (this.options.clock ?? (() => new Date()))().getTime()\n const expiresAt = token.expiresAt\n // A non-null expires_at that fails to parse counts as expired (fail closed), like the rule for created_at.\n const rawExpiresAt = token.attributes.expires_at\n if (rawExpiresAt !== null && rawExpiresAt !== undefined && expiresAt === undefined) return false\n if (expiresAt !== undefined && expiresAt.getTime() <= now) return false\n const expiration = this.options.expiration\n if (typeof expiration === 'number') {\n const createdAt = token.createdAt\n if (createdAt === undefined || createdAt.getTime() + expiration * 60_000 <= now) return false\n }\n return true\n }\n}\n","import { createHash } from 'node:crypto'\nimport { ClassRegistry, DatabaseManager, type Authenticatable, type Class, type DatabaseConnection, type Row } from '@orieljs/contracts'\nimport { currentContainer, inject } from '@orieljs/container'\nimport { Str } from '@orieljs/support'\nimport { parseStoredDate } from '../dates'\nimport { equals } from '../equals'\n\nconst sha256 = (value: string): string => createHash('sha256').update(value).digest('hex')\n\n/** The name stored in tokenable_type: the ClassRegistry name when registered, else the class name. */\nexport function tokenableType(user: object): string {\n const container = currentContainer()\n const cls = user.constructor as Class<unknown>\n const registered = container?.bound(ClassRegistry) ? container.make(ClassRegistry).nameOf(cls) : undefined\n return registered ?? cls.name\n}\n\n/** A row of personal_access_tokens (Sanctum's PersonalAccessToken). */\nexport class PersonalAccessToken {\n constructor(\n readonly attributes: Row,\n private readonly repository: TokenRepository,\n ) {}\n\n get id(): unknown {\n return this.attributes.id\n }\n\n get name(): string {\n return String(this.attributes.name ?? '')\n }\n\n get abilities(): string[] {\n const abilities = this.attributes.abilities\n if (Array.isArray(abilities)) return abilities.map(String)\n try {\n const parsed: unknown = JSON.parse(String(abilities ?? '[]'))\n return Array.isArray(parsed) ? parsed.map(String) : []\n } catch {\n return []\n }\n }\n\n get tokenableType(): string {\n return String(this.attributes.tokenable_type ?? '')\n }\n\n get tokenableId(): unknown {\n return this.attributes.tokenable_id\n }\n\n get lastUsedAt(): Date | undefined {\n return parseStoredDate(this.attributes.last_used_at)\n }\n\n get expiresAt(): Date | undefined {\n return parseStoredDate(this.attributes.expires_at)\n }\n\n get createdAt(): Date | undefined {\n return parseStoredDate(this.attributes.created_at)\n }\n\n /** Whether the token grants the ability ('*' grants everything). */\n can(ability: string): boolean {\n const abilities = this.abilities\n return abilities.includes('*') || abilities.includes(ability)\n }\n\n cant(ability: string): boolean {\n return !this.can(ability)\n }\n\n delete(): Promise<void> {\n return this.repository.delete(this)\n }\n}\n\nexport interface NewAccessToken {\n accessToken: PersonalAccessToken\n /** `<id>|<secret>`: shown to the user once; only the SHA-256 of the secret is stored. */\n plainTextToken: string\n}\n\n/** Reads and writes personal_access_tokens through the DatabaseManager contract. */\nexport class TokenRepository {\n constructor(\n private readonly connection: () => DatabaseConnection = () => inject(DatabaseManager),\n private readonly table = 'personal_access_tokens',\n private readonly clock: () => Date = () => new Date(),\n ) {}\n\n async create(user: Authenticatable, name: string, abilities: string[] = ['*'], expiresAt?: Date): Promise<NewAccessToken> {\n const secret = Str.random(40)\n const now = this.clock()\n const attributes: Row = {\n tokenable_type: tokenableType(user),\n tokenable_id: user.getAuthIdentifier(),\n name,\n token: sha256(secret),\n abilities: JSON.stringify(abilities),\n last_used_at: null,\n expires_at: expiresAt ?? null,\n created_at: now,\n updated_at: now,\n }\n const id = await this.#query().insertGetId(attributes)\n return { accessToken: new PersonalAccessToken({ id, ...attributes }, this), plainTextToken: `${id}|${secret}` }\n }\n\n /** Finds a token from its plain text (`<id>|<secret>`, or a bare secret), comparing hashes in constant time. */\n async findToken(plainText: string): Promise<PersonalAccessToken | undefined> {\n const separator = plainText.indexOf('|')\n if (separator === -1) {\n const row = await this.#query().where('token', sha256(plainText)).first()\n return row === undefined ? undefined : new PersonalAccessToken(row, this)\n }\n const id = plainText.slice(0, separator)\n const secret = plainText.slice(separator + 1)\n if (id === '' || secret === '') return undefined\n const row = await this.#query().where('id', id).first()\n if (row === undefined || typeof row.token !== 'string' || !equals(row.token, sha256(secret))) return undefined\n return new PersonalAccessToken(row, this)\n }\n\n /** Records the token's use (last_used_at). */\n async touch(token: PersonalAccessToken): Promise<void> {\n const now = this.clock()\n token.attributes.last_used_at = now\n await this.#query().where('id', token.id).update({ last_used_at: now })\n }\n\n async tokensFor(user: Authenticatable): Promise<PersonalAccessToken[]> {\n const rows = await this.#query().where('tokenable_type', tokenableType(user)).where('tokenable_id', user.getAuthIdentifier()).get()\n return rows.all().map((row) => new PersonalAccessToken(row, this))\n }\n\n async delete(token: PersonalAccessToken): Promise<void> {\n await this.#query().where('id', token.id).delete()\n }\n\n /** Revokes every token of the user. */\n async revokeAll(user: Authenticatable): Promise<number> {\n return this.#query().where('tokenable_type', tokenableType(user)).where('tokenable_id', user.getAuthIdentifier()).delete()\n }\n\n #query() {\n return this.connection().table<Row>(this.table)\n }\n}\n\n/** createToken(user, name, abilities?, expiresAt?) through the bound TokenRepository. */\nexport function createToken(user: Authenticatable, name: string, abilities?: string[], expiresAt?: Date): Promise<NewAccessToken> {\n return inject(TokenRepository).create(user, name, abilities, expiresAt)\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AuthenticatableConstructor = new (...args: any[]) => Authenticatable\n\n/** Sanctum's HasApiTokens: `class User extends HasApiTokens(AuthenticatableModel(Model)) {}`. */\nexport function HasApiTokens<TBase extends AuthenticatableConstructor>(Base: TBase) {\n return class WithApiTokens extends Base {\n /** The token the current request authenticated with (set by the token guard). */\n accessToken: PersonalAccessToken | undefined = undefined\n\n createToken(name: string, abilities?: string[], expiresAt?: Date): Promise<NewAccessToken> {\n return createToken(this, name, abilities, expiresAt)\n }\n\n tokens(): Promise<PersonalAccessToken[]> {\n return inject(TokenRepository).tokensFor(this)\n }\n\n tokenCan(ability: string): boolean {\n return this.accessToken?.can(ability) ?? false\n }\n\n tokenCant(ability: string): boolean {\n return !this.tokenCan(ability)\n }\n\n currentAccessToken(): PersonalAccessToken | undefined {\n return this.accessToken\n }\n\n withAccessToken(token: PersonalAccessToken | undefined): this {\n this.accessToken = token\n return this\n }\n }\n}\n","/** Database's zoneless UTC format: 'Y-m-d H:i:s', a 'T' separator and fractional seconds allowed. */\nconst ZONELESS = /^\\d{4}-\\d{2}-\\d{2}[ T]\\d{2}:\\d{2}(:\\d{2}(\\.\\d+)?)?$/\n\n/**\n * A timestamp read back from the database. Database writes Dates as zoneless UTC strings ('2026-09-25 04:30:00')\n * and its drivers return strings, so a zoneless string is UTC, never local time (a local parse makes every reset\n * token look hours old east of UTC). Dates pass through, numbers are epoch milliseconds, strings with a zone keep\n * it. null, undefined, '' and unparseable values give undefined.\n */\nexport function parseStoredDate(value: unknown): Date | undefined {\n if (value === null || value === undefined || value === '') return undefined\n let date: Date\n if (value instanceof Date) date = value\n else if (typeof value === 'number') date = new Date(value)\n else {\n const text = String(value)\n date = ZONELESS.test(text) ? new Date(`${text.replace(' ', 'T')}Z`) : new Date(text)\n }\n return Number.isNaN(date.getTime()) ? undefined : date\n}\n","/**\n * Migration text for the application skeleton (Auth doesn't own migrations: Database does, and its contract has no\n * migration-path mechanism). Laravel 11's 0001_01_01_000000_create_users_table: users, password_reset_tokens and\n * sessions in one file.\n */\nexport const USERS_TABLE_MIGRATION = `import { Migration, Schema } from '@orieljs/framework'\n\nexport default class extends Migration {\n async up() {\n await Schema.create('users', (t) => {\n t.id()\n t.string('name')\n t.string('email').unique()\n t.timestamp('email_verified_at').nullable()\n t.string('password')\n t.rememberToken()\n t.timestamps()\n })\n\n await Schema.create('password_reset_tokens', (t) => {\n t.string('email').primary()\n t.string('token')\n t.timestamp('created_at').nullable()\n })\n\n await Schema.create('sessions', (t) => {\n t.string('id').primary()\n t.foreignId('user_id').nullable().index()\n t.string('ip_address', 45).nullable()\n t.text('user_agent').nullable()\n t.longText('payload')\n t.integer('last_activity').index()\n })\n }\n\n async down() {\n await Schema.dropIfExists('users')\n await Schema.dropIfExists('password_reset_tokens')\n await Schema.dropIfExists('sessions')\n }\n}\n`\n\n/** Sanctum's create_personal_access_tokens_table (written by install:api). */\nexport const PERSONAL_ACCESS_TOKENS_MIGRATION = `import { Migration, Schema } from '@orieljs/framework'\n\nexport default class extends Migration {\n async up() {\n await Schema.create('personal_access_tokens', (t) => {\n t.id()\n t.morphs('tokenable')\n t.string('name')\n t.string('token', 64).unique()\n t.text('abilities').nullable()\n t.timestamp('last_used_at').nullable()\n t.timestamp('expires_at').nullable()\n t.timestamps()\n })\n }\n\n async down() {\n await Schema.dropIfExists('personal_access_tokens')\n }\n}\n`\n","import { AuthorizationError } from '../errors'\n\n/** Laravel's Illuminate\\Auth\\Access\\Response: what an ability or policy method may return instead of a boolean. */\nexport class GateResponse {\n readonly #allowed: boolean\n readonly #message: string | undefined\n readonly #code: string | undefined\n readonly #status: number | undefined\n\n constructor(allowed: boolean, message?: string, code?: string, status?: number) {\n this.#allowed = allowed\n this.#message = message\n this.#code = code\n this.#status = status\n }\n\n static allow(message?: string, code?: string): GateResponse {\n return new GateResponse(true, message, code)\n }\n\n static deny(message?: string, code?: string): GateResponse {\n return new GateResponse(false, message, code)\n }\n\n static denyWithStatus(status: number, message?: string, code?: string): GateResponse {\n return new GateResponse(false, message, code, status)\n }\n\n static denyAsNotFound(message?: string, code?: string): GateResponse {\n return GateResponse.denyWithStatus(404, message, code)\n }\n\n allowed(): boolean {\n return this.#allowed\n }\n\n denied(): boolean {\n return !this.#allowed\n }\n\n message(): string | undefined {\n return this.#message\n }\n\n code(): string | undefined {\n return this.#code\n }\n\n status(): number | undefined {\n return this.#status\n }\n\n /** Throws an AuthorizationError (403, or the chosen status) when denied. */\n authorize(): this {\n if (this.denied()) throw new AuthorizationError(this.#message, this.#status ?? 403, this.#code)\n return this\n }\n}\n","import {\n AuthFactory,\n ClassRegistry,\n type AbilityCallback,\n type Authenticatable,\n type Class,\n type Gate as GateContract,\n} from '@orieljs/contracts'\nimport { BindingResolutionError, currentContainer } from '@orieljs/container'\nimport { Str } from '@orieljs/support'\nimport { GateResponse } from './Response'\n\nconst GUESTS = Symbol.for('oriel:auth.allowGuests')\n\n/** Let an ability callback run for guests (its user argument may be undefined). */\nexport function allowGuests<T extends AbilityCallback>(callback: T): T {\n Object.defineProperty(callback, GUESTS, { value: true })\n return callback\n}\n\ntype Result = boolean | GateResponse | undefined | null | void\ntype AbilityResult = Result | Promise<Result>\nexport type GateAbility =\n | ((user: Authenticatable | undefined, ...args: unknown[]) => AbilityResult)\n | readonly [PolicyClass, string]\nexport type BeforeCallback = (user: Authenticatable | undefined, ability: string, ...args: unknown[]) => AbilityResult\nexport type AfterCallback = (user: Authenticatable | undefined, ability: string, result: boolean | GateResponse | undefined, ...args: unknown[]) => AbilityResult\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type PolicyClass = (new () => any) & { allowGuests?: boolean | string[] }\n\ninterface GateState {\n abilities: Map<string, GateAbility>\n policies: Map<Class<unknown>, PolicyClass>\n discovered: Map<string, PolicyClass>\n before: BeforeCallback[]\n after: AfterCallback[]\n}\n\n/** The user of the current scope's default guard; guests (and the CLI root container) resolve to undefined. */\nasync function defaultUser(): Promise<Authenticatable | undefined> {\n const container = currentContainer()\n if (container === undefined || !container.bound(AuthFactory)) return undefined\n try {\n return await container.make(AuthFactory).guard().user()\n } catch (error) {\n if (error instanceof BindingResolutionError) return undefined\n throw error\n }\n}\n\nconst normalize = (result: Result): boolean | GateResponse | undefined =>\n result === null || result === undefined ? undefined : result instanceof GateResponse ? result : result === true\n\n/** The last segment of a class-like name: 'App\\\\Models\\\\Post', 'App.Models.Post' and 'Post' all give 'Post'. */\nconst baseName = (name: string): string => name.split(/[\\\\/.]/).at(-1) ?? name\n\n/**\n * Laravel's Gate (Illuminate\\Auth\\Access\\Gate; the `Gate` export of this package is the facade): abilities, policies (explicit or discovered), before/after callbacks. Ability callbacks and policy\n * methods are not called for guests unless they opt in (allowGuests(), or a policy's `static allowGuests`).\n */\nexport class AccessGate implements GateContract {\n readonly #state: GateState\n readonly #user: () => Promise<Authenticatable | undefined>\n\n constructor(userResolver: () => Promise<Authenticatable | undefined> = defaultUser, state?: GateState) {\n this.#user = userResolver\n this.#state = state ?? { abilities: new Map(), policies: new Map(), discovered: new Map(), before: [], after: [] }\n }\n\n define(ability: string, callback: AbilityCallback | GateAbility): this {\n this.#state.abilities.set(ability, callback as GateAbility)\n return this\n }\n\n has(...abilities: string[]): boolean {\n return abilities.every((ability) => this.#state.abilities.has(ability))\n }\n\n policy(model: Class<unknown>, policy: Class<unknown>): this {\n this.#state.policies.set(model, policy as PolicyClass)\n return this\n }\n\n /** Register a discovered policy for models named `modelName` (see discoverPolicies). */\n discoveredPolicy(modelName: string, policy: PolicyClass): this {\n this.#state.discovered.set(modelName, policy)\n return this\n }\n\n before(callback: BeforeCallback): this {\n this.#state.before.push(callback)\n return this\n }\n\n after(callback: AfterCallback): this {\n this.#state.after.push(callback)\n return this\n }\n\n async allows(ability: string, ...args: unknown[]): Promise<boolean> {\n return (await this.inspect(ability, ...args)).allowed()\n }\n\n async denies(ability: string, ...args: unknown[]): Promise<boolean> {\n return !(await this.allows(ability, ...args))\n }\n\n /** Every ability is allowed. */\n async check(abilities: string | string[], ...args: unknown[]): Promise<boolean> {\n for (const ability of Array.isArray(abilities) ? abilities : [abilities]) if (!(await this.allows(ability, ...args))) return false\n return true\n }\n\n async any(abilities: string[], ...args: unknown[]): Promise<boolean> {\n for (const ability of abilities) if (await this.allows(ability, ...args)) return true\n return false\n }\n\n async none(abilities: string[], ...args: unknown[]): Promise<boolean> {\n return !(await this.any(abilities, ...args))\n }\n\n async authorize(ability: string, ...args: unknown[]): Promise<void> {\n ;(await this.inspect(ability, ...args)).authorize()\n }\n\n /** The decision as a GateResponse (message, code and status included). */\n async inspect(ability: string, ...args: unknown[]): Promise<GateResponse> {\n const result = await this.raw(ability, ...args)\n return result instanceof GateResponse ? result : result === true ? GateResponse.allow() : GateResponse.deny()\n }\n\n /** before callbacks, then the policy or ability, then after callbacks (which only fill an undecided result). */\n async raw(ability: string, ...args: unknown[]): Promise<boolean | GateResponse | undefined> {\n const user = await this.#user()\n let result: boolean | GateResponse | undefined\n for (const before of this.#state.before) {\n result = normalize(await before(user, ability, ...args))\n if (result !== undefined) break\n }\n if (result === undefined) result = await this.#callAuthCallback(user, ability, args)\n for (const after of this.#state.after) {\n const afterResult = normalize(await after(user, ability, result, ...args))\n result ??= afterResult\n }\n return result\n }\n\n forUser(user: Authenticatable | undefined): AccessGate {\n return new AccessGate(async () => user, this.#state)\n }\n\n abilities(): Record<string, GateAbility> {\n return Object.fromEntries(this.#state.abilities)\n }\n\n policies(): Map<Class<unknown>, PolicyClass> {\n return new Map(this.#state.policies)\n }\n\n /** The policy class for a model instance, a model class, or a model name. */\n getPolicyFor(target: unknown): PolicyClass | undefined {\n if (typeof target === 'string') {\n const name = baseName(target)\n for (const [model, policy] of this.#state.policies) if (model.name === name) return policy\n return this.#state.discovered.get(name)\n }\n let cls: unknown = typeof target === 'function' ? target : typeof target === 'object' && target !== null ? target.constructor : undefined\n for (; typeof cls === 'function' && cls !== Object && cls !== Function.prototype; cls = Object.getPrototypeOf(cls)) {\n const explicit = this.#state.policies.get(cls as Class<unknown>)\n if (explicit !== undefined) return explicit\n for (const name of this.#namesOf(cls as Class<unknown>)) {\n const discovered = this.#state.discovered.get(name)\n if (discovered !== undefined) return discovered\n }\n }\n return undefined\n }\n\n async #callAuthCallback(user: Authenticatable | undefined, ability: string, args: unknown[]): Promise<boolean | GateResponse | undefined> {\n const policyClass = args.length > 0 ? this.getPolicyFor(args[0]) : undefined\n if (policyClass !== undefined) {\n const policy = this.#instantiate(policyClass)\n const guestsAllowed = (method: string) =>\n user !== undefined || policyClass.allowGuests === true || (Array.isArray(policyClass.allowGuests) && policyClass.allowGuests.includes(method))\n if (typeof policy.before === 'function' && guestsAllowed('before')) {\n const before = normalize(await policy.before(user, ability, ...args))\n if (before !== undefined) return before\n }\n const method = Str.camel(ability)\n if (typeof policy[method] === 'function') {\n if (!guestsAllowed(method)) return false\n // A class or a model name as the first argument only selects the policy (Laravel removes it).\n const policyArgs = typeof args[0] === 'function' || typeof args[0] === 'string' ? args.slice(1) : args\n return normalize(await policy[method](user, ...policyArgs))\n }\n }\n const callback = this.#state.abilities.get(ability)\n if (callback === undefined) return undefined\n if (Array.isArray(callback)) {\n const [cls, method] = callback as readonly [PolicyClass, string]\n const target = this.#instantiate(cls)\n if (typeof target[method] !== 'function') return false\n if (user === undefined && cls.allowGuests !== true && !(Array.isArray(cls.allowGuests) && cls.allowGuests.includes(method))) return false\n return normalize(await target[method](user, ...args))\n }\n const fn = callback as (user: Authenticatable | undefined, ...args: unknown[]) => AbilityResult\n if (user === undefined && (fn as unknown as Record<symbol, unknown>)[GUESTS] !== true) return false\n return normalize(await fn(user, ...args))\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n #instantiate(cls: PolicyClass): any {\n const container = currentContainer()\n return container === undefined ? new cls() : container.make(cls)\n }\n\n #namesOf(cls: Class<unknown>): string[] {\n const container = currentContainer()\n const registered = container?.bound(ClassRegistry) ? container.make(ClassRegistry).nameOf(cls) : undefined\n return registered === undefined ? [cls.name] : [baseName(registered), cls.name]\n }\n}\n","import { Gate, type HttpRequest, type Middleware, type Next } from '@orieljs/contracts'\nimport { inject } from '@orieljs/container'\n\n/**\n * Laravel's Authorize middleware (`can:update,post`). Each extra parameter is a quoted literal ('\"draft\"'), else the\n * route parameter of that name (the bound model), else the name itself (a model name such as `Post`, which selects\n * the policy).\n */\nexport class Authorize implements Middleware {\n readonly #gate = inject(Gate)\n\n async handle(request: HttpRequest, next: Next, ability?: string, ...models: string[]): Promise<Response> {\n if (ability === undefined || ability === '') throw new Error('The can middleware needs an ability: can:update,post.')\n const args = models.map((model) => {\n const quoted = /^['\"](.*)['\"]$/.exec(model.trim())\n if (quoted) return quoted[1]\n const bound = request.route<unknown>(model)\n return bound === undefined || bound === null ? model.trim() : bound\n })\n await this.#gate.authorize(ability, ...args)\n return next(request)\n }\n}\n","import { createHmac } from 'node:crypto'\nimport type { DatabaseConnection, Hasher, Row } from '@orieljs/contracts'\nimport { Str } from '@orieljs/support'\nimport { parseStoredDate } from '../dates'\n\n/** What the token repository needs from a user (CanResetPassword). */\nexport interface CanResetPasswordUser {\n getEmailForPasswordReset(): string\n}\n\n/**\n * Laravel's DatabaseTokenRepository: one row per email in `password_reset_tokens`, the token stored hashed with\n * the Hasher. `expires` and `throttle` are in seconds.\n */\nexport class DatabaseTokenRepository {\n constructor(\n private readonly connection: () => DatabaseConnection,\n private readonly hasher: Hasher,\n private readonly table: string,\n private readonly hashKey: Uint8Array | string,\n private readonly expires = 3600,\n private readonly throttle = 60,\n private readonly clock: () => Date = () => new Date(),\n ) {}\n\n /** Replaces the user's token with a new one and returns it in plain text. */\n async create(user: CanResetPasswordUser): Promise<string> {\n const email = user.getEmailForPasswordReset()\n await this.#query().where('email', email).delete()\n const token = createHmac('sha256', this.hashKey).update(Str.random(40)).digest('hex')\n await this.#query().insert({ email, token: await this.hasher.make(token), created_at: this.clock() })\n return token\n }\n\n /** Whether the token matches the user's unexpired record. */\n async exists(user: CanResetPasswordUser, token: string): Promise<boolean> {\n const record = await this.#record(user)\n if (record === undefined || typeof record.token !== 'string' || this.#expired(record.created_at)) return false\n return this.hasher.check(token, record.token)\n }\n\n /** Whether a token was created less than `throttle` seconds ago. */\n async recentlyCreatedToken(user: CanResetPasswordUser): Promise<boolean> {\n if (this.throttle <= 0) return false\n const createdAt = parseStoredDate((await this.#record(user))?.created_at)\n return createdAt !== undefined && createdAt.getTime() + this.throttle * 1000 > this.clock().getTime()\n }\n\n async delete(user: CanResetPasswordUser): Promise<void> {\n await this.#query().where('email', user.getEmailForPasswordReset()).delete()\n }\n\n async deleteExpired(): Promise<void> {\n await this.#query().where('created_at', '<', new Date(this.clock().getTime() - this.expires * 1000)).delete()\n }\n\n #record(user: CanResetPasswordUser): Promise<Row | undefined> {\n return this.#query().where('email', user.getEmailForPasswordReset()).first()\n }\n\n /** A created_at that can't be read counts as expired (fail closed). */\n #expired(createdAt: unknown): boolean {\n const created = parseStoredDate(createdAt)\n return created === undefined || created.getTime() + this.expires * 1000 < this.clock().getTime()\n }\n\n #query() {\n return this.connection().table<Row>(this.table)\n }\n}\n","import {\n AuthFactory,\n ConfigRepository,\n DatabaseManager,\n Hasher,\n type Authenticatable,\n type Container,\n type Credentials,\n type PasswordBroker as PasswordBrokerContract,\n type PasswordStatus,\n type UserProvider,\n} from '@orieljs/contracts'\nimport { DatabaseTokenRepository, type CanResetPasswordUser } from './DatabaseTokenRepository'\n\ntype ResettableUser = Authenticatable & CanResetPasswordUser & { sendPasswordResetNotification?(token: string): Promise<void> }\n\n/** Laravel's PasswordBroker. */\nexport class PasswordBroker implements PasswordBrokerContract {\n constructor(\n readonly tokens: DatabaseTokenRepository,\n readonly users: UserProvider,\n ) {}\n\n /** Creates a token and sends it (through `callback`, else user.sendPasswordResetNotification()). */\n async sendResetLink(\n credentials: Credentials,\n callback?: (user: Authenticatable, token: string) => Promise<void> | void,\n ): Promise<PasswordStatus> {\n const user = await this.getUser(credentials)\n if (user === undefined) return 'passwords.user'\n if (await this.tokens.recentlyCreatedToken(user)) return 'passwords.throttled'\n const token = await this.tokens.create(user)\n if (callback !== undefined) await callback(user, token)\n else if (typeof user.sendPasswordResetNotification === 'function') await user.sendPasswordResetNotification(token)\n else throw new Error('User must implement sendPasswordResetNotification() (use AuthenticatableModel).')\n return 'passwords.sent'\n }\n\n /** Checks the token, then lets `callback` save the new password, then deletes the token. */\n async reset(credentials: Credentials, callback: (user: Authenticatable, password: string) => Promise<void>): Promise<PasswordStatus> {\n const user = await this.getUser(credentials)\n if (user === undefined) return 'passwords.user'\n const token = credentials.token\n if (typeof token !== 'string' || !(await this.tokens.exists(user, token))) return 'passwords.token'\n await callback(user, String(credentials.password ?? ''))\n await this.tokens.delete(user)\n return 'passwords.reset'\n }\n\n /** The user for the credentials (the token is never part of the query; password keys are ignored by the provider). */\n async getUser(credentials: Credentials): Promise<ResettableUser | undefined> {\n const { token: _token, ...rest } = credentials\n const user = (await this.users.retrieveByCredentials(rest)) as ResettableUser | undefined\n if (user !== undefined && typeof user.getEmailForPasswordReset !== 'function') {\n throw new Error('User must implement CanResetPassword interface.')\n }\n return user\n }\n\n createToken(user: ResettableUser): Promise<string> {\n return this.tokens.create(user)\n }\n\n deleteToken(user: ResettableUser): Promise<void> {\n return this.tokens.delete(user)\n }\n\n tokenExists(user: ResettableUser, token: string): Promise<boolean> {\n return this.tokens.exists(user, token)\n }\n}\n\ninterface BrokerConfig {\n provider?: string\n table?: string\n /** Minutes a token is valid. */\n expire?: number\n /** Seconds before another token may be created. */\n throttle?: number\n connection?: string | null\n}\n\n/** Laravel's PasswordBrokerManager: brokers from config('auth.passwords'). */\nexport class PasswordBrokerManager {\n readonly #brokers = new Map<string, PasswordBroker>()\n\n constructor(private readonly app: Container) {}\n\n broker(name?: string): PasswordBroker {\n const config = this.app.make(ConfigRepository)\n const brokerName = name ?? config.get<string>('auth.defaults.passwords', 'users')\n let broker = this.#brokers.get(brokerName)\n if (broker === undefined) {\n broker = this.#resolve(brokerName)\n this.#brokers.set(brokerName, broker)\n }\n return broker\n }\n\n #resolve(name: string): PasswordBroker {\n const config = this.app.make(ConfigRepository)\n const settings = config.get<BrokerConfig | undefined>(`auth.passwords.${name}`)\n if (settings === undefined) throw new Error(`Password resetter [${name}] is not defined.`)\n const key = String(config.get('app.key', ''))\n const hashKey = key.startsWith('base64:') ? new Uint8Array(Buffer.from(key.slice(7), 'base64')) : key\n const tokens = new DatabaseTokenRepository(\n () => this.app.make(DatabaseManager).connection(settings.connection ?? undefined),\n this.app.make(Hasher),\n settings.table ?? 'password_reset_tokens',\n hashKey,\n (settings.expire ?? 60) * 60,\n settings.throttle ?? 0,\n )\n const auth = this.app.make(AuthFactory) as AuthFactory & { createUserProvider(name?: string): UserProvider }\n return new PasswordBroker(tokens, auth.createUserProvider(settings.provider))\n }\n}\n","import { AuthFactory, ConfigRepository, type HttpRequest, type Middleware, type Next } from '@orieljs/contracts'\nimport { inject } from '@orieljs/container'\nimport { AuthenticationError } from '../errors'\n\n/**\n * Laravel's Authenticate middleware (`auth`, `auth:web,token`). The first guard that has a user becomes the default\n * guard for the request; otherwise an AuthenticationError (401, or a redirect to the login page) is thrown.\n */\nexport class Authenticate implements Middleware {\n protected readonly auth = inject(AuthFactory)\n protected readonly config = inject(ConfigRepository)\n\n async handle(request: HttpRequest, next: Next, ...guards: string[]): Promise<Response> {\n await this.authenticate(request, guards)\n return next(request)\n }\n\n protected async authenticate(request: HttpRequest, guards: string[]): Promise<void> {\n for (const guard of guards.length === 0 ? [undefined] : guards) {\n if (await this.auth.guard(guard).check()) {\n if (guard !== undefined) this.auth.shouldUse(guard)\n return\n }\n }\n this.unauthenticated(request, guards)\n }\n\n protected unauthenticated(request: HttpRequest, guards: string[]): never {\n throw new AuthenticationError('Unauthenticated.', guards, request.expectsJson() ? undefined : this.redirectTo(request))\n }\n\n /** config('http.redirect_guests_to') (set by withMiddleware(m => m.redirectGuestsTo(...))); Http falls back to route('login'). */\n protected redirectTo(request: HttpRequest): string | undefined {\n const target = this.config.get<unknown>('http.redirect_guests_to')\n if (typeof target === 'function') return String((target as (r: HttpRequest) => string)(request))\n return typeof target === 'string' && target !== '' ? target : undefined\n }\n}\n","import { AuthFactory, ConfigRepository, Container, UrlGenerator, type HttpRequest, type Middleware, type Next } from '@orieljs/contracts'\nimport { inject } from '@orieljs/container'\nimport { redirectTo } from './redirect'\n\n/** Laravel's RedirectIfAuthenticated (`guest`): signed-in users are sent to their home page. */\nexport class RedirectIfAuthenticated implements Middleware {\n protected readonly auth = inject(AuthFactory)\n protected readonly config = inject(ConfigRepository)\n readonly #container = inject(Container)\n\n async handle(request: HttpRequest, next: Next, ...guards: string[]): Promise<Response> {\n for (const guard of guards.length === 0 ? [undefined] : guards) {\n if (await this.auth.guard(guard).check()) return redirectTo(this.#container, request, this.redirectTo(request))\n }\n return next(request)\n }\n\n /** config('http.redirect_users_to'), then route('dashboard'), then route('home'), then '/'. */\n protected redirectTo(request: HttpRequest): string {\n const target = this.config.get<unknown>('http.redirect_users_to')\n if (typeof target === 'function') return String((target as (r: HttpRequest) => string)(request))\n if (typeof target === 'string' && target !== '') return target\n if (this.#container.bound(UrlGenerator)) {\n const url = this.#container.make(UrlGenerator)\n for (const name of ['dashboard', 'home']) if (url.hasRoute(name)) return url.route(name)\n }\n return '/'\n }\n}\n","import { Redirector, type Container, type HttpRequest } from '@orieljs/contracts'\n\n/** A redirect through Http's Redirector when bound (guest() remembers the intended URL), else a bare 302. */\nexport async function redirectTo(container: Container, request: HttpRequest, url: string, guest = false): Promise<Response> {\n if (container.bound(Redirector)) {\n const redirector = container.make(Redirector) as Redirector & { guest?(path: string): { toResponse(r: unknown): unknown } }\n const redirect = guest && typeof redirector.guest === 'function' ? redirector.guest(url) : redirector.to(url)\n return (await redirect.toResponse(request)) as Response\n }\n return new Response(null, { status: 302, headers: { Location: url } })\n}\n","import { AuthFactory, Container, UrlGenerator, type HttpRequest, type Middleware, type Next } from '@orieljs/contracts'\nimport { inject } from '@orieljs/container'\nimport { AuthorizationError } from '../errors'\nimport { redirectTo } from './redirect'\n\n/** Laravel's EnsureEmailIsVerified (`verified`, `verified:route.name`). */\nexport class EnsureEmailIsVerified implements Middleware {\n protected readonly auth = inject(AuthFactory)\n readonly #container = inject(Container)\n\n async handle(request: HttpRequest, next: Next, redirectToRoute?: string): Promise<Response> {\n const user = (await this.auth.guard().user()) as { hasVerifiedEmail?(): boolean } | undefined\n if (user === undefined || (typeof user.hasVerifiedEmail === 'function' && !user.hasVerifiedEmail())) {\n if (request.expectsJson()) throw new AuthorizationError('Your email address is not verified.', 403)\n return redirectTo(this.#container, request, this.#noticeUrl(redirectToRoute ?? 'verification.notice'), true)\n }\n return next(request)\n }\n\n #noticeUrl(route: string): string {\n if (this.#container.bound(UrlGenerator)) {\n const url = this.#container.make(UrlGenerator)\n if (url.hasRoute(route)) return url.route(route)\n }\n return '/email/verify'\n }\n}\n","import { readdir } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport type { AccessGate, PolicyClass } from './Access/Gate'\n\nconst POLICY_FILE = /^([A-Za-z0-9_]+)Policy\\.(ts|mts|js|mjs)$/\n\n/**\n * Policy auto-discovery (Laravel's guessPolicyNamesUsing): `app/Policies/PostPolicy.ts` authorizes models named\n * `Post`. The policy is the default export, or the export named after the file. Returns the model names found.\n */\nexport async function discoverPolicies(directory: string, gate: AccessGate): Promise<string[]> {\n const files = await readdir(directory).catch(() => [] as string[])\n const found: string[] = []\n for (const file of files.sort()) {\n const match = POLICY_FILE.exec(file)\n if (match === null || file.endsWith('.d.ts')) continue\n const module = (await import(pathToFileURL(join(directory, file)).href)) as Record<string, unknown>\n const policy = module.default ?? module[`${match[1]}Policy`]\n if (typeof policy !== 'function') continue\n gate.discoveredPolicy(match[1]!, policy as PolicyClass)\n found.push(match[1]!)\n }\n return found\n}\n","import { AuthFactory, Gate as GateToken, PasswordBroker as PasswordBrokerToken, type Guard, type StatefulGuard, type Token } from '@orieljs/contracts'\nimport { inject } from '@orieljs/container'\nimport { facade } from '@orieljs/support'\nimport type { AccessGate } from './Access/Gate'\nimport type { AuthManager } from './AuthManager'\nimport { PasswordBrokerManager, type PasswordBroker } from './Passwords/PasswordBroker'\n\n/** The Auth facade: the AuthManager (guard(), extend(), and the default guard's user()/check()/attempt()/…). */\nexport const Auth = facade(AuthFactory as unknown as Token<AuthManager>)\n\n/** The Gate facade. */\nexport const Gate = facade(GateToken as unknown as Token<AccessGate>)\n\n/** The Password facade: the default password broker, plus broker(name). */\nexport const Password = facade(PasswordBrokerToken as unknown as Token<PasswordBroker>, {\n broker: (name?: string): PasswordBroker => inject(PasswordBrokerManager).broker(name),\n})\n\n/** auth(): the AuthManager; auth(guard): that guard. */\nexport function auth(): AuthManager\nexport function auth(guard: string): StatefulGuard | Guard\nexport function auth(guard?: string): AuthManager | StatefulGuard | Guard {\n const manager = inject(AuthFactory) as AuthManager\n return guard === undefined ? manager : manager.guard(guard)\n}\n","import { AuthFactory, DatabaseManager, Gate as GateToken, PasswordBroker as PasswordBrokerToken, Router } from '@orieljs/contracts'\nimport { ServiceProvider } from '@orieljs/support'\nimport { AccessGate } from './Access/Gate'\nimport { AuthManager } from './AuthManager'\nimport { discoverPolicies } from './discoverPolicies'\nimport { Authenticate } from './middleware/Authenticate'\nimport { Authorize } from './middleware/Authorize'\nimport { EnsureEmailIsVerified } from './middleware/EnsureEmailIsVerified'\nimport { RedirectIfAuthenticated } from './middleware/RedirectIfAuthenticated'\nimport { PasswordBrokerManager } from './Passwords/PasswordBroker'\nimport { TokenRepository } from './tokens/PersonalAccessTokens'\n\nexport class AuthServiceProvider extends ServiceProvider {\n override register(): void {\n // Laravel 11's config/auth.php, plus the `token` guard used by `auth:token` (Sanctum's guard).\n // The user model can't be known here: the app's config/auth.ts sets providers.users.model.\n this.mergeConfigFrom(\n {\n defaults: { guard: 'web', passwords: 'users' },\n guards: {\n web: { driver: 'session', provider: 'users' },\n token: { driver: 'token', provider: 'users', expiration: null },\n },\n providers: { users: { driver: 'eloquent', model: null } },\n passwords: { users: { provider: 'users', table: 'password_reset_tokens', expire: 60, throttle: 60 } },\n password_timeout: 10800,\n },\n 'auth',\n )\n this.app.singleton(AuthFactory, (container) => new AuthManager(container))\n // inject(AuthManager) must get the same instance, not a second manager built by the container.\n this.app.singleton(AuthManager, (container) => container.make(AuthFactory) as AuthManager)\n this.app.singleton(GateToken, () => new AccessGate())\n this.app.singleton(PasswordBrokerManager, (container) => new PasswordBrokerManager(container))\n this.app.singleton(PasswordBrokerToken, (container) => container.make(PasswordBrokerManager).broker())\n this.app.singleton(TokenRepository, (container) => new TokenRepository(() => container.make(DatabaseManager)))\n }\n\n override async boot(): Promise<void> {\n if (this.app.bound(Router)) {\n this.app\n .make(Router)\n .aliasMiddleware('auth', Authenticate)\n .aliasMiddleware('guest', RedirectIfAuthenticated)\n .aliasMiddleware('can', Authorize)\n .aliasMiddleware('verified', EnsureEmailIsVerified)\n }\n await discoverPolicies(this.app.appPath('Policies'), this.app.make(GateToken) as AccessGate)\n }\n}\n","import type { OrielError } from '@orieljs/contracts'\n\n/** Base for bus errors: internal failures, reported and rendered as a 500 (kind 'Server'). */\nexport class BusError extends Error implements OrielError {\n readonly kind = 'Server' as const\n readonly status = 500\n override readonly name: string = 'BusError'\n}\n\nexport class QueueUnavailableError extends BusError {\n override readonly name = 'QueueUnavailableError'\n constructor() {\n super('Queued jobs need the queue: register the QueueServiceProvider.')\n }\n}\n\nexport class UniqueJobsNeedCacheError extends BusError {\n override readonly name = 'UniqueJobsNeedCacheError'\n constructor(job: string) {\n super(`[${job}] is a unique job, and unique jobs need a cache store for their lock. Register the CacheServiceProvider.`)\n }\n}\n\nexport class BatchingUnavailableError extends BusError {\n override readonly name = 'BatchingUnavailableError'\n constructor() {\n super('Batches are stored in the database: register the QueueServiceProvider and the DatabaseServiceProvider.')\n }\n}\n","import type { Job } from '@orieljs/contracts'\n\n/**\n * Symbol.for keys shared with @orieljs/queue (which declares the same keys; the two packages never import each other).\n * Symbol-keyed properties are never serialized into a payload's data.\n */\n\n/** \"Queue me\" marker, set on the Queueable prototype. */\nexport const SHOULD_QUEUE = Symbol.for('oriel:bus.shouldQueue')\n/** The running QueueJob, set on the restored job by Queue's CallQueuedHandler. */\nexport const QUEUE_JOB = Symbol.for('oriel:queue.job')\n/** The chain spec set on a chain's first job; Queue turns it into payload.chain & co. */\nexport const CHAIN = Symbol.for('oriel:queue.chain')\n/** The unique-lock spec set after acquiring the lock; Queue copies it to payload.uniqueLock and releases it. */\nexport const UNIQUE_LOCK = Symbol.for('oriel:queue.uniqueLock')\n\nexport interface ChainSpec {\n jobs: Job[]\n connection?: string\n queue?: string\n catch: Job[]\n}\n\nexport interface UniqueLockSpec {\n key: string\n store?: string\n untilProcessing: boolean\n}\n\nconst QUEUE_OPTIONS = ['connection', 'queue', 'delay', 'tries', 'backoff', 'timeout'] as const\n\ntype Members = Record<PropertyKey, unknown>\n\n/**\n * Whether dispatch() queues the job: it carries the ShouldQueue marker (the Queueable base class), has a value for\n * any ShouldQueue option, or defines uniqueId()/retryUntil(). `implements ShouldQueue` alone leaves no runtime trace.\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[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\n/** Laravel's ShouldBeUnique: the job defines uniqueId(), uniqueFor, uniqueUntilProcessing or uniqueVia(). */\nexport function isUnique(job: unknown): boolean {\n if (typeof job !== 'object' || job === null) return false\n const members = job as Members\n return (\n typeof members.uniqueId === 'function' ||\n members.uniqueFor !== undefined ||\n members.uniqueUntilProcessing === true ||\n typeof members.uniqueVia === 'function'\n )\n}\n\nexport function setSymbol(target: object, key: symbol, value: unknown): void {\n ;(target as Members)[key] = value\n}\n\nexport function getSymbol<T>(target: object, key: symbol): T | undefined {\n return (target as Members)[key] as T | undefined\n}\n\n/** `value` if it's a string, else `undefined`. Internal helper; not exported from Bus's index.ts. */\nexport function optionalString(value: unknown): string | undefined {\n return typeof value === 'string' ? value : undefined\n}\n","import type { CacheManager, CacheRepository, Job } from '@orieljs/contracts'\nimport type { UniqueLockSpec } from './symbols'\n\ninterface UniqueMembers {\n uniqueId?: () => unknown\n uniqueFor?: number | (() => number)\n uniqueUntilProcessing?: boolean\n uniqueVia?: () => string | undefined\n}\n\n/** Laravel's UniqueLock. The lock lives in `uniqueVia()`'s cache store (a store name) or the default store. */\nexport class UniqueLock {\n constructor(private readonly cache: CacheManager) {}\n\n static key(job: Job): string {\n const uniqueId = (job as UniqueMembers).uniqueId?.call(job)\n return `oriel_unique_job:${job.constructor.name}:${uniqueId === undefined || uniqueId === null ? '' : String(uniqueId)}`\n }\n\n /**\n * Tries to take the lock. Returns the spec to store on the payload, or undefined when another dispatch holds it.\n * `uniqueFor` of 0 or less (or none) means no expiry, as in Laravel: the Cache lock gets `undefined` seconds, which\n * is Cache's \"forever\" (a 0-second lock would expire at once and make the job not unique at all).\n */\n async acquire(job: Job): Promise<UniqueLockSpec | undefined> {\n const members = job as UniqueMembers\n const uniqueFor = typeof members.uniqueFor === 'function' ? members.uniqueFor.call(job) : (members.uniqueFor ?? 0)\n const store = members.uniqueVia?.call(job)\n const key = UniqueLock.key(job)\n if (!(await this.store(store).lock(key, uniqueFor > 0 ? uniqueFor : undefined).get())) return undefined\n const spec: UniqueLockSpec = { key, untilProcessing: members.uniqueUntilProcessing === true }\n if (store !== undefined) spec.store = store\n return spec\n }\n\n async release(spec: UniqueLockSpec): Promise<void> {\n await this.store(spec.store).lock(spec.key).forceRelease()\n }\n\n private store(name: string | undefined): CacheRepository {\n return name === undefined ? this.cache : this.cache.store(name)\n }\n}\n","import type { Job, PendingChain as PendingChainContract } from '@orieljs/contracts'\nimport type { Dispatcher } from './Dispatcher'\nimport { CHAIN, setSymbol, type ChainSpec } from './symbols'\n\n/** Bus.chain([...]): the first job is queued carrying the rest; each link queues the next one when it succeeds. */\nexport class PendingChain implements PendingChainContract {\n private connection: string | undefined\n private queue: string | undefined\n private readonly catchCallbacks: Job[] = []\n\n constructor(\n private readonly dispatcher: Dispatcher,\n private readonly jobs: Job[],\n ) {}\n\n onConnection(connection: string): this {\n this.connection = connection\n return this\n }\n\n onQueue(queue: string): this {\n this.queue = queue\n return this\n }\n\n /** A job dispatched when any job in the chain fails for good. */\n catch(job: Job): this {\n this.catchCallbacks.push(job)\n return this\n }\n\n async dispatch(): Promise<void> {\n const [first, ...rest] = this.jobs\n if (first === undefined) return\n if (this.connection !== undefined) first.connection = this.connection\n if (this.queue !== undefined) first.queue = this.queue\n const spec: ChainSpec = { jobs: rest, catch: this.catchCallbacks }\n if (this.connection !== undefined) spec.connection = this.connection\n if (this.queue !== undefined) spec.queue = this.queue\n setSymbol(first, CHAIN, spec)\n await this.dispatcher.dispatchToQueue(first)\n }\n}\n","import {\n BatchRepository,\n QueueManager,\n type Batch,\n type Container,\n type Job,\n type PendingBatch as PendingBatchContract,\n type PendingBatchOptions,\n} from '@orieljs/contracts'\nimport { BatchingUnavailableError, QueueUnavailableError } from './errors'\nimport { optionalString } from './symbols'\n\n/** Bus.batch([...]): stores the batch, then queues every job with its batchId. */\nexport class PendingBatch implements PendingBatchContract {\n private batchName = ''\n private connection: string | undefined\n private queue: string | undefined\n private failuresAllowed = false\n private readonly thenCallbacks: Job[] = []\n private readonly catchCallbacks: Job[] = []\n private readonly finallyCallbacks: Job[] = []\n\n constructor(\n private readonly container: Container,\n private readonly jobs: Job[],\n ) {}\n\n name(name: string): this {\n this.batchName = name\n return this\n }\n\n onConnection(connection: string): this {\n this.connection = connection\n return this\n }\n\n onQueue(queue: string): this {\n this.queue = queue\n return this\n }\n\n allowFailures(allow = true): this {\n this.failuresAllowed = allow\n return this\n }\n\n /** Dispatched once every job has succeeded. */\n then(job: Job): this {\n this.thenCallbacks.push(job)\n return this\n }\n\n /** Dispatched on the first job failure. */\n catch(job: Job): this {\n this.catchCallbacks.push(job)\n return this\n }\n\n /** Dispatched once every job has run exactly once, whatever the outcome. */\n finally(job: Job): this {\n this.finallyCallbacks.push(job)\n return this\n }\n\n /**\n * Stores the batch and pushes its jobs. On the sync connection a failing job's error is rethrown after every job\n * has been pushed, so the batch's counters still add up.\n */\n async dispatch(): Promise<Batch> {\n if (!this.container.bound(BatchRepository)) throw new BatchingUnavailableError()\n if (!this.container.bound(QueueManager)) throw new QueueUnavailableError()\n const repository = this.container.make(BatchRepository)\n const options: PendingBatchOptions = {\n name: this.batchName,\n then: this.thenCallbacks,\n catch: this.catchCallbacks,\n finally: this.finallyCallbacks,\n allowFailures: this.failuresAllowed,\n }\n if (this.connection !== undefined) options.connection = this.connection\n if (this.queue !== undefined) options.queue = this.queue\n const batch = await repository.store(options)\n\n if (this.jobs.length === 0) {\n await repository.markAsFinished(batch.id)\n return (await repository.find(batch.id))!\n }\n\n await repository.incrementTotalJobs(batch.id, this.jobs.length)\n const manager = this.container.make(QueueManager)\n const errors: unknown[] = []\n for (const job of this.jobs) {\n ;(job as { batchId?: string }).batchId = batch.id\n try {\n await manager\n .connection(this.connection ?? (optionalString(job.connection) || undefined))\n .push(job, this.queue ?? (optionalString(job.queue) || undefined))\n } catch (error) {\n errors.push(error)\n }\n }\n if (errors.length > 0) throw errors[0]\n return (await repository.find(batch.id))!\n }\n}\n","import {\n BatchRepository,\n CacheManager,\n QueueManager,\n type Batch,\n type BusDispatcher,\n type Container,\n type Job,\n} from '@orieljs/contracts'\nimport { currentContainer } from '@orieljs/container'\nimport { QueueUnavailableError, UniqueJobsNeedCacheError } from './errors'\nimport { PendingBatch } from './PendingBatch'\nimport { PendingChain } from './PendingChain'\nimport { isQueueable, isUnique, optionalString, setSymbol, UNIQUE_LOCK } from './symbols'\nimport { UniqueLock } from './UniqueLock'\n\n/** Seconds from a delay given as seconds or a Date. */\nexport function delaySeconds(delay: unknown): number {\n if (delay instanceof Date) return Math.max(0, (delay.getTime() - Date.now()) / 1000)\n return typeof delay === 'number' && delay > 0 ? delay : 0\n}\n\n/** Laravel's Illuminate\\Bus\\Dispatcher. */\nexport class Dispatcher implements BusDispatcher {\n /** Jobs deferred with dispatchAfterResponse(), per container: each request scope has its own list. */\n readonly #afterResponse = new WeakMap<object, Job[]>()\n\n constructor(private readonly container: Container) {}\n\n /** Queues the job when it is queueable, otherwise runs it now and returns handle()'s result. */\n async dispatch(job: Job): Promise<unknown> {\n return isQueueable(job) ? this.dispatchToQueue(job) : this.dispatchNow(job)\n }\n\n /** Runs the job now. A queueable job still goes through the sync queue (payload, middleware, failed_jobs). */\n async dispatchSync(job: Job): Promise<unknown> {\n return isQueueable(job) ? this.dispatchToQueue(job, 'sync') : this.dispatchNow(job)\n }\n\n /** Calls handle() directly: no serialization, no queue middleware. */\n async dispatchNow(job: Job): Promise<unknown> {\n return job.handle()\n }\n\n /**\n * Pushes the job on its connection and queue (with its delay). A unique job whose lock is taken is dropped and\n * undefined is returned. Returns the queue's job id otherwise.\n */\n async dispatchToQueue(job: Job, connection?: string): Promise<unknown> {\n if (!this.container.bound(QueueManager)) throw new QueueUnavailableError()\n const lock = isUnique(job) ? await this.acquireUniqueLock(job) : undefined\n if (lock === false) return undefined\n try {\n // Inside the try: an unknown connection (or a driver that fails to build) must release the lock too.\n const queue = this.container.make(QueueManager).connection(connection ?? (optionalString(job.connection) || undefined))\n const queueName = optionalString(job.queue) || undefined\n const delay = delaySeconds(job.delay)\n return delay > 0 ? await queue.later(delay, job, queueName) : await queue.push(job, queueName)\n } catch (error) {\n if (lock) await new UniqueLock(this.container.make(CacheManager)).release(lock)\n throw error\n }\n }\n\n #afterResponseList(): Job[] {\n const owner = currentContainer() ?? this.container\n let list = this.#afterResponse.get(owner)\n if (list === undefined) this.#afterResponse.set(owner, (list = []))\n return list\n }\n\n /** Runs the job (like dispatchSync) after the response is sent, or after the current queued job. */\n dispatchAfterResponse(job: Job): void {\n this.#afterResponseList().push(job)\n }\n\n /** Runs the jobs deferred by dispatchAfterResponse() (the provider's terminating callback and the worker call it). */\n async flushAfterResponse(): Promise<void> {\n for (const job of this.#afterResponseList().splice(0)) await this.dispatchSync(job)\n }\n\n chain(jobs: Job[]): PendingChain {\n return new PendingChain(this, jobs)\n }\n\n batch(jobs: Job[]): PendingBatch {\n return new PendingBatch(this.container, jobs)\n }\n\n async findBatch(id: string): Promise<Batch | undefined> {\n if (!this.container.bound(BatchRepository)) return undefined\n return this.container.make(BatchRepository).find(id)\n }\n\n /** The lock spec, or false when another dispatch holds the lock. */\n private async acquireUniqueLock(job: Job) {\n if (!this.container.bound(CacheManager)) throw new UniqueJobsNeedCacheError(job.constructor.name)\n const spec = await new UniqueLock(this.container.make(CacheManager)).acquire(job)\n if (!spec) return false as const\n setSymbol(job, UNIQUE_LOCK, spec)\n return spec\n }\n}\n","import { BusDispatcher, ExceptionHandler, type Container, type Job } from '@orieljs/contracts'\nimport { currentContainer } from '@orieljs/container'\nimport { BusError } from './errors'\nimport { delaySeconds } from './Dispatcher'\n\n/**\n * What `Job.dispatch(...)` and `dispatch(job)` return (Laravel's PendingDispatch). Chain the options synchronously;\n * the job is dispatched exactly once: on the next microtask, or when awaited, whichever comes first. So both\n * `ProcessPodcast.dispatch(podcast)` and `await ProcessPodcast.dispatch(podcast).onQueue('audio')` work.\n */\nexport class PendingDispatch implements PromiseLike<unknown> {\n private promise: Promise<unknown> | undefined\n private observed = false\n private deferred = false\n private chained: Job[] = []\n private readonly container: Container | undefined\n\n /** `job` undefined: a no-op dispatch (dispatchIf(false, …)). */\n constructor(private readonly job: Job | undefined) {\n this.container = currentContainer()\n queueMicrotask(() => {\n this.execute().catch((error: unknown) => this.reportUnobserved(error))\n })\n }\n\n onConnection(connection: string): this {\n return this.set(() => this.job && (this.job.connection = connection))\n }\n\n onQueue(queue: string): this {\n return this.set(() => this.job && (this.job.queue = queue))\n }\n\n /** Seconds, or a Date to run at. */\n delay(delay: number | Date): this {\n return this.set(() => this.job && (this.job.delay = delaySeconds(delay)))\n }\n\n /** Jobs to run after this one succeeds (a chain). */\n chain(jobs: Job[]): this {\n return this.set(() => (this.chained = [...this.chained, ...jobs]))\n }\n\n /** Run it after the response is sent instead (sync). */\n afterResponse(): this {\n return this.set(() => (this.deferred = true))\n }\n\n then<R1 = unknown, R2 = never>(\n onfulfilled?: ((value: unknown) => R1 | PromiseLike<R1>) | null,\n onrejected?: ((reason: unknown) => R2 | PromiseLike<R2>) | null,\n ): Promise<R1 | R2> {\n this.observed = true\n return this.execute().then(onfulfilled, onrejected)\n }\n\n private set(change: () => unknown): this {\n if (this.promise) throw new BusError('This job was already dispatched: chain onQueue()/delay()/… in the same statement as dispatch().')\n change()\n return this\n }\n\n private execute(): Promise<unknown> {\n return (this.promise ??= this.run())\n }\n\n private async run(): Promise<unknown> {\n const job = this.job\n if (job === undefined) return undefined\n const container = this.container ?? currentContainer()\n if (!container) throw new BusError('dispatch() needs a running application (no container is available).')\n return container.run(async () => {\n const bus = container.make(BusDispatcher)\n if (this.deferred) return bus.dispatchAfterResponse(job)\n if (this.chained.length > 0) return bus.chain([job, ...this.chained]).dispatch()\n return bus.dispatch(job)\n })\n }\n\n /** A failure nobody awaited: report it instead of leaving an unhandled rejection. */\n private async reportUnobserved(error: unknown): Promise<void> {\n if (this.observed) return\n const container = this.container ?? currentContainer()\n if (container?.bound(ExceptionHandler)) await container.make(ExceptionHandler).report(error)\n else console.error(error)\n }\n}\n","import { BusDispatcher, type Batch, type Job, type QueueJob } from '@orieljs/contracts'\nimport { inject } from '@orieljs/container'\nimport { PendingDispatch } from './PendingDispatch'\nimport { getSymbol, QUEUE_JOB, SHOULD_QUEUE } from './symbols'\n\ntype Condition = boolean | (() => boolean)\nconst holds = (condition: Condition): boolean => (typeof condition === 'function' ? condition() : condition)\n\n/**\n * Laravel's Dispatchable + InteractsWithQueue + Batchable for a job class. Extending it gives `Job.dispatch(...)`\n * statics and `this.release()` / `this.attempts()` / `this.fail()` / `this.batch()` inside handle(). A Dispatchable\n * job is NOT queued by itself (like a Laravel job without ShouldQueue); extend Queueable for that.\n */\nexport abstract class Dispatchable implements Job {\n // No option fields are declared here on purpose: subclasses write `tries = 3` without `override`, and nothing is\n // serialized (or counts as a queue option) unless the job sets it.\n abstract handle(): unknown\n\n /** `ProcessPodcast.dispatch(podcast)`: dispatched on the next microtask, or when awaited. */\n static dispatch<A extends unknown[]>(this: new (...args: A) => Job, ...args: A): PendingDispatch {\n return new PendingDispatch(new this(...args))\n }\n\n static dispatchIf<A extends unknown[]>(this: new (...args: A) => Job, condition: Condition, ...args: A): PendingDispatch {\n return new PendingDispatch(holds(condition) ? new this(...args) : undefined)\n }\n\n static dispatchUnless<A extends unknown[]>(this: new (...args: A) => Job, condition: Condition, ...args: A): PendingDispatch {\n return new PendingDispatch(holds(condition) ? undefined : new this(...args))\n }\n\n /** Runs now (a queueable job goes through the sync queue). Returns handle()'s result for plain jobs. */\n static dispatchSync<A extends unknown[]>(this: new (...args: A) => Job, ...args: A): Promise<unknown> {\n return inject(BusDispatcher).dispatchSync(new this(...args))\n }\n\n static dispatchAfterResponse<A extends unknown[]>(this: new (...args: A) => Job, ...args: A): void {\n inject(BusDispatcher).dispatchAfterResponse(new this(...args))\n }\n\n onConnection(connection: string): this {\n ;(this as Job).connection = connection\n return this\n }\n\n onQueue(queue: string): this {\n ;(this as Job).queue = queue\n return this\n }\n\n /** The queue job running this instance (undefined when it runs outside a queue). */\n queueJob(): QueueJob | undefined {\n return getSymbol<QueueJob>(this, QUEUE_JOB)\n }\n\n /** How many times the job has been attempted (1 outside a queue). */\n attempts(): number {\n return this.queueJob()?.attempts() ?? 1\n }\n\n /** Puts the job back on the queue, available again after `delaySeconds`. */\n async release(delaySeconds = 0): Promise<void> {\n await this.queueJob()?.release(delaySeconds)\n }\n\n async delete(): Promise<void> {\n await this.queueJob()?.delete()\n }\n\n /** Marks the job as failed now (no more retries): failed_jobs, failed(), batch and chain bookkeeping. */\n async fail(error?: unknown): Promise<void> {\n await this.queueJob()?.fail(error)\n }\n\n /** The batch this job belongs to. */\n async batch(): Promise<Batch | undefined> {\n const batchId = (this as { batchId?: unknown }).batchId\n return typeof batchId === 'string' ? inject(BusDispatcher).findBatch(batchId) : undefined\n }\n}\n\n/**\n * A queued job: Laravel's `implements ShouldQueue` + `use Queueable`. `dispatch()` pushes it onto the queue.\n * The marker lives on the prototype, so it is never serialized.\n */\nexport abstract class Queueable extends Dispatchable {}\nObject.defineProperty(Queueable.prototype, SHOULD_QUEUE, { value: true })\n","import { BusDispatcher, type Job } from '@orieljs/contracts'\nimport { inject } from '@orieljs/container'\nimport { PendingDispatch } from './PendingDispatch'\n\n/** Laravel's dispatch() helper: queued when the job is queueable, else run now. Dispatched once, awaited or not. */\nexport function dispatch(job: Job): PendingDispatch {\n return new PendingDispatch(job)\n}\n\n/** Laravel's dispatch_sync(). */\nexport function dispatchSync(job: Job): Promise<unknown> {\n return inject(BusDispatcher).dispatchSync(job)\n}\n","import { BusDispatcher } from '@orieljs/contracts'\nimport { facade } from '@orieljs/support'\n\n/** `Bus.dispatch(job)`, `Bus.chain([...]).dispatch()`, `Bus.batch([...]).then(job).dispatch()`, `Bus.findBatch(id)`. */\nexport const Bus = facade(BusDispatcher)\n","import { BusDispatcher } from '@orieljs/contracts'\nimport { ServiceProvider } from '@orieljs/support'\nimport { Dispatcher } from './Dispatcher'\n\ninterface FlushesAfterResponse {\n flushAfterResponse?(): Promise<void>\n}\n\nexport class BusServiceProvider extends ServiceProvider {\n override register(): void {\n this.app.singleton(BusDispatcher, (container) => new Dispatcher(container))\n }\n\n /** One terminating callback runs the jobs deferred with dispatchAfterResponse() (Http terminates after each response). */\n override boot(): void {\n this.app.terminating(async () => {\n if (!this.app.resolved(BusDispatcher)) return\n await (this.app.make(BusDispatcher) as FlushesAfterResponse).flushAfterResponse?.()\n })\n }\n}\n","import type { OrielError } from '@orieljs/contracts'\n\nexport class LockTimeoutError extends Error implements OrielError {\n readonly kind = 'Server' as const\n readonly status = 500\n override readonly name = 'LockTimeoutError'\n constructor(readonly lockName: string) {\n super(`Unable to acquire lock [${lockName}].`)\n }\n}\n\nexport class TagsNotSupportedError extends Error implements OrielError {\n readonly kind = 'Server' as const\n readonly status = 500\n override readonly name = 'TagsNotSupportedError'\n constructor(store: string) {\n super(`The [${store}] cache store does not support tags. Only the redis store does.`)\n }\n}\n\nexport class UnknownCacheStoreError extends Error implements OrielError {\n readonly kind = 'Server' as const\n readonly status = 500\n override readonly name = 'UnknownCacheStoreError'\n constructor(name: string) {\n super(`Cache store [${name}] is not configured. Add it to config('cache.stores').`)\n }\n}\n\nexport class UnknownCacheDriverError extends Error implements OrielError {\n readonly kind = 'Server' as const\n readonly status = 500\n override readonly name = 'UnknownCacheDriverError'\n constructor(driver: string) {\n super(`Cache driver [${driver}] is not supported. Register it first with CacheManager.extend().`)\n }\n}\n\nexport class InvalidCacheConfigError extends Error implements OrielError {\n readonly kind = 'Server' as const\n readonly status = 500\n override readonly name = 'InvalidCacheConfigError'\n}\n","/**\n * Cache values always round-trip through JSON.stringify/JSON.parse, on every store — even the in-process\n * memory store — so switching `cache.default` never changes behaviour. Practical limits this implies:\n * - A Date becomes a string (ISO 8601). Read it back with `new Date(...)`, or use a Model cast.\n * - undefined properties on an object are dropped, and a bare `undefined` value is stored as `null` (it reads\n * back as `null`, not as a miss: `undefined` is only ever the \"cache miss\" result of a read).\n * - NaN and Infinity become `null`.\n * - Map, Set, class instances, functions and symbols do not round-trip: plain data only.\n */\nexport function serialize(value: unknown): string {\n return JSON.stringify(value) ?? 'null'\n}\n\nexport function deserialize(raw: string): unknown {\n return JSON.parse(raw)\n}\n\n/** Deep-clones `value` through JSON, applying the same limits as every persisted store. */\nexport function roundTrip<T>(value: T): T {\n return JSON.parse(serialize(value)) as T\n}\n","import { setTimeout as sleep } from 'node:timers/promises'\nimport type { Lock } from '@orieljs/contracts'\nimport { Str } from '@orieljs/support'\nimport { LockTimeoutError } from '../errors'\nimport type { Store } from '../Store'\n\n/**\n * Backs a Lock with any Store whose add() is atomic (memory, array, file). Shares the store's key space with\n * regular cache entries, exactly like Laravel's CacheLock: `Cache::lock('x')` and `Cache::put('x', ...)` name the\n * same slot on purpose.\n */\nexport class GenericLock implements Lock {\n private readonly ownerValue: string\n\n constructor(\n private readonly store: Store,\n private readonly name: string,\n private readonly seconds: number | undefined,\n owner?: string,\n private readonly pollMs = 50,\n ) {\n this.ownerValue = owner ?? Str.random(20)\n }\n\n owner(): string {\n return this.ownerValue\n }\n\n async get<T = boolean>(callback?: () => T | Promise<T>): Promise<T | false> {\n const acquired = await this.store.add(this.name, this.ownerValue, this.seconds)\n if (!acquired) return false\n if (!callback) return true as T\n try {\n return await callback()\n } finally {\n await this.release()\n }\n }\n\n async block<T = boolean>(seconds: number, callback?: () => T | Promise<T>): Promise<T | true> {\n const deadline = Date.now() + seconds * 1000\n for (;;) {\n if (await this.get()) break\n if (Date.now() >= deadline) throw new LockTimeoutError(this.name)\n await sleep(this.pollMs)\n }\n if (!callback) return true\n try {\n return await callback()\n } finally {\n await this.release()\n }\n }\n\n async release(): Promise<boolean> {\n const current = await this.store.get(this.name)\n if (current !== this.ownerValue) return false\n return this.store.forget(this.name)\n }\n\n async forceRelease(): Promise<void> {\n await this.store.forget(this.name)\n }\n}\n","import type { CacheRepository, Lock } from '@orieljs/contracts'\nimport { GenericLock } from './locks/GenericLock'\nimport { TagsNotSupportedError } from './errors'\nimport type { Store } from './Store'\n\nexport type LockFactory = (store: Store, name: string, seconds: number | undefined, owner: string | undefined) => Lock\n\nexport const defaultLockFactory: LockFactory = (store, name, seconds, owner) => new GenericLock(store, name, seconds, owner)\n\n/** Implements the full CacheRepository API over any Store, the way Illuminate\\Cache\\Repository wraps a Store. */\nexport class Repository implements CacheRepository {\n constructor(\n protected readonly store: Store,\n private readonly lockFactory: LockFactory = defaultLockFactory,\n ) {}\n\n async get<T = unknown>(key: string, defaultValue?: T | (() => T)): Promise<T | undefined> {\n const value = await this.store.get(key)\n if (value !== undefined) return value as T\n return typeof defaultValue === 'function' ? (defaultValue as () => T)() : defaultValue\n }\n\n async many<T = unknown>(keys: string[]): Promise<Record<string, T | undefined>> {\n const found = await this.store.many(keys)\n const result: Record<string, T | undefined> = {}\n for (const key of keys) result[key] = found[key] as T | undefined\n return result\n }\n\n async has(key: string): Promise<boolean> {\n return (await this.store.get(key)) !== undefined\n }\n\n async missing(key: string): Promise<boolean> {\n return !(await this.has(key))\n }\n\n async put(key: string, value: unknown, ttlSeconds?: number): Promise<boolean> {\n if (ttlSeconds !== undefined && ttlSeconds <= 0) {\n await this.store.forget(key)\n return true\n }\n if (ttlSeconds === undefined) return this.store.putForever(key, value)\n return this.store.put(key, value, ttlSeconds)\n }\n\n async add(key: string, value: unknown, ttlSeconds?: number): Promise<boolean> {\n if (ttlSeconds !== undefined && ttlSeconds <= 0) return false\n return this.store.add(key, value, ttlSeconds)\n }\n\n increment(key: string, by = 1): Promise<number> {\n return this.store.increment(key, by)\n }\n\n decrement(key: string, by = 1): Promise<number> {\n return this.store.decrement(key, by)\n }\n\n forever(key: string, value: unknown): Promise<boolean> {\n return this.store.putForever(key, value)\n }\n\n async pull<T = unknown>(key: string, defaultValue?: T): Promise<T | undefined> {\n const value = await this.get<T>(key)\n await this.forget(key)\n return value === undefined ? defaultValue : value\n }\n\n forget(key: string): Promise<boolean> {\n return this.store.forget(key)\n }\n\n flush(): Promise<boolean> {\n return this.store.flush()\n }\n\n async remember<T>(key: string, ttlSeconds: number, callback: () => T | Promise<T>): Promise<T> {\n const cached = await this.get<T>(key)\n if (cached !== undefined) return cached\n const value = await callback()\n if (value !== undefined) await this.put(key, value, ttlSeconds)\n return value\n }\n\n async rememberForever<T>(key: string, callback: () => T | Promise<T>): Promise<T> {\n const cached = await this.get<T>(key)\n if (cached !== undefined) return cached\n const value = await callback()\n if (value !== undefined) await this.forever(key, value)\n return value\n }\n\n lock(name: string, seconds?: number, owner?: string): Lock {\n // Laravel's semantics: 0 (and anything <= 0) seconds means \"no expiry\", exactly like `undefined`. Locks are\n // always positive-duration in practice, but callers that compute `uniqueFor ?? 0` (Bus's UniqueLock, for\n // example) need `lock(key, 0)` to behave the same as `lock(key)`, not to expire immediately.\n const normalizedSeconds = seconds !== undefined && seconds <= 0 ? undefined : seconds\n return this.lockFactory(this.store, name, normalizedSeconds, owner)\n }\n\n tags(_names: string | string[]): CacheRepository {\n throw new TagsNotSupportedError(this.store.constructor.name)\n }\n}\n","import { InvalidCacheConfigError } from '../errors'\nimport { roundTrip } from '../serialize'\nimport type { Store } from '../Store'\n\ninterface Entry {\n value: unknown\n expiresAt: number | undefined\n}\n\n/**\n * Backs both the `memory` and `array` drivers: `array` is just a MemoryStore with no `maxItems` bound.\n * A bounded store evicts least-recently-used entries, and that includes held locks (GenericLock keys).\n */\nexport class MemoryStore implements Store {\n private readonly entries = new Map<string, Entry>()\n\n constructor(\n private readonly keyPrefix: string = '',\n private readonly maxItems?: number,\n ) {\n if (maxItems !== undefined && !(maxItems >= 1)) {\n throw new InvalidCacheConfigError(`Memory cache maxItems must be at least 1, got [${maxItems}].`)\n }\n }\n\n private k(key: string): string {\n return this.keyPrefix + key\n }\n\n /** Reads and, on a hit, re-inserts the entry so Map iteration order tracks recency (a simple LRU). */\n private read(key: string): Entry | undefined {\n const entry = this.entries.get(key)\n if (!entry) return undefined\n if (entry.expiresAt !== undefined && entry.expiresAt <= Date.now()) {\n this.entries.delete(key)\n return undefined\n }\n this.entries.delete(key)\n this.entries.set(key, entry)\n return entry\n }\n\n private write(key: string, value: unknown, expiresAt: number | undefined): void {\n this.entries.delete(key)\n this.entries.set(key, { value: roundTrip(value), expiresAt })\n if (this.maxItems !== undefined) {\n while (this.entries.size > this.maxItems) {\n const oldest = this.entries.keys().next().value\n if (oldest === undefined) break\n this.entries.delete(oldest)\n }\n }\n }\n\n async get(key: string): Promise<unknown> {\n return this.read(this.k(key))?.value\n }\n\n async many(keys: string[]): Promise<Record<string, unknown>> {\n const result: Record<string, unknown> = {}\n for (const key of keys) {\n const entry = this.read(this.k(key))\n if (entry) result[key] = entry.value\n }\n return result\n }\n\n async put(key: string, value: unknown, seconds: number): Promise<boolean> {\n this.write(this.k(key), value, Date.now() + seconds * 1000)\n return true\n }\n\n async putForever(key: string, value: unknown): Promise<boolean> {\n this.write(this.k(key), value, undefined)\n return true\n }\n\n async add(key: string, value: unknown, seconds?: number): Promise<boolean> {\n const k = this.k(key)\n if (this.read(k) !== undefined) return false\n this.write(k, value, seconds === undefined ? undefined : Date.now() + seconds * 1000)\n return true\n }\n\n async increment(key: string, by: number): Promise<number> {\n const k = this.k(key)\n const existing = this.read(k)\n const current = typeof existing?.value === 'number' ? existing.value : 0\n const next = current + by\n this.write(k, next, existing?.expiresAt)\n return next\n }\n\n async decrement(key: string, by: number): Promise<number> {\n return this.increment(key, -by)\n }\n\n async forget(key: string): Promise<boolean> {\n return this.entries.delete(this.k(key))\n }\n\n async flush(): Promise<boolean> {\n this.entries.clear()\n return true\n }\n}\n","import { createHash } from 'node:crypto'\nimport { link, mkdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises'\nimport { dirname, join } from 'node:path'\nimport { deserialize, roundTrip, serialize } from '../serialize'\nimport type { Store } from '../Store'\n\n/**\n * Unix-milliseconds sentinel for \"forever\" (13 digits, year 2286 — the same horizon as Laravel's FileStore\n * sentinel, just in milliseconds instead of seconds). Millisecond, not second, resolution: the test suite (and\n * Console's scheduler, which can pass sub-second-rounding-sensitive TTLs) relies on short TTLs like 0.05s\n * actually expiring within tens of milliseconds, which a whole-seconds timestamp can't represent.\n */\nconst FOREVER = 9999999999999\n\n/**\n * How old a key's takeover mutex file must be before another process may assume its holder crashed. The\n * critical section it guards is one small read plus a rename, so anything this old is not a live holder.\n */\nconst MUTEX_STALE_MS = 10_000\n\ninterface Payload {\n expiresAt: number\n value: unknown\n}\n\nconst now = (): number => Date.now()\n\nconst isLive = (payload: Payload | undefined): payload is Payload => payload !== undefined && payload.expiresAt > now()\n\nconst errorCode = (error: unknown): string | undefined => (error as NodeJS.ErrnoException).code\n\n/**\n * Store impl at `storage/framework/cache/data`: hashed paths, atomic writes (temp file + rename). Reads never\n * delete anything: an expired or corrupt file is simply a miss, and is replaced by the next write.\n */\nexport class FileStore implements Store {\n constructor(\n private readonly directory: string,\n private readonly keyPrefix: string = '',\n ) {}\n\n private path(key: string): string {\n const hash = createHash('sha1').update(this.keyPrefix + key).digest('hex')\n return join(this.directory, hash.slice(0, 2), hash.slice(2, 4), hash)\n }\n\n private tempPath(path: string): string {\n return `${path}.tmp-${process.pid}-${Math.random().toString(36).slice(2)}`\n }\n\n private encode(value: unknown, expiresAt: number): string {\n return `${String(expiresAt).padStart(13, '0')}${serialize(roundTrip(value))}`\n }\n\n /** Undefined for a missing or corrupt file; the payload (possibly expired) otherwise. */\n private async readPayload(path: string): Promise<Payload | undefined> {\n let raw: string\n try {\n raw = await readFile(path, 'utf8')\n } catch (error) {\n if (errorCode(error) === 'ENOENT') return undefined\n throw error\n }\n const header = raw.slice(0, 13)\n if (!/^\\d{13}$/.test(header)) return undefined\n try {\n return { expiresAt: Number(header), value: deserialize(raw.slice(13)) }\n } catch {\n return undefined\n }\n }\n\n private async writeTemp(path: string, contents: string): Promise<string> {\n await mkdir(dirname(path), { recursive: true })\n const temp = this.tempPath(path)\n await writeFile(temp, contents)\n return temp\n }\n\n private async atomicWrite(path: string, contents: string): Promise<void> {\n const temp = await this.writeTemp(path, contents)\n try {\n await rename(temp, path)\n } catch (error) {\n await rm(temp, { force: true })\n throw error\n }\n }\n\n async get(key: string): Promise<unknown> {\n const payload = await this.readPayload(this.path(key))\n return isLive(payload) ? payload.value : undefined\n }\n\n async many(keys: string[]): Promise<Record<string, unknown>> {\n const result: Record<string, unknown> = {}\n for (const key of keys) {\n const payload = await this.readPayload(this.path(key))\n if (isLive(payload)) result[key] = payload.value\n }\n return result\n }\n\n async put(key: string, value: unknown, seconds: number): Promise<boolean> {\n await this.atomicWrite(this.path(key), this.encode(value, now() + seconds * 1000))\n return true\n }\n\n async putForever(key: string, value: unknown): Promise<boolean> {\n await this.atomicWrite(this.path(key), this.encode(value, FOREVER))\n return true\n }\n\n /**\n * Exclusive create is the atomicity primitive, but the exclusive step is a hard link, not opening `path`\n * directly with `wx`: the full payload is written to a temp file first, then `link()`'d into place. `link()`\n * is atomic and fails `EEXIST` if the destination already exists, so no concurrent reader can ever observe a\n * half-written file at `path` — unlike creating `path` itself with `wx` and writing to it afterwards, which\n * leaves a window (between file creation and the write completing) where a concurrent `get()`/`add()` can read\n * an empty or truncated file and throw a JSON parse error instead of losing the race cleanly.\n *\n * If the key holds an expired or corrupt entry, the takeover happens under a per-key mutex (see\n * takeOverExpired), so two callers can never both replace it.\n */\n async add(key: string, value: unknown, seconds?: number): Promise<boolean> {\n const path = this.path(key)\n const expiresAt = seconds === undefined ? FOREVER : now() + seconds * 1000\n const temp = await this.writeTemp(path, this.encode(value, expiresAt))\n try {\n if (await this.linkExclusive(temp, path)) return true\n if (isLive(await this.readPayload(path))) return false\n return await this.takeOverExpired(path, temp)\n } finally {\n await rm(temp, { force: true })\n }\n }\n\n private async linkExclusive(from: string, to: string): Promise<boolean> {\n try {\n await link(from, to)\n return true\n } catch (error) {\n if (errorCode(error) === 'EEXIST') return false\n throw error\n }\n }\n\n /**\n * Replaces an expired or corrupt entry, holding `path + '.lock'` (created with the same link() trick) so only\n * one add() at a time can take it over. A caller that finds the mutex held loses without waiting: the holder\n * is replacing the entry right now, so at that moment the key is taken either way. Inside the mutex the entry\n * is re-read (it may have been replaced by a put() meanwhile), then removed and our file linked in: if anything\n * else creates the key in between (a put(), or an add() after a forget()), the link fails and we lose cleanly.\n */\n private async takeOverExpired(path: string, temp: string): Promise<boolean> {\n const mutex = `${path}.lock`\n const token = await this.acquireMutex(mutex)\n if (token === undefined) return false\n try {\n if (isLive(await this.readPayload(path))) return false\n await rm(path, { force: true })\n return await this.linkExclusive(temp, path)\n } finally {\n await this.releaseMutex(mutex, token)\n }\n }\n\n /** Returns our token once the mutex is held, or undefined if another live holder has it. */\n private async acquireMutex(mutex: string, retried = false): Promise<string | undefined> {\n const token = `${process.pid}-${Math.random().toString(36).slice(2)}`\n const temp = await this.writeTemp(mutex, token)\n try {\n if (await this.linkExclusive(temp, mutex)) return token\n } finally {\n await rm(temp, { force: true })\n }\n if (retried) return undefined\n let modified: number\n try {\n modified = (await stat(mutex)).mtimeMs\n } catch (error) {\n if (errorCode(error) === 'ENOENT') return this.acquireMutex(mutex, true) // released meanwhile\n throw error\n }\n if (now() - modified < MUTEX_STALE_MS) return undefined\n // Its holder crashed: clear it and try once more.\n await rm(mutex, { force: true })\n return this.acquireMutex(mutex, true)\n }\n\n /** Only removes the mutex if it is still ours (a stalled holder's mutex may have been cleared as stale). */\n private async releaseMutex(mutex: string, token: string): Promise<void> {\n try {\n if ((await readFile(mutex, 'utf8')) === token) await rm(mutex, { force: true })\n } catch (error) {\n if (errorCode(error) !== 'ENOENT') throw error\n }\n }\n\n async increment(key: string, by: number): Promise<number> {\n const path = this.path(key)\n const payload = await this.readPayload(path)\n const existing = isLive(payload) ? payload : undefined\n const current = existing && typeof existing.value === 'number' ? existing.value : 0\n const next = current + by\n await this.atomicWrite(path, this.encode(next, existing?.expiresAt ?? FOREVER))\n return next\n }\n\n decrement(key: string, by: number): Promise<number> {\n return this.increment(key, -by)\n }\n\n async forget(key: string): Promise<boolean> {\n try {\n await rm(this.path(key))\n return true\n } catch (error) {\n if (errorCode(error) === 'ENOENT') return false\n throw error\n }\n }\n\n /** Clears the whole directory, regardless of prefix — matches Laravel's FileStore::flush(). */\n async flush(): Promise<boolean> {\n await rm(this.directory, { recursive: true, force: true })\n await mkdir(this.directory, { recursive: true })\n return true\n }\n}\n","import type { DatabaseConnection } from '@orieljs/contracts'\n\n/**\n * Laravel's add()/acquire(): insert the row unless its key exists, and otherwise take the row over only when it has\n * expired. Returns whether the row is now this caller's. `row` holds the `key` and `expiration` columns.\n *\n * The insert never fails on a taken key (insertOrIgnore), so it can't abort the caller's transaction on Postgres and\n * needs no savepoint or queue: concurrent callers, in one transaction or in several, only wait on the database's own\n * row locks.\n */\nexport async function insertOrTakeOver(connection: DatabaseConnection, table: string, row: Record<string, unknown>): Promise<boolean> {\n if ((await connection.table(table).insertOrIgnore(row)) === 1) return true\n const now = Math.floor(Date.now() / 1000)\n return (await connection.table(table).where('key', row.key).where('expiration', '<=', now).update(row)) > 0\n}\n","import type { DatabaseConnection } from '@orieljs/contracts'\nimport { insertOrTakeOver } from '../insertOrTakeOver'\nimport { deserialize, roundTrip, serialize } from '../serialize'\nimport type { Store } from '../Store'\n\n/**\n * \"Forever\" here is a 10-year TTL from now, not a fixed epoch sentinel: `expiration` is an `integer` column\n * (Postgres/MySQL `int4`, max 2147483647), and the epoch-millisecond sentinel FileStore uses (9999999999999) overflows\n * it. This is Laravel's own DatabaseStore::forever(), which calls `put(key, value, 315360000)` for the same\n * reason, rather than a magic-number timestamp.\n */\nconst FOREVER_SECONDS = 315360000\n\ninterface CacheRow {\n key: string\n value: string\n expiration: number\n}\n\nconst now = (): number => Math.floor(Date.now() / 1000)\n\n/** Store impl over the `cache` table, resolved through DatabaseManager (never imports @orieljs/database). */\nexport class DatabaseStore implements Store {\n constructor(\n private readonly connection: DatabaseConnection,\n private readonly table: string,\n private readonly keyPrefix: string = '',\n ) {}\n\n private k(key: string): string {\n return this.keyPrefix + key\n }\n\n async get(key: string): Promise<unknown> {\n const k = this.k(key)\n const row = await this.connection.table<CacheRow>(this.table).where('key', k).first()\n if (!row) return undefined\n if (row.expiration <= now()) {\n // Only delete while still expired: another process may have rewritten the key since we read it.\n await this.connection.table(this.table).where('key', k).where('expiration', '<=', now()).delete()\n return undefined\n }\n return deserialize(row.value)\n }\n\n async many(keys: string[]): Promise<Record<string, unknown>> {\n if (keys.length === 0) return {}\n const prefixed = keys.map((key) => this.k(key))\n const rows = await this.connection.table<CacheRow>(this.table).whereIn('key', prefixed).get()\n const byKey = new Map(rows.all().map((row) => [row.key, row]))\n const time = now()\n const result: Record<string, unknown> = {}\n keys.forEach((key, i) => {\n const row = byKey.get(prefixed[i]!)\n if (row && row.expiration > time) result[key] = deserialize(row.value)\n })\n return result\n }\n\n async put(key: string, value: unknown, seconds: number): Promise<boolean> {\n return this.write(this.k(key), value, now() + Math.ceil(seconds))\n }\n\n async putForever(key: string, value: unknown): Promise<boolean> {\n return this.write(this.k(key), value, now() + FOREVER_SECONDS)\n }\n\n private async write(key: string, value: unknown, expiration: number): Promise<boolean> {\n await this.connection.table(this.table).upsert({ key, value: serialize(roundTrip(value)), expiration }, ['key'])\n return true\n }\n\n /**\n * Laravel's DatabaseStore::add(): an insert that skips a taken key, and then a conditional update that only takes\n * over an expired row (see insertOrTakeOver). Nothing fails on a taken key, so a caller's transaction stays usable.\n */\n async add(key: string, value: unknown, seconds?: number): Promise<boolean> {\n const k = this.k(key)\n const expiration = seconds === undefined ? now() + FOREVER_SECONDS : now() + Math.ceil(seconds)\n const row = { key: k, value: serialize(roundTrip(value)), expiration }\n return insertOrTakeOver(this.connection, this.table, row)\n }\n\n async increment(key: string, by: number, attempt = 0): Promise<number> {\n const k = this.k(key)\n try {\n return await this.connection.transaction(async (trx) => {\n const existing = await trx.table<CacheRow>(this.table).where('key', k).lockForUpdate().first()\n const unexpired = existing !== undefined && existing.expiration > now()\n const current = unexpired ? Number(deserialize(existing!.value)) : 0\n const next = current + by\n const expiration = unexpired ? existing!.expiration : now() + FOREVER_SECONDS\n const row = { key: k, value: serialize(next), expiration }\n if (existing) await trx.table(this.table).where('key', k).update(row)\n else await trx.table(this.table).insert(row)\n return next\n })\n } catch (error) {\n // Another writer's increment()/put() inserted this key between our lockForUpdate read (which saw no row)\n // and our own insert. Unlike add(), we can't just leave the other\n // writer's value alone — Store.ts requires increment() to apply `by` on top of whatever is there — so\n // retry the whole transaction once, this time reading the row the other writer just created. A second\n // failure propagates: something other than a benign insert race is going on.\n if (attempt > 0) throw error\n return this.increment(key, by, attempt + 1)\n }\n }\n\n decrement(key: string, by: number): Promise<number> {\n return this.increment(key, -by)\n }\n\n async forget(key: string): Promise<boolean> {\n const deleted = await this.connection.table(this.table).where('key', this.k(key)).delete()\n return deleted > 0\n }\n\n async flush(): Promise<boolean> {\n if (this.keyPrefix) await this.connection.table(this.table).where('key', 'like', `${this.keyPrefix}%`).delete()\n else await this.connection.table(this.table).delete()\n return true\n }\n}\n","import { setTimeout as sleep } from 'node:timers/promises'\nimport type { DatabaseConnection, Lock } from '@orieljs/contracts'\nimport { Str } from '@orieljs/support'\nimport { LockTimeoutError } from '../errors'\nimport { insertOrTakeOver } from '../insertOrTakeOver'\n\n// See DatabaseStore.ts: a 10-year TTL from now, not an epoch sentinel — `expiration` is an `integer` column and\n// FileStore's 9999999999999 sentinel overflows it on Postgres/MySQL (B8). Matches Laravel's DatabaseStore/DatabaseLock.\nconst FOREVER_SECONDS = 315360000\nconst now = (): number => Math.floor(Date.now() / 1000)\n\ninterface LockRow {\n key: string\n owner: string\n expiration: number\n}\n\n/**\n * Locks use their own `cache_locks` table (not `cache`), like Laravel's DatabaseLock: a `value` column with\n * arbitrary serialized data would make comparing owners awkward, so locks get dedicated `owner`/`expiration`\n * columns instead.\n */\nexport class DatabaseLock implements Lock {\n private readonly ownerValue: string\n\n constructor(\n private readonly connection: DatabaseConnection,\n private readonly table: string,\n private readonly name: string,\n private readonly seconds: number | undefined,\n owner?: string,\n private readonly pollMs = 50,\n ) {\n this.ownerValue = owner ?? Str.random(20)\n }\n\n owner(): string {\n return this.ownerValue\n }\n\n async get<T = boolean>(callback?: () => T | Promise<T>): Promise<T | false> {\n const acquired = await this.acquire()\n if (!acquired) return false\n if (!callback) return true as T\n try {\n return await callback()\n } finally {\n await this.release()\n }\n }\n\n async block<T = boolean>(seconds: number, callback?: () => T | Promise<T>): Promise<T | true> {\n const deadline = Date.now() + seconds * 1000\n for (;;) {\n if (await this.acquire()) break\n if (Date.now() >= deadline) throw new LockTimeoutError(this.name)\n await sleep(this.pollMs)\n }\n if (!callback) return true\n try {\n return await callback()\n } finally {\n await this.release()\n }\n }\n\n async release(): Promise<boolean> {\n return this.connection.transaction(async (trx) => {\n const existing = await trx.table<LockRow>(this.table).where('key', this.name).lockForUpdate().first()\n if (!existing || existing.owner !== this.ownerValue) return false\n await trx.table(this.table).where('key', this.name).delete()\n return true\n })\n }\n\n async forceRelease(): Promise<void> {\n await this.connection.table(this.table).where('key', this.name).delete()\n }\n\n /**\n * Laravel's DatabaseLock::acquire(): an insert that skips a taken key, and then a conditional update that only takes\n * over an expired lock (no re-entry for the same owner, like RedisLock); see insertOrTakeOver.\n */\n private async acquire(): Promise<boolean> {\n const expiration = this.seconds === undefined ? now() + FOREVER_SECONDS : now() + Math.ceil(this.seconds)\n const row = { key: this.name, owner: this.ownerValue, expiration }\n return insertOrTakeOver(this.connection, this.table, row)\n }\n}\n","/**\n * Text for `database/migrations/..._create_cache_table.ts`. Cache does not own migrations — Database does — so\n * this is plain text for the coordinator's Wave-1 C2 skeleton step to copy in, not code Cache compiles against.\n * Mirrors Laravel 11's default cache migration: one file, two tables. `expiration` stays a plain `integer`\n * (int4/int, max 2147483647): DatabaseStore/DatabaseLock's \"forever\" is a 10-year TTL from now\n * (`FOREVER_SECONDS`), never a fixed epoch sentinel, so it always fits (B8).\n */\nexport const CACHE_TABLE_MIGRATION = `import { Migration, Schema } from '@orieljs/framework'\n\nexport default class extends Migration {\n async up() {\n await Schema.create('cache', (t) => {\n t.string('key').primary()\n t.text('value')\n t.integer('expiration')\n })\n await Schema.create('cache_locks', (t) => {\n t.string('key').primary()\n t.string('owner')\n t.integer('expiration')\n })\n }\n\n async down() {\n await Schema.dropIfExists('cache_locks')\n await Schema.dropIfExists('cache')\n }\n}\n`\n","import { createHash, randomUUID } from 'node:crypto'\nimport Redis from 'ioredis'\nimport { deserialize, roundTrip, serialize } from '../serialize'\nimport type { Store } from '../Store'\n\nexport interface RedisConfig {\n /** A prebuilt ioredis instance. A string here (Laravel's `'client' => 'phpredis'` style) is ignored. */\n client?: Redis | string\n url?: string\n [option: string]: unknown\n}\n\n/**\n * Builds an ioredis client from cache.stores.redis config: a prebuilt client, or a URL and/or raw ioredis\n * options. With a URL, the remaining options (db, password, lazyConnect...) are still passed through.\n */\nexport function makeRedisClient(config: RedisConfig): Redis {\n if (typeof config.client === 'object' && config.client !== null) return config.client\n const { client: _client, url, driver: _driver, prefix: _prefix, connection: _connection, ...options } = config\n if (typeof url === 'string') return new Redis(url, options)\n return new Redis(options)\n}\n\n/** Shared low-level redis primitives, parameterized only by the fully-computed key. No prefixing here on purpose:\n * RedisStore and RedisTaggedStore each compute their own keys and never rely on ioredis's `keyPrefix` client\n * option (which doesn't rewrite SCAN's MATCH pattern, making prefixed flush()/tag-namespace lookups unreliable). */\nabstract class RedisPrimitives {\n protected constructor(protected readonly redis: Redis) {}\n\n protected async rawGet(key: string): Promise<unknown> {\n const raw = await this.redis.get(key)\n return raw === null ? undefined : deserialize(raw)\n }\n\n protected async rawMany(keys: string[]): Promise<Record<string, unknown>> {\n if (keys.length === 0) return {}\n const values = await this.redis.mget(...keys)\n const result: Record<string, unknown> = {}\n keys.forEach((key, i) => {\n const raw = values[i]\n if (raw !== null && raw !== undefined) result[key] = deserialize(raw)\n })\n return result\n }\n\n protected async rawPut(key: string, value: unknown, ms?: number): Promise<boolean> {\n if (ms === undefined) await this.redis.set(key, serialize(roundTrip(value)))\n else await this.redis.set(key, serialize(roundTrip(value)), 'PX', Math.max(1, Math.round(ms)))\n return true\n }\n\n protected async rawAdd(key: string, value: unknown, ms?: number): Promise<boolean> {\n const result =\n ms === undefined\n ? await this.redis.set(key, serialize(roundTrip(value)), 'NX')\n : await this.redis.set(key, serialize(roundTrip(value)), 'PX', Math.max(1, Math.round(ms)), 'NX')\n return result === 'OK'\n }\n\n protected rawIncrement(key: string, by: number): Promise<number> {\n return this.redis.incrby(key, by)\n }\n\n protected async rawForget(key: string): Promise<boolean> {\n return (await this.redis.del(key)) > 0\n }\n}\n\nexport class RedisStore extends RedisPrimitives implements Store {\n constructor(\n redis: Redis,\n private readonly keyPrefix: string = '',\n ) {\n super(redis)\n }\n\n private k(key: string): string {\n return this.keyPrefix + key\n }\n\n getPrefix(): string {\n return this.keyPrefix\n }\n\n get(key: string): Promise<unknown> {\n return this.rawGet(this.k(key))\n }\n\n async many(keys: string[]): Promise<Record<string, unknown>> {\n const prefixed = keys.map((key) => this.k(key))\n const found = await this.rawMany(prefixed)\n const result: Record<string, unknown> = {}\n keys.forEach((key, i) => {\n const p = prefixed[i]!\n if (p in found) result[key] = found[p]\n })\n return result\n }\n\n put(key: string, value: unknown, seconds: number): Promise<boolean> {\n return this.rawPut(this.k(key), value, seconds * 1000)\n }\n\n putForever(key: string, value: unknown): Promise<boolean> {\n return this.rawPut(this.k(key), value)\n }\n\n add(key: string, value: unknown, seconds?: number): Promise<boolean> {\n return this.rawAdd(this.k(key), value, seconds === undefined ? undefined : seconds * 1000)\n }\n\n increment(key: string, by: number): Promise<number> {\n return this.rawIncrement(this.k(key), by)\n }\n\n decrement(key: string, by: number): Promise<number> {\n return this.rawIncrement(this.k(key), -by)\n }\n\n forget(key: string): Promise<boolean> {\n return this.rawForget(this.k(key))\n }\n\n async flush(): Promise<boolean> {\n let cursor = '0'\n do {\n const [next, keys] = await this.redis.scan(cursor, 'MATCH', `${this.keyPrefix}*`, 'COUNT', 200)\n cursor = next\n if (keys.length > 0) await this.redis.unlink(...keys)\n } while (cursor !== '0')\n return true\n }\n\n tags(names: string[]): RedisTaggedStore {\n return new RedisTaggedStore(this.redis, this.keyPrefix, names)\n }\n}\n\n/**\n * A namespaced view of the same redis database. Every tag has a version (a random id); the namespace is a hash\n * of the sorted tag=version pairs. flush() bumps every tag's version, orphaning previously-namespaced entries\n * (they aren't deleted — they expire on their own TTL) — this is Laravel's actual TagSet::reset() behaviour.\n */\nexport class RedisTaggedStore extends RedisPrimitives implements Store {\n constructor(\n redis: Redis,\n private readonly keyPrefix: string,\n private readonly tagNames: string[],\n ) {\n super(redis)\n }\n\n private async tagVersion(name: string): Promise<string> {\n const key = `${this.keyPrefix}tag:${name}:version`\n const existing = await this.redis.get(key)\n if (existing !== null) return existing\n const version = randomUUID()\n const set = await this.redis.set(key, version, 'NX')\n return set === 'OK' ? version : ((await this.redis.get(key)) ?? version)\n }\n\n private async namespace(): Promise<string> {\n const versions = await Promise.all(this.tagNames.map((name) => this.tagVersion(name)))\n const joined = this.tagNames.map((name, i) => `${name}=${versions[i]}`).sort().join('|')\n return createHash('sha1').update(joined).digest('hex').slice(0, 16)\n }\n\n private async k(key: string): Promise<string> {\n return `${this.keyPrefix}tags:${await this.namespace()}:${key}`\n }\n\n async get(key: string): Promise<unknown> {\n return this.rawGet(await this.k(key))\n }\n\n async many(keys: string[]): Promise<Record<string, unknown>> {\n const prefixed = await Promise.all(keys.map((key) => this.k(key)))\n const found = await this.rawMany(prefixed)\n const result: Record<string, unknown> = {}\n keys.forEach((key, i) => {\n const p = prefixed[i]!\n if (p in found) result[key] = found[p]\n })\n return result\n }\n\n async put(key: string, value: unknown, seconds: number): Promise<boolean> {\n return this.rawPut(await this.k(key), value, seconds * 1000)\n }\n\n async putForever(key: string, value: unknown): Promise<boolean> {\n return this.rawPut(await this.k(key), value)\n }\n\n async add(key: string, value: unknown, seconds?: number): Promise<boolean> {\n return this.rawAdd(await this.k(key), value, seconds === undefined ? undefined : seconds * 1000)\n }\n\n async increment(key: string, by: number): Promise<number> {\n return this.rawIncrement(await this.k(key), by)\n }\n\n async decrement(key: string, by: number): Promise<number> {\n return this.rawIncrement(await this.k(key), -by)\n }\n\n async forget(key: string): Promise<boolean> {\n return this.rawForget(await this.k(key))\n }\n\n async flush(): Promise<boolean> {\n await Promise.all(this.tagNames.map((name) => this.redis.set(`${this.keyPrefix}tag:${name}:version`, randomUUID())))\n return true\n }\n}\n","import { setTimeout as sleep } from 'node:timers/promises'\nimport type { Lock } from '@orieljs/contracts'\nimport type Redis from 'ioredis'\nimport { Str } from '@orieljs/support'\nimport { LockTimeoutError } from '../errors'\n\nconst RELEASE_SCRIPT = 'if redis.call(\"get\", KEYS[1]) == ARGV[1] then return redis.call(\"del\", KEYS[1]) else return 0 end'\n\n/** SET key value [PX ms] NX to acquire; a Lua script to release only if we still own it (compare-and-delete). */\nexport class RedisLock implements Lock {\n private readonly ownerValue: string\n\n constructor(\n private readonly redis: Redis,\n private readonly name: string,\n private readonly seconds: number | undefined,\n owner?: string,\n private readonly pollMs = 50,\n ) {\n this.ownerValue = owner ?? Str.random(20)\n }\n\n owner(): string {\n return this.ownerValue\n }\n\n async get<T = boolean>(callback?: () => T | Promise<T>): Promise<T | false> {\n const acquired = await this.acquire()\n if (!acquired) return false\n if (!callback) return true as T\n try {\n return await callback()\n } finally {\n await this.release()\n }\n }\n\n async block<T = boolean>(seconds: number, callback?: () => T | Promise<T>): Promise<T | true> {\n const deadline = Date.now() + seconds * 1000\n for (;;) {\n if (await this.acquire()) break\n if (Date.now() >= deadline) throw new LockTimeoutError(this.name)\n await sleep(this.pollMs)\n }\n if (!callback) return true\n try {\n return await callback()\n } finally {\n await this.release()\n }\n }\n\n async release(): Promise<boolean> {\n const result = await this.redis.eval(RELEASE_SCRIPT, 1, this.name, this.ownerValue)\n return result === 1\n }\n\n async forceRelease(): Promise<void> {\n await this.redis.del(this.name)\n }\n\n private async acquire(): Promise<boolean> {\n const result =\n this.seconds === undefined\n ? await this.redis.set(this.name, this.ownerValue, 'NX')\n : await this.redis.set(this.name, this.ownerValue, 'PX', Math.max(1, Math.round(this.seconds * 1000)), 'NX')\n return result === 'OK'\n }\n}\n","import type { CacheRepository } from '@orieljs/contracts'\nimport type Redis from 'ioredis'\nimport { RedisLock } from '../locks/RedisLock'\nimport { Repository } from '../Repository'\nimport { RedisStore } from './RedisStore'\n\n/** The only Repository subclass: the only store where tags() doesn't throw. */\nexport class RedisRepository extends Repository {\n constructor(\n private readonly redisStore: RedisStore,\n private readonly redis: Redis,\n ) {\n // Lock keys carry the store's prefix, like every cache key (and like Laravel's RedisStore::lock()).\n super(redisStore, (_store, name, seconds, owner) => new RedisLock(redis, redisStore.getPrefix() + name, seconds, owner))\n }\n\n override tags(names: string | string[]): CacheRepository {\n const list = Array.isArray(names) ? names : [names]\n const taggedStore = this.redisStore.tags(list)\n // Tagged locks use the same base prefix: tags namespace entries, not locks.\n const prefix = this.redisStore.getPrefix()\n return new Repository(taggedStore, (_store, name, seconds, owner) => new RedisLock(this.redis, prefix + name, seconds, owner))\n }\n}\n","import type { CacheRepository, Container } from '@orieljs/contracts'\nimport { CacheManager as CacheManagerToken, ConfigRepository, DatabaseManager } from '@orieljs/contracts'\nimport { UnknownCacheDriverError, UnknownCacheStoreError } from './errors'\nimport { DatabaseLock } from './locks/DatabaseLock'\nimport { Repository } from './Repository'\nimport { DatabaseStore } from './stores/DatabaseStore'\nimport { FileStore } from './stores/FileStore'\nimport { MemoryStore } from './stores/MemoryStore'\nimport { makeRedisClient, RedisStore } from './stores/RedisStore'\nimport { RedisRepository } from './stores/RedisRepository'\n\ntype StoreConfig = Record<string, unknown>\ntype Driver = (config: StoreConfig) => CacheRepository\n\n/**\n * Resolves the ioredis config for the `redis` cache driver, as a pure function so the fallback logic is testable\n * without a real redis connection. An inline `url` or client instance on `cache.stores.redis` wins and is passed straight\n * through; otherwise this falls back to `database.redis.<connection ?? 'default'>` (U3, Laravel's own\n * convention) — Session and Queue's redis connections resolve the exact same way, so one `database.redis`\n * config block covers every component that needs redis.\n */\nexport function resolveRedisConfig(cfg: StoreConfig, lookupDatabaseRedis: (connectionName: string) => StoreConfig): StoreConfig {\n const hasClient = typeof cfg.client === 'object' && cfg.client !== null\n if (cfg.url !== undefined || hasClient) return cfg\n const connectionName = (cfg.connection as string | undefined) ?? 'default'\n return { ...lookupDatabaseRedis(connectionName), ...cfg }\n}\n\ninterface CacheConfig {\n default: string\n prefix?: string\n stores: Record<string, StoreConfig>\n}\n\nexport class CacheManager implements CacheManagerToken {\n private readonly stores = new Map<string, CacheRepository>()\n private readonly drivers = new Map<string, Driver>()\n\n constructor(private readonly container: Container) {\n this.drivers.set('memory', (cfg) => new Repository(new MemoryStore(this.str(cfg.prefix), cfg.maxItems as number | undefined)))\n this.drivers.set('array', (cfg) => new Repository(new MemoryStore(this.str(cfg.prefix))))\n this.drivers.set('file', (cfg) => new Repository(new FileStore(cfg.path as string, this.str(cfg.prefix))))\n this.drivers.set('database', (cfg) => this.buildDatabaseStore(cfg))\n this.drivers.set('redis', (cfg) => this.buildRedisStore(cfg))\n }\n\n private str(value: unknown): string {\n return typeof value === 'string' ? value : ''\n }\n\n private cacheConfig(): CacheConfig {\n return this.container.make(ConfigRepository).get<CacheConfig>('cache', { default: 'database', stores: {} })\n }\n\n private buildDatabaseStore(cfg: StoreConfig): CacheRepository {\n const connection = this.container.make(DatabaseManager).connection(cfg.connection as string | undefined)\n const table = (cfg.table as string | undefined) ?? 'cache'\n const lockTable = (cfg.lockTable as string | undefined) ?? 'cache_locks'\n const prefix = this.str(cfg.prefix)\n const store = new DatabaseStore(connection, table, prefix)\n // Lock names carry the store's prefix, like every cache key (and like Laravel's DatabaseStore::lock()).\n return new Repository(store, (_store, name, seconds, owner) => new DatabaseLock(connection, lockTable, prefix + name, seconds, owner))\n }\n\n private buildRedisStore(cfg: StoreConfig): CacheRepository {\n const resolved = resolveRedisConfig(cfg, (connectionName) =>\n this.container.make(ConfigRepository).get<StoreConfig>(`database.redis.${connectionName}`, {}),\n )\n const redis = makeRedisClient(resolved)\n const store = new RedisStore(redis, this.str(cfg.prefix))\n return new RedisRepository(store, redis)\n }\n\n store(name?: string): CacheRepository {\n const cacheConfig = this.cacheConfig()\n const storeName = name ?? cacheConfig.default\n let repository = this.stores.get(storeName)\n if (!repository) {\n const storeConfig = cacheConfig.stores[storeName]\n if (!storeConfig) throw new UnknownCacheStoreError(storeName)\n const driverName = storeConfig.driver as string | undefined\n const driver = driverName ? this.drivers.get(driverName) : undefined\n if (!driver) throw new UnknownCacheDriverError(String(driverName))\n repository = driver({ ...storeConfig, prefix: storeConfig.prefix ?? cacheConfig.prefix ?? '' })\n this.stores.set(storeName, repository)\n }\n return repository\n }\n\n extend(driver: string, factory: Driver): void {\n this.drivers.set(driver, factory)\n }\n\n get<T = unknown>(key: string, defaultValue?: T | (() => T)): Promise<T | undefined> {\n return defaultValue === undefined ? this.store().get<T>(key) : this.store().get<T>(key, defaultValue)\n }\n many<T = unknown>(keys: string[]): Promise<Record<string, T | undefined>> {\n return this.store().many<T>(keys)\n }\n has(key: string): Promise<boolean> {\n return this.store().has(key)\n }\n missing(key: string): Promise<boolean> {\n return this.store().missing(key)\n }\n put(key: string, value: unknown, ttlSeconds?: number): Promise<boolean> {\n return this.store().put(key, value, ttlSeconds)\n }\n add(key: string, value: unknown, ttlSeconds?: number): Promise<boolean> {\n return this.store().add(key, value, ttlSeconds)\n }\n increment(key: string, by?: number): Promise<number> {\n return this.store().increment(key, by)\n }\n decrement(key: string, by?: number): Promise<number> {\n return this.store().decrement(key, by)\n }\n forever(key: string, value: unknown): Promise<boolean> {\n return this.store().forever(key, value)\n }\n pull<T = unknown>(key: string, defaultValue?: T): Promise<T | undefined> {\n return this.store().pull<T>(key, defaultValue)\n }\n forget(key: string): Promise<boolean> {\n return this.store().forget(key)\n }\n flush(): Promise<boolean> {\n return this.store().flush()\n }\n remember<T>(key: string, ttlSeconds: number, callback: () => T | Promise<T>): Promise<T> {\n return this.store().remember(key, ttlSeconds, callback)\n }\n rememberForever<T>(key: string, callback: () => T | Promise<T>): Promise<T> {\n return this.store().rememberForever(key, callback)\n }\n lock(name: string, seconds?: number, owner?: string) {\n return this.store().lock(name, seconds, owner)\n }\n tags(names: string | string[]): CacheRepository {\n return this.store().tags(names)\n }\n}\n","import type { CacheManager } from '@orieljs/contracts'\nimport { CacheManager as CacheManagerToken } from '@orieljs/contracts'\nimport { inject } from '@orieljs/container'\nimport { facade } from '@orieljs/support'\n\nexport const Cache = facade<CacheManager>(CacheManagerToken)\n\nexport function cache(): CacheManager\nexport function cache(key: string): Promise<unknown>\nexport function cache(values: Record<string, unknown>, ttlSeconds?: number): Promise<boolean>\nexport function cache(arg?: string | Record<string, unknown>, ttlSeconds?: number): unknown {\n const manager = inject(CacheManagerToken)\n if (arg === undefined) return manager\n if (typeof arg === 'string') return manager.get(arg)\n return Promise.all(Object.entries(arg).map(([key, value]) => manager.put(key, value, ttlSeconds))).then((results) =>\n results.every(Boolean),\n )\n}\n","import { CacheManager as CacheManagerToken } from '@orieljs/contracts'\nimport { ServiceProvider } from '@orieljs/support'\nimport { CacheManager } from './CacheManager'\n\nexport class CacheServiceProvider extends ServiceProvider {\n override register(): void {\n this.mergeConfigFrom(\n {\n default: 'database',\n prefix: '',\n stores: {\n array: { driver: 'array' },\n memory: { driver: 'memory' },\n file: { driver: 'file', path: this.app.storagePath('framework/cache/data') },\n database: { driver: 'database', table: 'cache', lockTable: 'cache_locks' },\n // Resolved from `database.redis.cache` (its own db), not `default`: flush() scans every key under the\n // prefix, so sharing a db with Queue or Session would wipe their keys too.\n redis: { driver: 'redis', connection: 'cache' },\n },\n },\n 'cache',\n )\n this.app.singleton(CacheManagerToken, (container) => new CacheManager(container))\n }\n}\n","import { ConsoleKernel, Schedule as ScheduleToken } from '@orieljs/contracts'\nimport { ServiceProvider } from '@orieljs/support'\nimport { AboutCommand } from './commands/AboutCommand'\nimport { HelpCommand } from './commands/HelpCommand'\nimport { ListCommand } from './commands/ListCommand'\nimport { MakeCastCommand } from './commands/make/MakeCastCommand'\nimport { MakeCommandCommand } from './commands/make/MakeCommandCommand'\nimport { MakeControllerCommand } from './commands/make/MakeControllerCommand'\nimport { MakeEventCommand } from './commands/make/MakeEventCommand'\nimport { MakeFactoryCommand } from './commands/make/MakeFactoryCommand'\nimport { MakeJobCommand } from './commands/make/MakeJobCommand'\nimport { MakeListenerCommand } from './commands/make/MakeListenerCommand'\nimport { MakeMailCommand } from './commands/make/MakeMailCommand'\nimport { MakeMiddlewareCommand } from './commands/make/MakeMiddlewareCommand'\nimport { MakeModelCommand } from './commands/make/MakeModelCommand'\nimport { MakeNotificationCommand } from './commands/make/MakeNotificationCommand'\nimport { MakeObserverCommand } from './commands/make/MakeObserverCommand'\nimport { MakePolicyCommand } from './commands/make/MakePolicyCommand'\nimport { MakeProviderCommand } from './commands/make/MakeProviderCommand'\nimport { MakeRequestCommand } from './commands/make/MakeRequestCommand'\nimport { MakeResourceCommand } from './commands/make/MakeResourceCommand'\nimport { MakeRuleCommand } from './commands/make/MakeRuleCommand'\nimport { MakeSeederCommand } from './commands/make/MakeSeederCommand'\nimport { MakeTestCommand } from './commands/make/MakeTestCommand'\nimport { ScheduleListCommand } from './commands/ScheduleListCommand'\nimport { ScheduleRunCommand } from './commands/ScheduleRunCommand'\nimport { ScheduleWorkCommand } from './commands/ScheduleWorkCommand'\nimport { TestCommand } from './commands/TestCommand'\nimport { TinkerCommand } from './commands/TinkerCommand'\nimport { discoverCommands, loadConsoleRoutes } from './discover'\nimport { Kernel } from './Kernel'\nimport { ScheduleImpl } from './Schedule'\n\nexport class ConsoleServiceProvider extends ServiceProvider {\n override register(): void {\n // Reserved for future per-stub override paths (spec §4.7 mentions an optional stub:publish, out of v1 scope).\n this.mergeConfigFrom({ stubs: {} }, 'console')\n this.app.singleton(ConsoleKernel, () => new Kernel(this.app))\n this.app.singleton(ScheduleToken, () => new ScheduleImpl())\n }\n\n override boot(): void {\n this.app\n .make(ConsoleKernel)\n .register(\n ListCommand,\n HelpCommand,\n AboutCommand,\n TestCommand,\n TinkerCommand,\n ScheduleRunCommand,\n ScheduleWorkCommand,\n ScheduleListCommand,\n MakeControllerCommand,\n MakeModelCommand,\n MakeMiddlewareCommand,\n MakeRequestCommand,\n MakeCommandCommand,\n MakeEventCommand,\n MakeListenerCommand,\n MakeJobCommand,\n MakeMailCommand,\n MakeNotificationCommand,\n MakePolicyCommand,\n MakeProviderCommand,\n MakeSeederCommand,\n MakeFactoryCommand,\n MakeRuleCommand,\n MakeCastCommand,\n MakeObserverCommand,\n MakeResourceCommand,\n MakeTestCommand,\n )\n\n // Like Laravel's console kernel bootstrap: only in the console (the oriel CLI, or a test calling artisan()),\n // and after every provider, the app's own included, has booted.\n this.app.booted(async (app) => {\n if (!app.runningInConsole()) return\n const kernel = app.make(ConsoleKernel)\n await discoverCommands(kernel, app.appPath('Console/Commands'))\n await loadConsoleRoutes(app, kernel)\n })\n }\n}\n","import { Application, ConfigRepository } from '@orieljs/contracts'\nimport { currentContainer, inject } from '@orieljs/container'\nimport { Command } from '../Command'\n\nexport class AboutCommand extends Command {\n override readonly signature = 'about'\n override description = 'Display basic information about your application'\n\n override handle(): number {\n const app = inject(Application)\n const container = currentContainer()\n const config = container?.bound(ConfigRepository) ? container.make(ConfigRepository) : undefined\n const read = (key: string, fallback: unknown): unknown => (config ? config.get(key, fallback) : fallback)\n\n this.table(\n ['Property', 'Value'],\n [\n ['Application Name', String(read('app.name', 'Oriel'))],\n ['Oriel Version', app.version],\n ['Node Version', process.version],\n ['Environment', app.environment()],\n ['Debug Mode', String(read('app.debug', false))],\n ['URL', String(read('app.url', '(none)'))],\n ],\n )\n return 0\n }\n}\n","import type { CommandContext, ConsoleKernel as ConsoleKernelContract, OptionValue } from '@orieljs/contracts'\nimport { ConsoleKernel } from '@orieljs/contracts'\nimport { inject } from '@orieljs/container'\nimport { InvalidSignatureError } from './errors'\nimport type { ConsoleInput, ConsoleIo, ConsoleOutput } from './io'\nimport { NodeConsoleInput, NodeConsoleOutput } from './io'\n\nexport type { OptionValue } from '@orieljs/contracts'\n\n/** Console's Kernel also runs a nested command with the caller's I/O, so `this.call()` output isn't swallowed. */\ninterface IoCallingKernel extends ConsoleKernelContract {\n callWithIo?(command: string, parameters: Record<string, unknown>, io: ConsoleIo): Promise<number>\n}\n\n/**\n * The Laravel-style CLI command base class. Concrete commands declare `signature` and implement `handle()`.\n * It implements the contract `CommandContext`, which is `this` inside closure commands.\n */\nexport abstract class Command implements CommandContext {\n abstract readonly signature: string\n description = ''\n\n private boundArguments: Record<string, string | string[]> = {}\n private boundOptions: Record<string, OptionValue> = {}\n private consoleOutput: ConsoleOutput = new NodeConsoleOutput()\n private consoleInput: ConsoleInput = new NodeConsoleInput()\n\n abstract handle(): number | void | Promise<number | void>\n\n /** @internal Set by the kernel before handle() runs. */\n bind(args: Record<string, string | string[]>, options: Record<string, OptionValue>, io: ConsoleIo): void {\n this.boundArguments = args\n this.boundOptions = options\n this.consoleInput = io.input\n this.consoleOutput = io.output\n }\n\n argument(name: string): string | string[] | undefined {\n return this.boundArguments[name]\n }\n\n arguments(): Record<string, string | string[]> {\n return { ...this.boundArguments }\n }\n\n /** undefined when the option isn't declared, or when it's a value option with no default and none was passed. */\n option(name: string): OptionValue {\n return this.boundOptions[name]\n }\n\n options(): Record<string, OptionValue> {\n return { ...this.boundOptions }\n }\n\n info(message: string): void {\n this.consoleOutput.write(`${message}\\n`)\n }\n line(message = ''): void {\n this.consoleOutput.write(`${message}\\n`)\n }\n comment(message: string): void {\n this.consoleOutput.write(`${message}\\n`)\n }\n warn(message: string): void {\n this.consoleOutput.writeError(`${message}\\n`)\n }\n error(message: string): void {\n this.consoleOutput.writeError(`${message}\\n`)\n }\n newLine(count = 1): void {\n this.consoleOutput.write('\\n'.repeat(count))\n }\n\n table(headers: string[], rows: string[][]): void {\n const widths = headers.map((header, i) => Math.max(header.length, ...rows.map((row) => (row[i] ?? '').length)))\n const border = `+${widths.map((w) => '-'.repeat(w + 2)).join('+')}+`\n const renderRow = (cells: string[]) => `| ${cells.map((cell, i) => (cell ?? '').padEnd(widths[i]!)).join(' | ')} |`\n this.line(border)\n this.line(renderRow(headers))\n this.line(border)\n for (const row of rows) this.line(renderRow(row))\n this.line(border)\n }\n\n async ask(question: string, defaultValue?: string): Promise<string> {\n const suffix = defaultValue !== undefined ? ` (${defaultValue})` : ''\n const answer = (await this.consoleInput.question(`${question}${suffix}: `)).trim()\n return answer === '' && defaultValue !== undefined ? defaultValue : answer\n }\n\n /** v1 simplification: reads through the same stream as ask(), without suppressing terminal echo. */\n async secret(question: string): Promise<string> {\n return this.ask(question)\n }\n\n async confirm(question: string, defaultValue = false): Promise<boolean> {\n const hint = defaultValue ? 'Y/n' : 'y/N'\n const answer = (await this.consoleInput.question(`${question} (${hint}): `)).trim().toLowerCase()\n if (answer === '') return defaultValue\n return answer === 'y' || answer === 'yes'\n }\n\n async choice(question: string, choices: string[], defaultIndex?: number): Promise<string> {\n this.line(question)\n choices.forEach((choice, i) => this.line(` [${i}] ${choice}`))\n const defaultValue = defaultIndex !== undefined ? choices[defaultIndex] : undefined\n const answer = await this.ask('Choice', defaultValue)\n if (choices.includes(answer)) return answer\n const index = Number(answer)\n if (Number.isInteger(index) && choices[index] !== undefined) return choices[index]!\n throw new InvalidSignatureError(`\"${answer}\" is not a valid choice.`)\n }\n\n /**\n * Runs another command through the kernel, but only if a component actually registered it. Like Laravel's\n * `$this->call()`, the nested command writes to this command's output.\n */\n protected async call(command: string, parameters: Record<string, unknown> = {}): Promise<number | undefined> {\n const kernel = inject(ConsoleKernel) as IoCallingKernel\n if (!(command in kernel.all())) return undefined\n if (kernel.callWithIo)\n return kernel.callWithIo(command, parameters, { input: this.consoleInput, output: this.consoleOutput })\n return kernel.call(command, parameters)\n }\n}\n","import type { OrielError } from '@orieljs/contracts'\n\n/**\n * CLI-only errors. Not `OrielError`: they never reach the HTTP exception handler (Contracts/Exceptions.ts's\n * ErrorKind union has no CLI member), and only ConsoleKernel.handle() ever catches them.\n */\nexport class InvalidSignatureError extends Error {\n override readonly name = 'InvalidSignatureError'\n}\n\nexport class CommandNotFoundError extends Error {\n constructor(\n message: string,\n readonly suggestions: string[] = [],\n ) {\n super(message)\n }\n override readonly name = 'CommandNotFoundError'\n}\n\n/**\n * Thrown by `withoutOverlapping()`/`onOneServer()` on a closure event (`call()`/`job()`) that has no `name()` yet —\n * Laravel's `CallbackEvent` throws the same message, since the mutex key for a closure event is `sha1(name())`\n * Unlike the two errors above, this one *can* be raised outside `ConsoleKernel.handle()`\n * (schedule building happens in `routes/console.ts`, not inside a running command), so it implements `OrielError`\n * with kind `'Server'`/status 500.\n */\nexport class ScheduleNameRequiredError extends Error implements OrielError {\n readonly kind = 'Server' as const\n readonly status = 500 as const\n override readonly name = 'ScheduleNameRequiredError'\n constructor(method: 'withoutOverlapping' | 'onOneServer') {\n super(`A scheduled event name is required to prevent overlapping. Use the 'name' method before '${method}'.`)\n }\n}\n","import type { Interface } from 'node:readline'\n\nexport interface ConsoleOutput {\n write(text: string): void\n writeError(text: string): void\n}\n\n/** Resolves with the line typed, without the trailing newline. */\nexport interface ConsoleInput {\n question(prompt: string): Promise<string>\n /** Releases whatever the input holds open (stdin), once the outermost command has finished. */\n close?(): void\n}\n\n/** The input/output pair a command runs with. */\nexport interface ConsoleIo {\n input: ConsoleInput\n output: ConsoleOutput\n}\n\nexport class NodeConsoleOutput implements ConsoleOutput {\n write(text: string): void {\n process.stdout.write(text)\n }\n writeError(text: string): void {\n process.stderr.write(text)\n }\n}\n\nexport class BufferedConsoleOutput implements ConsoleOutput {\n private out = ''\n private err = ''\n write(text: string): void {\n this.out += text\n }\n writeError(text: string): void {\n this.err += text\n }\n get stdout(): string {\n return this.out\n }\n get stderr(): string {\n return this.err\n }\n get combined(): string {\n return this.out + this.err\n }\n}\n\n/**\n * Reads answers from stdin through one readline interface, created on the first prompt and reused after that, so\n * piped input that arrives all at once keeps every line. Lines read ahead of a prompt are queued for the next one.\n * `close()` releases stdin so the process can exit; the next prompt opens a fresh interface.\n */\nexport class NodeConsoleInput implements ConsoleInput {\n private rl: Interface | undefined\n private lines: string[] = []\n private waiting: Array<{ resolve: (line: string) => void; reject: (error: Error) => void }> = []\n private ended = false\n\n constructor(\n private readonly input: NodeJS.ReadableStream = process.stdin,\n private readonly output: NodeJS.WritableStream = process.stdout,\n ) {}\n\n async question(prompt: string): Promise<string> {\n const rl = await this.open()\n if (this.ended) {\n this.output.write(prompt)\n } else {\n rl.setPrompt(prompt)\n rl.prompt()\n }\n const line = this.lines.shift()\n if (line !== undefined) return line\n if (this.ended) throw new Error('Aborted.')\n return new Promise((resolve, reject) => this.waiting.push({ resolve, reject }))\n }\n\n close(): void {\n const rl = this.rl\n this.rl = undefined\n rl?.close()\n this.lines = []\n this.ended = false\n }\n\n private async open(): Promise<Interface> {\n if (this.rl) return this.rl\n const { createInterface } = await import('node:readline')\n if (this.rl) return this.rl\n const rl = createInterface({ input: this.input, output: this.output })\n rl.on('line', (line) => {\n const next = this.waiting.shift()\n if (next) next.resolve(line)\n else this.lines.push(line)\n })\n rl.on('close', () => {\n if (this.rl !== rl) return\n this.ended = true\n for (const { reject } of this.waiting.splice(0)) reject(new Error('Aborted.'))\n })\n this.rl = rl\n return rl\n }\n}\n\n/** Feeds pre-recorded answers to ask()/confirm()/choice()/secret() in tests, without a TTY. */\nexport class QueuedConsoleInput implements ConsoleInput {\n private readonly queue: string[]\n constructor(answers: string[] = []) {\n this.queue = [...answers]\n }\n async question(_prompt: string): Promise<string> {\n if (this.queue.length === 0) throw new Error('QueuedConsoleInput ran out of answers.')\n return this.queue.shift()!\n }\n}\n","import { ConsoleKernel } from '@orieljs/contracts'\nimport { inject } from '@orieljs/container'\nimport { Command } from '../Command'\nimport { parseSignature } from '../signature'\n\nexport class HelpCommand extends Command {\n override readonly signature = 'help {command_name? : The command to show help for}'\n override description = 'Display help for a command'\n\n override handle(): number {\n const kernel = inject(ConsoleKernel)\n const name = (this.argument('command_name') as string | undefined) ?? 'help'\n const target = kernel.all()[name]\n if (!target) {\n this.error(`Command \"${name}\" is not defined.`)\n return 1\n }\n\n const signature = parseSignature(target.signature)\n this.line('Description:')\n this.line(` ${target.description || '(no description)'}`)\n this.newLine()\n\n const hasOptions = signature.options.length > 0\n const hasArguments = signature.arguments.length > 0\n const usage = [\n name,\n ...(hasOptions ? ['[options]'] : []),\n ...(hasOptions && hasArguments ? ['[--]'] : []),\n ...signature.arguments.map((a) => (a.required ? `<${a.name}>` : `[${a.name}]`)),\n ]\n const flagOf = (opt: (typeof signature.options)[number]): string =>\n opt.shortcut ? `-${opt.shortcut}, --${opt.name}` : `--${opt.name}`\n const width = Math.max(\n 0,\n ...signature.arguments.map((a) => a.name.length),\n ...signature.options.map((o) => flagOf(o).length),\n )\n this.line('Usage:')\n this.line(` ${usage.join(' ')}`)\n\n if (hasArguments) {\n this.newLine()\n this.line('Arguments:')\n for (const arg of signature.arguments) this.line(` ${arg.name.padEnd(width)} ${arg.description}`)\n }\n if (hasOptions) {\n this.newLine()\n this.line('Options:')\n for (const opt of signature.options) this.line(` ${flagOf(opt).padEnd(width)} ${opt.description}`)\n }\n return 0\n }\n}\n","import type { OptionValue } from '@orieljs/contracts'\nimport { InvalidSignatureError } from './errors'\n\nexport interface ArgumentDefinition {\n readonly name: string\n readonly description: string\n readonly required: boolean\n readonly variadic: boolean\n readonly default: string | string[] | undefined\n}\n\nexport interface OptionDefinition {\n readonly name: string\n readonly shortcut: string | undefined\n readonly description: string\n readonly mode: 'flag' | 'value' | 'array'\n readonly default: string | string[] | boolean | undefined\n}\n\nexport interface ParsedSignature {\n readonly name: string\n readonly arguments: ArgumentDefinition[]\n readonly options: OptionDefinition[]\n}\n\nexport interface ParsedInput {\n arguments: Record<string, string | string[]>\n options: Record<string, string | string[] | true>\n}\n\nconst PARAMETER = /\\{(.+?)\\}/g\nconst ARGUMENT_SHAPE = /^([A-Za-z][A-Za-z0-9_-]*)(\\?)?(\\*)?(?:=(.*))?$/\nconst OPTION_SHAPE = /^(?:([A-Za-z])\\|)?([A-Za-z][A-Za-z0-9_-]*)(=)?(.*)?$/\n\nfunction splitDescription(body: string): [string, string] {\n const index = body.indexOf(' : ')\n return index === -1 ? [body.trim(), ''] : [body.slice(0, index).trim(), body.slice(index + 3).trim()]\n}\n\nfunction parseArgument(body: string): ArgumentDefinition {\n const [spec, description] = splitDescription(body)\n const match = ARGUMENT_SHAPE.exec(spec)\n if (!match) throw new InvalidSignatureError(`Invalid argument definition: {${body}}`)\n const [, name, optional, variadic, rawDefault] = match\n const isVariadic = variadic === '*'\n const hasDefault = rawDefault !== undefined\n return {\n name: name!,\n description,\n required: isVariadic ? !optional : !optional && !hasDefault,\n variadic: isVariadic,\n default: hasDefault ? (isVariadic ? (rawDefault === '' ? [] : rawDefault!.split(',')) : rawDefault) : undefined,\n }\n}\n\nfunction parseOption(body: string): OptionDefinition {\n const [spec, description] = splitDescription(body)\n const match = OPTION_SHAPE.exec(spec)\n if (!match) throw new InvalidSignatureError(`Invalid option definition: {--${body}}`)\n const [, shortcut, name, equals, rawDefault] = match\n if (!equals) return { name: name!, shortcut, description, mode: 'flag', default: false }\n if (rawDefault === '*') return { name: name!, shortcut, description, mode: 'array', default: [] }\n return { name: name!, shortcut, description, mode: 'value', default: rawDefault === '' ? undefined : rawDefault! }\n}\n\n/** Parses a Laravel-style signature: `'mail:send {user} {--queue=default}'`. */\nexport function parseSignature(signature: string): ParsedSignature {\n const name = signature.trim().split(/\\s+/)[0] ?? ''\n if (name === '') throw new InvalidSignatureError('A command signature needs a name.')\n const args: ArgumentDefinition[] = []\n const options: OptionDefinition[] = []\n for (const match of signature.matchAll(PARAMETER)) {\n const body = match[1]!.trim()\n if (body.startsWith('--')) options.push(parseOption(body.slice(2)))\n else args.push(parseArgument(body))\n }\n return { name, arguments: args, options }\n}\n\n/**\n * Records one option. A value/array option with no inline value takes the next token (`--queue high`), unless that\n * token is missing or starts with `-`; then nothing is recorded and the declared default applies (Symfony's\n * VALUE_OPTIONAL). Returns how many extra argv tokens it consumed.\n */\nfunction applyOption(\n options: ParsedInput['options'],\n def: OptionDefinition,\n inline: string | undefined,\n next: string | undefined,\n): number {\n if (def.mode === 'flag') {\n options[def.name] = true\n return 0\n }\n const takesNext = inline === undefined && next !== undefined && !next.startsWith('-')\n const value = takesNext ? next : inline\n if (value === undefined) return 0\n if (def.mode === 'array') {\n const existing = options[def.name]\n options[def.name] = Array.isArray(existing) ? [...existing, value] : [value]\n } else {\n options[def.name] = value\n }\n return takesNext ? 1 : 0\n}\n\n/**\n * Handles a single `-x...` token. Symfony-style shortcut expansion: each character is looked up as a shortcut in\n * turn. A flag shortcut just sets its flag and moves to the next character (`-mfc` -> `-m -f -c`). A value/array\n * shortcut consumes the *rest* of the token as its inline value (or, if nothing is left, the next argv token, same\n * as a lone `-Q high`) and ends the token — nothing follows a value. An unknown character throws the same error a\n * standalone unknown shortcut throws.\n */\nfunction applyShortcutToken(\n options: ParsedInput['options'],\n token: string,\n next: string | undefined,\n shortcuts: Map<string, string>,\n byName: Map<string, OptionDefinition>,\n): number {\n let pos = 1\n while (pos < token.length) {\n const shortcutChar = token[pos]!\n const name = shortcuts.get(shortcutChar)\n if (!name) throw new InvalidSignatureError(`The \"-${shortcutChar}\" option does not exist.`)\n const def = byName.get(name)!\n if (def.mode === 'flag') {\n options[def.name] = true\n pos++\n continue\n }\n const rest = token.slice(pos + 1)\n const inline = rest === '' ? undefined : rest.replace(/^=/, '')\n return applyOption(options, def, inline, next)\n }\n return 0\n}\n\n/** Parses argv (without the command name) against a signature already produced by parseSignature(). */\nexport function parseArgv(argv: string[], signature: ParsedSignature): ParsedInput {\n const shortcuts = new Map(signature.options.filter((o) => o.shortcut).map((o) => [o.shortcut!, o.name]))\n const byName = new Map(signature.options.map((o) => [o.name, o]))\n const options: ParsedInput['options'] = {}\n const positionals: string[] = []\n\n for (let i = 0; i < argv.length; i++) {\n const token = argv[i]!\n if (token === '--') {\n positionals.push(...argv.slice(i + 1))\n break\n }\n if (token.startsWith('--')) {\n const eq = token.indexOf('=')\n const name = eq === -1 ? token.slice(2) : token.slice(2, eq)\n const inline = eq === -1 ? undefined : token.slice(eq + 1)\n const def = byName.get(name)\n if (!def) throw new InvalidSignatureError(`The \"--${name}\" option does not exist.`)\n i += applyOption(options, def, inline, argv[i + 1])\n } else if (token.length > 1 && token.startsWith('-')) {\n i += applyShortcutToken(options, token, argv[i + 1], shortcuts, byName)\n } else {\n positionals.push(token)\n }\n }\n\n const args: ParsedInput['arguments'] = {}\n let cursor = 0\n for (const arg of signature.arguments) {\n if (arg.variadic) {\n args[arg.name] = positionals.slice(cursor)\n cursor = positionals.length\n } else if (cursor < positionals.length) {\n args[arg.name] = positionals[cursor]!\n cursor++\n }\n }\n if (cursor < positionals.length) {\n const expected = signature.arguments.map((arg) => `\"${arg.name}\"`).join(' ')\n throw new InvalidSignatureError(\n expected === ''\n ? `No arguments expected, got \"${positionals[cursor]}\".`\n : `Too many arguments, expected arguments ${expected}.`,\n )\n }\n return { arguments: args, options }\n}\n\n/** Throws InvalidSignatureError naming the first missing required argument. */\nexport function validateRequiredArguments(signature: ParsedSignature, input: ParsedInput): void {\n for (const arg of signature.arguments) {\n const value = input.arguments[arg.name]\n const missing = arg.variadic ? !Array.isArray(value) || value.length === 0 : value === undefined\n if (arg.required && missing) throw new InvalidSignatureError(`Not enough arguments (missing: \"${arg.name}\").`)\n }\n}\n\n/** Applies declared defaults (including [] for a missing variadic) to whatever parseArgv found. */\nexport function resolveArguments(signature: ParsedSignature, input: ParsedInput): Record<string, string | string[]> {\n const result: Record<string, string | string[]> = { ...input.arguments }\n for (const arg of signature.arguments) {\n if (arg.name in result) continue\n if (arg.default !== undefined) result[arg.name] = arg.default\n else if (arg.variadic) result[arg.name] = []\n }\n return result\n}\n\n/** Every declared option, resolved to what was passed or its declared default (flag: false, value: undefined unless a default was set, array: []). */\nexport function resolveOptions(signature: ParsedSignature, input: ParsedInput): Record<string, OptionValue> {\n const result: Record<string, OptionValue> = {}\n for (const opt of signature.options) {\n result[opt.name] = opt.name in input.options ? input.options[opt.name]! : opt.default\n }\n return result\n}\n","import { ConsoleKernel } from '@orieljs/contracts'\nimport { inject } from '@orieljs/container'\nimport { Command } from '../Command'\n\nexport class ListCommand extends Command {\n override readonly signature = 'list {namespace? : Only list commands in this namespace}'\n override description = 'List commands'\n\n override handle(): number {\n const all = inject(ConsoleKernel).all()\n const namespace = this.argument('namespace') as string | undefined\n const names = Object.keys(all)\n .filter((name) => namespace === undefined || name === namespace || name.startsWith(`${namespace}:`))\n .sort()\n const width = Math.max(0, ...names.map((name) => name.length))\n const describe = (name: string): string => ` ${name.padEnd(width)} ${all[name]!.description}`\n\n this.line('Available commands:')\n\n // Un-namespaced commands print first, then namespaced ones grouped under a header line,\n // regardless of where the namespace would otherwise fall alphabetically.\n const unnamespaced = names.filter((name) => !name.includes(':'))\n const namespaced = names.filter((name) => name.includes(':'))\n\n for (const name of unnamespaced) this.line(describe(name))\n\n let currentGroup: string | undefined\n for (const name of namespaced) {\n const group = name.slice(0, name.indexOf(':'))\n if (group !== currentGroup) this.line(` ${group}`)\n currentGroup = group\n this.line(describe(name))\n }\n return 0\n }\n}\n","import { existsSync } from 'node:fs'\nimport { mkdir, writeFile } from 'node:fs/promises'\nimport { dirname, join, relative, sep } from 'node:path'\nimport { Application } from '@orieljs/contracts'\nimport { inject } from '@orieljs/container'\nimport { Str } from '@orieljs/support'\nimport { Command } from '../../Command'\n\nfunction render(stub: string, replacements: Record<string, string>): string {\n return stub.replace(/\\{\\{\\s*(\\w+)\\s*\\}\\}/g, (_match, key: string) => replacements[key] ?? '')\n}\n\n/** Shared machinery for every make:* generator: resolves the target path, renders the stub, writes the file. */\nexport abstract class GeneratorCommand extends Command {\n /** Subpath under appPath(), e.g. 'Http/Controllers'. */\n protected abstract type(): string\n /** The stub template, with {{ placeholder }} tokens. */\n protected abstract stub(): string\n /** Appended to the class name if it isn't already there, e.g. 'Controller'. */\n protected suffix(): string {\n return ''\n }\n /** Extra {{ placeholder }} values beyond {{ class }}. */\n protected extraPlaceholders(_rawName: string): Record<string, string> {\n return {}\n }\n\n protected qualifyClass(rawName: string): { directories: string[]; className: string } {\n const segments = rawName\n .split('/')\n .filter(Boolean)\n .map((part) => Str.studly(part))\n const last = segments.pop()\n if (!last) throw new Error('A name is required.')\n const suffix = this.suffix()\n const className = suffix && !last.endsWith(suffix) ? `${last}${suffix}` : last\n return { directories: segments, className }\n }\n\n /** Where generated files are rooted. Overridden by seeders/factories, which live under database/. */\n protected root(subpath: string): string {\n return inject(Application).appPath(subpath)\n }\n\n /** The generated file's name, given its class name. Overridden by make:test for a `.test.ts` suffix. */\n protected fileName(className: string): string {\n return `${className}.ts`\n }\n\n protected targetPath(rawName: string): string {\n const { directories, className } = this.qualifyClass(rawName)\n return join(this.root(this.type()), ...directories, this.fileName(className))\n }\n\n /** The singular kind of file for messages, like Laravel's `$type`: 'Http/Controllers' -> 'Controller'. */\n protected kind(): string {\n return Str.ucfirst(Str.singular(this.type().split('/').pop()!))\n }\n\n /** The import specifier from the generated file to `target` (an absolute path without extension): './X', '../Y/X'. */\n protected importPath(rawName: string, target: string): string {\n const specifier = relative(dirname(this.targetPath(rawName)), target)\n .split(sep)\n .join('/')\n return specifier.startsWith('.') ? specifier : `./${specifier}`\n }\n\n override async handle(): Promise<number> {\n const rawName = this.argument('name') as string | undefined\n if (!rawName) {\n this.error('A name is required.')\n return 1\n }\n const target = this.targetPath(rawName)\n if (existsSync(target) && !this.option('force')) {\n this.error(`${this.kind()} already exists.`)\n return 1\n }\n const { className } = this.qualifyClass(rawName)\n const rendered = render(this.stub(), { class: className, ...this.extraPlaceholders(rawName) })\n await mkdir(dirname(target), { recursive: true })\n await writeFile(target, rendered, 'utf8')\n this.info(`${this.kind()} [${target}] created successfully.`)\n return 0\n }\n}\n","export const CONTROLLER_STUB = `import { Controller } from '{{ controllerImport }}'\n\nexport class {{ class }} extends Controller {\n //\n}\n`\n\nexport const CONTROLLER_STUB_RESOURCE = `import { Controller } from '{{ controllerImport }}'\n\nexport class {{ class }} extends Controller {\n async index() {\n //\n }\n\n async create() {\n //\n }\n\n async store() {\n //\n }\n\n async show({{ variable }}: unknown) {\n //\n }\n\n async edit({{ variable }}: unknown) {\n //\n }\n\n async update({{ variable }}: unknown) {\n //\n }\n\n async destroy({{ variable }}: unknown) {\n //\n }\n}\n`\n\nexport const CONTROLLER_STUB_API = `import { Controller } from '{{ controllerImport }}'\n\nexport class {{ class }} extends Controller {\n async index() {\n //\n }\n\n async store() {\n //\n }\n\n async show({{ variable }}: unknown) {\n //\n }\n\n async update({{ variable }}: unknown) {\n //\n }\n\n async destroy({{ variable }}: unknown) {\n //\n }\n}\n`\n\nexport const MODEL_STUB = `import { Model } from '@orieljs/framework'\n\nexport class {{ class }} extends Model {\n protected override fillable: string[] = []\n}\n`\n\nexport const MIDDLEWARE_STUB = `import type { HttpRequest, Middleware, Next } from '@orieljs/framework/contracts'\n\nexport class {{ class }} implements Middleware {\n async handle(request: HttpRequest, next: Next): Promise<Response> {\n return next(request)\n }\n}\n`\n\n/** FormRequest.rules() is abstract; authorize() overrides its concrete default, so only it keeps `override`. */\nexport const REQUEST_STUB = `import { FormRequest } from '@orieljs/framework'\n\nexport class {{ class }} extends FormRequest {\n override authorize(): boolean {\n return true\n }\n\n rules(): Record<string, string> {\n return {}\n }\n}\n`\n\n/** Command's signature/handle are abstract; description overrides its concrete default, so only it keeps `override`. */\nexport const COMMAND_STUB = `import { Command } from '@orieljs/framework'\n\nexport class {{ class }} extends Command {\n readonly signature = '{{ signature }}'\n override description = ''\n\n async handle(): Promise<number | void> {\n //\n }\n}\n`\n\nexport const EVENT_STUB = `export class {{ class }} {\n constructor() {}\n}\n`\n\n/** Events discovers a listener in app/Listeners by its static listensTo (09-events.md). */\nexport const LISTENER_STUB = `import { {{ event }} } from '{{ eventImport }}'\n\nexport class {{ class }} {\n static listensTo = {{ event }}\n\n async handle(_event: {{ event }}): Promise<void> {\n //\n }\n}\n`\n\nexport const LISTENER_STUB_PLAIN = `export class {{ class }} {\n // Name the event class (or event name) this listener handles, so app/Listeners discovery registers it:\n // static listensTo = OrderShipped\n\n async handle(_event: unknown): Promise<void> {\n //\n }\n}\n`\n\n/** Queueable carries Bus's shouldQueue marker, so dispatch() queues the job (Laravel's ShouldQueue job). */\nexport const JOB_STUB = `import { Queueable } from '@orieljs/framework'\n\nexport class {{ class }} extends Queueable {\n async handle(): Promise<void> {\n //\n }\n}\n`\n\n/** make:job --sync: Dispatchable gives the dispatch() statics without queueing. */\nexport const JOB_STUB_SYNC = `import { Dispatchable } from '@orieljs/framework'\n\nexport class {{ class }} extends Dispatchable {\n async handle(): Promise<void> {\n //\n }\n}\n`\n\nexport const MAIL_STUB = `import { Mailable } from '@orieljs/framework'\nimport type { Content, Envelope } from '@orieljs/framework/contracts'\n\nexport class {{ class }} extends Mailable {\n override async envelope(): Promise<Envelope> {\n return { subject: '{{ subject }}' }\n }\n\n override async content(): Promise<Content> {\n return { view: '{{ view }}' }\n }\n}\n`\n\nexport const NOTIFICATION_STUB = `import { MailMessage, Notification } from '@orieljs/framework'\nimport type { Notifiable } from '@orieljs/framework/contracts'\n\nexport class {{ class }} extends Notification {\n via(_notifiable: Notifiable): string[] {\n return ['mail']\n }\n\n toMail(_notifiable: Notifiable): MailMessage {\n return new MailMessage()\n .line('The introduction to the notification.')\n .action('Notification Action', '/')\n .line('Thank you for using our application!')\n }\n\n toArray(_notifiable: Notifiable): Record<string, unknown> {\n return {}\n }\n}\n`\n\nexport const POLICY_STUB = `export class {{ class }} {\n view(_user: unknown, _model: unknown): boolean {\n return true\n }\n\n create(_user: unknown): boolean {\n return true\n }\n\n update(_user: unknown, _model: unknown): boolean {\n return true\n }\n\n delete(_user: unknown, _model: unknown): boolean {\n return true\n }\n}\n`\n\nexport const PROVIDER_STUB = `import { ServiceProvider } from '@orieljs/framework'\n\nexport class {{ class }} extends ServiceProvider {\n override register(): void {\n //\n }\n\n override boot(): void {\n //\n }\n}\n`\n\n/** db:seed loads the default export and requires a Seeder subclass (03-database.md). */\nexport const SEEDER_STUB = `import { Seeder } from '@orieljs/framework'\n\nexport default class {{ class }} extends Seeder {\n async run(): Promise<void> {\n //\n }\n}\n`\n\n/** Factory discovery registers exported Factory subclasses; \\`model\\` is abstract on the base (03-database.md). */\nexport const FACTORY_STUB = `import { Factory } from '@orieljs/framework'\nimport { {{ model }} } from '{{ modelImport }}'\n\nexport default class {{ class }} extends Factory<{{ model }}> {\n model = {{ model }}\n\n definition() {\n return {\n //\n }\n }\n}\n`\n\nexport const RULE_STUB = `import type { ValidationRule } from '@orieljs/framework/contracts'\n\nexport class {{ class }} implements ValidationRule {\n validate(_attribute: string, _value: unknown, _fail: (message: string) => void): void {\n //\n }\n}\n`\n\n/** Database calls get(model, key, value, attributes) and set(model, key, value, attributes) (03-database.md). */\nexport const CAST_STUB = `import type { CastsAttributes } from '@orieljs/framework'\n\nexport class {{ class }} implements CastsAttributes {\n get(_model: object, _key: string, value: unknown, _attributes: Record<string, unknown>): unknown {\n return value\n }\n\n set(_model: object, _key: string, value: unknown, _attributes: Record<string, unknown>): unknown {\n return value\n }\n}\n`\n\nexport const RESOURCE_STUB = `export class {{ class }} {\n constructor(private readonly resource: unknown) {}\n\n toArray(): Record<string, unknown> {\n return { ...(this.resource as Record<string, unknown>) }\n }\n}\n`\n\nexport const RESOURCE_COLLECTION_STUB = `export class {{ class }} {\n constructor(private readonly resource: unknown[]) {}\n\n toArray(): unknown[] {\n return this.resource\n }\n}\n`\n\nexport const TEST_STUB = `import { describe, expect, test } from 'vitest'\n\ndescribe('{{ class }}', () => {\n test('example', () => {\n expect(true).toBe(true)\n })\n})\n`\n\nexport const OBSERVER_STUB = `export class {{ class }} {\n created(_model: unknown): void {\n //\n }\n\n updated(_model: unknown): void {\n //\n }\n\n deleted(_model: unknown): void {\n //\n }\n}\n`\n","import { GeneratorCommand } from './GeneratorCommand'\nimport { CAST_STUB } from './stubs'\n\nexport class MakeCastCommand extends GeneratorCommand {\n override readonly signature = 'make:cast {name} {--force}'\n override description = 'Create a new custom cast class'\n protected override type(): string {\n return 'Casts'\n }\n protected override stub(): string {\n return CAST_STUB\n }\n}\n","import { Str } from '@orieljs/support'\nimport { GeneratorCommand } from './GeneratorCommand'\nimport { COMMAND_STUB } from './stubs'\n\nexport class MakeCommandCommand extends GeneratorCommand {\n /** --command sets the generated signature; without it, Laravel's `app:` plus the kebab-cased name is used. */\n override readonly signature = 'make:command {name} {--command=} {--force}'\n override description = 'Create a new Artisan command'\n protected override type(): string {\n return 'Console/Commands'\n }\n protected override suffix(): string {\n return 'Command'\n }\n protected override stub(): string {\n return COMMAND_STUB\n }\n protected override extraPlaceholders(rawName: string): Record<string, string> {\n const option = this.option('command')\n const className = this.qualifyClass(rawName).className\n return {\n signature: typeof option === 'string' ? option : `app:${Str.kebab(className.replace(/Command$/, ''))}`,\n }\n }\n}\n","import { join } from 'node:path'\nimport { Str } from '@orieljs/support'\nimport { GeneratorCommand } from './GeneratorCommand'\nimport { CONTROLLER_STUB, CONTROLLER_STUB_API, CONTROLLER_STUB_RESOURCE } from './stubs'\n\nexport class MakeControllerCommand extends GeneratorCommand {\n override readonly signature = 'make:controller {name} {--resource} {--api} {--force}'\n override description = 'Create a new controller class'\n\n protected override type(): string {\n return 'Http/Controllers'\n }\n protected override suffix(): string {\n return 'Controller'\n }\n protected override stub(): string {\n if (this.option('api')) return CONTROLLER_STUB_API\n if (this.option('resource')) return CONTROLLER_STUB_RESOURCE\n return CONTROLLER_STUB\n }\n protected override extraPlaceholders(rawName: string): Record<string, string> {\n return {\n variable: Str.camel(rawName.split('/').pop()!),\n // The app's base controller (app/Http/Controllers/Controller.ts, from the skeleton), as in Laravel 11.\n controllerImport: this.importPath(rawName, join(this.root(this.type()), 'Controller')),\n }\n }\n}\n","import { GeneratorCommand } from './GeneratorCommand'\nimport { EVENT_STUB } from './stubs'\n\nexport class MakeEventCommand extends GeneratorCommand {\n override readonly signature = 'make:event {name} {--force}'\n override description = 'Create a new event class'\n protected override type(): string {\n return 'Events'\n }\n protected override stub(): string {\n return EVENT_STUB\n }\n}\n","import { Application } from '@orieljs/contracts'\nimport { inject } from '@orieljs/container'\nimport { Str } from '@orieljs/support'\nimport { GeneratorCommand } from './GeneratorCommand'\nimport { FACTORY_STUB } from './stubs'\n\nexport class MakeFactoryCommand extends GeneratorCommand {\n override readonly signature = 'make:factory {name} {--m|model= : The name of the model} {--force}'\n override description = 'Create a new factory class'\n protected override type(): string {\n return 'factories'\n }\n protected override suffix(): string {\n return 'Factory'\n }\n protected override stub(): string {\n return FACTORY_STUB\n }\n protected override root(subpath: string): string {\n return inject(Application).databasePath(subpath)\n }\n /** The model comes from --model, else from the name (UserFactory → User), and is imported from app/Models. */\n protected override extraPlaceholders(rawName: string): Record<string, string> {\n const option = this.option('model')\n const modelName = typeof option === 'string' ? option : this.qualifyClass(rawName).className.replace(/Factory$/, '')\n const segments = modelName\n .split('/')\n .filter(Boolean)\n .map((part) => Str.studly(part))\n return {\n model: segments.at(-1) ?? modelName,\n modelImport: this.importPath(rawName, inject(Application).appPath(['Models', ...segments].join('/'))),\n }\n }\n}\n","import { GeneratorCommand } from './GeneratorCommand'\nimport { JOB_STUB, JOB_STUB_SYNC } from './stubs'\n\nexport class MakeJobCommand extends GeneratorCommand {\n override readonly signature = 'make:job {name} {--sync : Indicates that the job should be synchronous} {--force}'\n override description = 'Create a new job class'\n protected override type(): string {\n return 'Jobs'\n }\n protected override stub(): string {\n return this.option('sync') ? JOB_STUB_SYNC : JOB_STUB\n }\n}\n","import { Application } from '@orieljs/contracts'\nimport { inject } from '@orieljs/container'\nimport { Str } from '@orieljs/support'\nimport { GeneratorCommand } from './GeneratorCommand'\nimport { LISTENER_STUB, LISTENER_STUB_PLAIN } from './stubs'\n\nexport class MakeListenerCommand extends GeneratorCommand {\n override readonly signature = 'make:listener {name} {--e|event= : The event class being listened for} {--force}'\n override description = 'Create a new event listener class'\n protected override type(): string {\n return 'Listeners'\n }\n protected override stub(): string {\n return typeof this.option('event') === 'string' ? LISTENER_STUB : LISTENER_STUB_PLAIN\n }\n protected override extraPlaceholders(rawName: string): Record<string, string> {\n const event = this.option('event')\n if (typeof event !== 'string') return {}\n const segments = event\n .split('/')\n .filter(Boolean)\n .map((part) => Str.studly(part))\n return {\n event: segments.at(-1) ?? event,\n eventImport: this.importPath(rawName, inject(Application).appPath(['Events', ...segments].join('/'))),\n }\n }\n}\n","import { Str } from '@orieljs/support'\nimport { GeneratorCommand } from './GeneratorCommand'\nimport { MAIL_STUB } from './stubs'\n\nexport class MakeMailCommand extends GeneratorCommand {\n override readonly signature = 'make:mail {name} {--force}'\n override description = 'Create a new mailable class'\n protected override type(): string {\n return 'Mail'\n }\n protected override stub(): string {\n return MAIL_STUB\n }\n protected override extraPlaceholders(rawName: string): Record<string, string> {\n const name = rawName.split('/').pop()!\n return { view: Str.kebab(name), subject: Str.title(Str.snake(name, ' ')) }\n }\n}\n","import { GeneratorCommand } from './GeneratorCommand'\nimport { MIDDLEWARE_STUB } from './stubs'\n\nexport class MakeMiddlewareCommand extends GeneratorCommand {\n override readonly signature = 'make:middleware {name} {--force}'\n override description = 'Create a new middleware class'\n protected override type(): string {\n return 'Http/Middleware'\n }\n protected override stub(): string {\n return MIDDLEWARE_STUB\n }\n}\n","import { Str } from '@orieljs/support'\nimport { GeneratorCommand } from './GeneratorCommand'\nimport { MODEL_STUB } from './stubs'\n\nexport class MakeModelCommand extends GeneratorCommand {\n override readonly signature =\n 'make:model {name} {--m|migration} {--f|factory} {--s|seed} {--c|controller} {--resource} {--api} {--force}'\n override description = 'Create a new model class'\n\n protected override type(): string {\n return 'Models'\n }\n protected override stub(): string {\n return MODEL_STUB\n }\n\n override async handle(): Promise<number> {\n const code = await super.handle()\n if (code !== 0) return code\n\n const name = (this.argument('name') as string).split('/').pop()!\n const tableName = Str.snake(Str.plural(name))\n\n if (this.option('migration')) {\n // make:migration belongs to the database component; this is a no-op when it isn't installed.\n await this.call('make:migration', { name: `create_${tableName}_table`, '--create': tableName })\n }\n if (this.option('factory')) {\n await this.call('make:factory', { name: `${name}Factory`, '--model': this.argument('name') })\n }\n if (this.option('seed')) {\n await this.call('make:seeder', { name: `${name}Seeder` })\n }\n if (this.option('controller')) {\n const options: Record<string, unknown> = {}\n if (this.option('resource')) options['--resource'] = true\n if (this.option('api')) options['--api'] = true\n await this.call('make:controller', { name: `${name}Controller`, ...options })\n }\n return 0\n }\n}\n","import { GeneratorCommand } from './GeneratorCommand'\nimport { NOTIFICATION_STUB } from './stubs'\n\nexport class MakeNotificationCommand extends GeneratorCommand {\n override readonly signature = 'make:notification {name} {--force}'\n override description = 'Create a new notification class'\n protected override type(): string {\n return 'Notifications'\n }\n protected override stub(): string {\n return NOTIFICATION_STUB\n }\n}\n","import { GeneratorCommand } from './GeneratorCommand'\nimport { OBSERVER_STUB } from './stubs'\n\nexport class MakeObserverCommand extends GeneratorCommand {\n override readonly signature = 'make:observer {name} {--force}'\n override description = 'Create a new observer class'\n protected override type(): string {\n return 'Observers'\n }\n protected override suffix(): string {\n return 'Observer'\n }\n protected override stub(): string {\n return OBSERVER_STUB\n }\n}\n","import { GeneratorCommand } from './GeneratorCommand'\nimport { POLICY_STUB } from './stubs'\n\nexport class MakePolicyCommand extends GeneratorCommand {\n override readonly signature = 'make:policy {name} {--force}'\n override description = 'Create a new policy class'\n protected override type(): string {\n return 'Policies'\n }\n protected override suffix(): string {\n return 'Policy'\n }\n protected override stub(): string {\n return POLICY_STUB\n }\n}\n","import { GeneratorCommand } from './GeneratorCommand'\nimport { PROVIDER_STUB } from './stubs'\n\nexport class MakeProviderCommand extends GeneratorCommand {\n override readonly signature = 'make:provider {name} {--force}'\n override description = 'Create a new service provider class'\n protected override type(): string {\n return 'Providers'\n }\n protected override suffix(): string {\n return 'ServiceProvider'\n }\n protected override stub(): string {\n return PROVIDER_STUB\n }\n}\n","import { GeneratorCommand } from './GeneratorCommand'\nimport { REQUEST_STUB } from './stubs'\n\nexport class MakeRequestCommand extends GeneratorCommand {\n override readonly signature = 'make:request {name} {--force}'\n override description = 'Create a new form request class'\n protected override type(): string {\n return 'Http/Requests'\n }\n protected override suffix(): string {\n return 'Request'\n }\n protected override stub(): string {\n return REQUEST_STUB\n }\n}\n","import { GeneratorCommand } from './GeneratorCommand'\nimport { RESOURCE_COLLECTION_STUB, RESOURCE_STUB } from './stubs'\n\nexport class MakeResourceCommand extends GeneratorCommand {\n override readonly signature = 'make:resource {name} {--collection} {--force}'\n override description = 'Create a new resource transformer class'\n\n protected override type(): string {\n return 'Http/Resources'\n }\n protected override stub(): string {\n return this.option('collection') ? RESOURCE_COLLECTION_STUB : RESOURCE_STUB\n }\n}\n","import { GeneratorCommand } from './GeneratorCommand'\nimport { RULE_STUB } from './stubs'\n\nexport class MakeRuleCommand extends GeneratorCommand {\n override readonly signature = 'make:rule {name} {--force}'\n override description = 'Create a new validation rule'\n protected override type(): string {\n return 'Rules'\n }\n protected override stub(): string {\n return RULE_STUB\n }\n}\n","import { Application } from '@orieljs/contracts'\nimport { inject } from '@orieljs/container'\nimport { GeneratorCommand } from './GeneratorCommand'\nimport { SEEDER_STUB } from './stubs'\n\nexport class MakeSeederCommand extends GeneratorCommand {\n override readonly signature = 'make:seeder {name} {--force}'\n override description = 'Create a new seeder class'\n protected override type(): string {\n return 'seeders'\n }\n protected override suffix(): string {\n return 'Seeder'\n }\n protected override stub(): string {\n return SEEDER_STUB\n }\n protected override root(subpath: string): string {\n return inject(Application).databasePath(subpath)\n }\n}\n","import { join } from 'node:path'\nimport { Application } from '@orieljs/contracts'\nimport { inject } from '@orieljs/container'\nimport { GeneratorCommand } from './GeneratorCommand'\nimport { TEST_STUB } from './stubs'\n\nexport class MakeTestCommand extends GeneratorCommand {\n override readonly signature = 'make:test {name} {--unit} {--force}'\n override description = 'Create a new test class'\n\n protected override type(): string {\n return this.option('unit') ? 'Unit' : 'Feature'\n }\n protected override kind(): string {\n return 'Test'\n }\n protected override suffix(): string {\n return 'Test'\n }\n protected override stub(): string {\n return TEST_STUB\n }\n protected override root(subpath: string): string {\n return inject(Application).basePath(join('tests', subpath))\n }\n protected override fileName(className: string): string {\n // Strip a trailing Test, unless that would leave nothing (make:test Test).\n return `${className.replace(/(?<=.)Test$/, '')}.test.ts`\n }\n}\n","import { Schedule } from '@orieljs/contracts'\nimport { inject } from '@orieljs/container'\nimport { Command } from '../Command'\nimport type { ScheduledEventImpl } from '../Schedule'\n\nexport class ScheduleListCommand extends Command {\n override readonly signature = 'schedule:list'\n override description = 'List the scheduled commands'\n\n override handle(): number {\n const events = inject(Schedule).events()\n if (events.length === 0) {\n // Laravel's exact message: \"tasks\", not \"commands\".\n this.info('No scheduled tasks have been defined.')\n return 0\n }\n this.table(\n ['Command', 'Expression'],\n events.map((event) => [(event as ScheduledEventImpl).getSummary(), event.expression]),\n )\n return 0\n }\n}\n","import { Schedule } from '@orieljs/contracts'\nimport { inject } from '@orieljs/container'\nimport { Command } from '../Command'\nimport { runDueEvents } from './scheduleEvents'\n\nexport class ScheduleRunCommand extends Command {\n override readonly signature = 'schedule:run'\n override description = 'Run the scheduled commands'\n\n override async handle(): Promise<number> {\n const now = new Date()\n const due = inject(Schedule).dueEvents(now)\n if (due.length === 0) {\n this.info('No scheduled commands are ready to run.')\n return 0\n }\n await runDueEvents(due, this, now)\n return 0\n }\n}\n","import type { ScheduledEvent as ScheduledEventContract } from '@orieljs/contracts'\nimport type { ScheduledEventImpl } from '../Schedule'\n\n/** The subset of Command that the shared loop below needs to report progress and failures. */\ninterface EventReporter {\n info(message: string): void\n error(message: string): void\n}\n\nfunction summaryOf(event: ScheduledEventContract): string {\n return (event as ScheduledEventImpl).getSummary()\n}\n\n/**\n * The per-event error-isolating loop shared by schedule:run and schedule:work. One event throwing is reported and\n * never stops the rest. `now` is the moment the events were found due, passed on to each run.\n *\n * Background events (`runInBackground()`) are started without being awaited in turn (the loop moves on to the next\n * event immediately) and only awaited together, via `Promise.allSettled`, after every due event has been started.\n * Each background run still gets the same try/catch error reporting as a foreground one, so a background failure\n * never escapes past this function.\n */\nexport async function runDueEvents(events: ScheduledEventContract[], io: EventReporter, now: Date): Promise<void> {\n const backgroundRuns: Promise<void>[] = []\n for (const event of events) {\n io.info(`Running scheduled task: ${summaryOf(event)}`)\n const attempt = async () => {\n try {\n await (event as ScheduledEventImpl).run(now)\n } catch (error) {\n io.error(` Failed: ${error instanceof Error ? error.message : String(error)}`)\n }\n }\n if ((event as ScheduledEventImpl).isBackground()) {\n backgroundRuns.push(attempt())\n } else {\n await attempt()\n }\n }\n await Promise.allSettled(backgroundRuns)\n}\n","import { Schedule } from '@orieljs/contracts'\nimport { inject } from '@orieljs/container'\nimport { Command } from '../Command'\nimport { runDueEvents } from './scheduleEvents'\n\nexport interface ScheduleWorkOptions {\n /** Overridable so tests don't wait on a real timer. */\n sleep?: (ms: number) => Promise<void>\n /** Overridable so tests can stop the otherwise-infinite loop. */\n signal?: AbortSignal\n /** Overridable so tests control the clock (milliseconds since the epoch). */\n now?: () => number\n}\n\nexport class ScheduleWorkCommand extends Command {\n override readonly signature = 'schedule:work'\n override description = 'Start the schedule worker'\n\n constructor(private readonly workOptions: ScheduleWorkOptions = {}) {\n super()\n }\n\n override async handle(): Promise<number> {\n const schedule = inject(Schedule)\n const sleep = this.workOptions.sleep ?? ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)))\n const clock = this.workOptions.now ?? Date.now\n this.info('Running scheduled tasks every minute.')\n let lastMinute: number | undefined\n while (!this.workOptions.signal?.aborted) {\n const time = clock()\n const minute = Math.floor(time / 60_000)\n // A timer can wake a little early, so each minute runs at most once, whenever the loop first sees it.\n if (minute !== lastMinute) {\n lastMinute = minute\n const now = new Date(time)\n await runDueEvents(schedule.dueEvents(now), this, now)\n }\n await sleep(Math.max(0, (minute + 1) * 60_000 - clock()) + 10)\n }\n return 0\n }\n}\n","import { spawn } from 'node:child_process'\nimport { Command } from '../Command'\n\nexport interface SpawnResult {\n on(event: 'exit', listener: (code: number | null) => void): unknown\n on(event: 'error', listener: (error: Error) => void): unknown\n}\nexport type Spawner = (command: string, args: string[]) => SpawnResult\n\nconst defaultSpawner: Spawner = (command, args) =>\n spawn(command, args, { stdio: 'inherit', shell: process.platform === 'win32' })\n\nexport class TestCommand extends Command {\n /** Paths are passed on to vitest; so is everything after `--` (`oriel test -- --coverage`). */\n override readonly signature = 'test {args?*} {--filter=}'\n override description = 'Run the test suite'\n\n constructor(private readonly spawner: Spawner = defaultSpawner) {\n super()\n }\n\n override handle(): Promise<number> {\n const args = ['vitest', 'run']\n const filter = this.option('filter')\n if (typeof filter === 'string') args.push('--testNamePattern', filter)\n const extra = this.argument('args')\n if (Array.isArray(extra)) args.push(...extra)\n return new Promise((resolve) => {\n const child = this.spawner('npx', args)\n child.on('error', (error: Error) => {\n this.error(error.message)\n resolve(1)\n })\n child.on('exit', (code) => resolve(code ?? 1))\n })\n }\n}\n","import { start } from 'node:repl'\nimport { Application } from '@orieljs/contracts'\nimport { inject } from '@orieljs/container'\nimport { Command } from '../Command'\n\nexport interface TinkerRepl {\n context: Record<string, unknown>\n on(event: 'exit', listener: () => void): unknown\n}\nexport type ReplStarter = (options: { prompt: string }) => TinkerRepl\n\nexport interface TinkerOptions {\n start?: ReplStarter\n}\n\nexport class TinkerCommand extends Command {\n override readonly signature = 'tinker'\n override description = 'Interact with your application'\n\n constructor(private readonly tinkerOptions: TinkerOptions = {}) {\n super()\n }\n\n override handle(): Promise<number> {\n const app = inject(Application)\n const startRepl = this.tinkerOptions.start ?? ((options) => start(options))\n return new Promise((resolve) => {\n const repl = startRepl({ prompt: 'oriel> ' })\n repl.context.app = app\n repl.on('exit', () => resolve(0))\n })\n }\n}\n","import { existsSync, readdirSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport type { Application, Command, ConsoleKernel } from '@orieljs/contracts'\nimport { RoutingPaths } from '@orieljs/contracts'\n\nfunction sourceFiles(directory: string): string[] {\n const files: string[] = []\n for (const entry of readdirSync(directory, { withFileTypes: true })) {\n const path = join(directory, entry.name)\n if (entry.isDirectory()) files.push(...sourceFiles(path))\n else if (/\\.(ts|js|mts|mjs)$/.test(entry.name) && !/\\.d\\.[mc]?ts$/.test(entry.name)) files.push(path)\n }\n return files.sort()\n}\n\n/**\n * Laravel 11 registers every command class in app/Console/Commands. An export counts when its prototype has\n * handle() and an instance has a string signature; anything else in those files is skipped.\n */\nexport async function discoverCommands(kernel: ConsoleKernel, directory: string): Promise<void> {\n if (!existsSync(directory)) return\n for (const file of sourceFiles(directory)) {\n const module = (await import(pathToFileURL(file).href)) as Record<string, unknown>\n for (const exported of Object.values(module)) {\n if (typeof exported !== 'function') continue\n const prototype = (exported as { prototype?: { handle?: unknown } }).prototype\n if (typeof prototype?.handle !== 'function') continue\n const instance = new (exported as new () => Command)()\n if (typeof instance.signature === 'string') kernel.register(instance)\n }\n }\n}\n\nlet generation = 0\n\n/**\n * Loads routes/console.ts for this app. The counter query gives every app a fresh module (ESM caches by URL), and\n * app.run() makes the Artisan/Schedule facades in the file resolve to this app. A default-exported function is\n * called with the kernel.\n */\nexport async function loadConsoleRoutes(app: Application, kernel: ConsoleKernel): Promise<void> {\n if (!app.bound(RoutingPaths)) return\n const file = app.make(RoutingPaths).console\n if (!file || !existsSync(file)) return\n const url = `${pathToFileURL(file).href}?oriel-console=${++generation}`\n await app.run(async () => {\n const module = (await import(url)) as { default?: unknown }\n if (typeof module.default === 'function') await (module.default as (kernel: ConsoleKernel) => unknown)(kernel)\n })\n}\n","import type {\n Application,\n ClosureCommand as ClosureCommandContract,\n Command as CommandContract,\n CommandContext,\n ConsoleKernel as ConsoleKernelContract,\n OptionValue,\n} from '@orieljs/contracts'\nimport { BusDispatcher, ConsoleKernel as ConsoleKernelToken } from '@orieljs/contracts'\nimport { ClosureCommand } from './ClosureCommand'\nimport { CommandNotFoundError, InvalidSignatureError } from './errors'\nimport {\n BufferedConsoleOutput,\n NodeConsoleInput,\n NodeConsoleOutput,\n QueuedConsoleInput,\n type ConsoleInput,\n type ConsoleIo,\n type ConsoleOutput,\n} from './io'\nimport {\n parseArgv,\n parseSignature,\n resolveArguments,\n resolveOptions,\n validateRequiredArguments,\n type ParsedInput,\n type ParsedSignature,\n} from './signature'\nimport { suggest } from './suggest'\n\ninterface BindableCommand {\n bind(args: Record<string, string | string[]>, options: Record<string, OptionValue>, io: ConsoleIo): void\n}\n\n/** Everything the kernel needs from the application: a fresh scope per command run. */\nexport type KernelApp = Pick<Application, 'createScope'>\n\n/**\n * Laravel's Artisan::call() parameters: `--name` keys are options, the rest are arguments. Each value is coerced to\n * the declared shape: a flag is set by any truthy value, an array option or variadic argument wraps a single value,\n * and a value option takes the value as a string (`true` is ignored). `false`/`null`/`undefined` are skipped, so the\n * option keeps its default. An undeclared option throws, like Symfony's ArrayInput.\n */\nfunction parametersToInput(parameters: Record<string, unknown>, signature: ParsedSignature): ParsedInput {\n const args: ParsedInput['arguments'] = {}\n const options: ParsedInput['options'] = {}\n const toList = (value: unknown): string[] => (Array.isArray(value) ? value.map(String) : [String(value)])\n for (const [key, value] of Object.entries(parameters)) {\n if (key.startsWith('--')) {\n const name = key.slice(2)\n const definition = signature.options.find((option) => option.name === name)\n if (!definition) throw new InvalidSignatureError(`The \"--${name}\" option does not exist.`)\n if (definition.mode === 'flag') {\n if (value) options[name] = true\n continue\n }\n if (value === false || value === null || value === undefined || value === true) continue\n options[name] = definition.mode === 'array' ? toList(value) : String(value)\n continue\n }\n if (value === false || value === null || value === undefined) continue\n const variadic = signature.arguments.find((argument) => argument.name === key)?.variadic\n args[key] = variadic ? toList(value) : Array.isArray(value) ? value.map(String) : String(value)\n }\n return { arguments: args, options }\n}\n\nexport class Kernel implements ConsoleKernelContract {\n private readonly commands = new Map<string, CommandContract>()\n private readonly defaultInput: ConsoleInput\n private readonly defaultOutput: ConsoleOutput\n private lastOutput = ''\n private running = 0\n\n constructor(\n private readonly app: KernelApp,\n io: { input?: ConsoleInput; output?: ConsoleOutput } = {},\n ) {\n this.defaultInput = io.input ?? new NodeConsoleInput()\n this.defaultOutput = io.output ?? new NodeConsoleOutput()\n }\n\n register(...commands: Array<CommandContract | (new () => CommandContract)>): void {\n for (const entry of commands) {\n const instance = typeof entry === 'function' ? new entry() : entry\n const name = parseSignature(instance.signature).name\n // Last registration wins (Laravel: Artisan's command map is a plain object keyed by name).\n this.commands.set(name, instance)\n }\n }\n\n command(\n signature: string,\n handler: (this: CommandContext, ...args: unknown[]) => number | void | Promise<number | void>,\n ): ClosureCommandContract {\n const closure = new ClosureCommand(signature, handler)\n this.register(closure)\n return closure\n }\n\n all(): Record<string, CommandContract> {\n return Object.fromEntries(this.commands)\n }\n\n output(): string {\n return this.lastOutput\n }\n\n async call(command: string, parameters: Record<string, unknown> = {}): Promise<number> {\n const output = new BufferedConsoleOutput()\n const code = await this.callWithIo(command, parameters, { input: new QueuedConsoleInput(), output })\n this.lastOutput = output.combined\n return code\n }\n\n /** @internal Runs a command with the given I/O. Command.call() passes its own, so nested output isn't swallowed. */\n async callWithIo(command: string, parameters: Record<string, unknown>, io: ConsoleIo): Promise<number> {\n const instance = this.findOrThrow(command)\n const signature = parseSignature(instance.signature)\n return this.execute(instance, signature, parametersToInput(parameters, signature), io)\n }\n\n async handle(argv: string[]): Promise<number> {\n const io = { input: this.defaultInput, output: this.defaultOutput }\n this.running++\n try {\n const [name, ...rest] = this.normalizeTopLevel(argv)\n const instance = this.findOrThrow(name!)\n const signature = parseSignature(instance.signature)\n const input = parseArgv(rest, signature)\n return await this.execute(instance, signature, input, io)\n } catch (error) {\n return this.reportTopLevelError(error, io.output)\n } finally {\n // Nested and background handle() calls share the default input; only the outermost run releases it.\n if (--this.running === 0) this.defaultInput.close?.()\n }\n }\n\n private reportTopLevelError(error: unknown, output: ConsoleOutput): number {\n if (error instanceof CommandNotFoundError) {\n output.writeError(`${error.message}\\n`)\n if (error.suggestions.length > 0) {\n output.writeError('\\nDid you mean one of these?\\n')\n for (const s of error.suggestions) output.writeError(` ${s}\\n`)\n }\n return 1\n }\n if (error instanceof InvalidSignatureError) {\n output.writeError(`${error.message}\\n`)\n return 1\n }\n output.writeError(`${error instanceof Error ? (error.stack ?? error.message) : String(error)}\\n`)\n return 1\n }\n\n /**\n * No argv -> list. `--help`/`-h` alone -> list. `<command> --help`/`-h` -> help <command>, unless the flag comes\n * after `--`, where it is a plain positional.\n */\n private normalizeTopLevel(argv: string[]): string[] {\n const [first, ...rest] = argv\n if (first === undefined || first === '--help' || first === '-h') return ['list']\n const beforeSeparator = rest.includes('--') ? rest.slice(0, rest.indexOf('--')) : rest\n if (beforeSeparator.includes('--help') || beforeSeparator.includes('-h')) return ['help', first]\n return [first, ...rest]\n }\n\n private findOrThrow(name: string): CommandContract {\n const instance = this.commands.get(name)\n if (!instance)\n throw new CommandNotFoundError(`Command \"${name}\" is not defined.`, suggest(name, [...this.commands.keys()]))\n return instance\n }\n\n private async execute(\n instance: CommandContract,\n signature: ParsedSignature,\n input: ParsedInput,\n io: ConsoleIo,\n ): Promise<number> {\n validateRequiredArguments(signature, input)\n // A per-run object layered over the registered instance, so concurrent runs never share bound input or I/O.\n const run = Object.create(instance) as CommandContract & Partial<BindableCommand>\n run.bind?.(resolveArguments(signature, input), resolveOptions(signature, input), io)\n const scope = this.app.createScope()\n // The kernel running the command is the one inject(ConsoleKernel) and Command.call() see, bound app or not.\n scope.instance(ConsoleKernelToken, this)\n return scope.run(async () => {\n try {\n const result = await run.handle()\n return typeof result === 'number' ? result : 0\n } finally {\n // Jobs from dispatchAfterResponse() are kept per scope, and the app terminates outside this one.\n if (scope.bound(BusDispatcher)) {\n await (scope.make(BusDispatcher) as { flushAfterResponse?(): Promise<void> }).flushAfterResponse?.()\n }\n }\n })\n }\n}\n","import type { ClosureCommand as ClosureCommandContract, CommandContext } from '@orieljs/contracts'\nimport { Command } from './Command'\nimport { parseSignature } from './signature'\n\ntype Handler = (this: CommandContext, ...args: unknown[]) => number | void | Promise<number | void>\n\n/** The object returned by ConsoleKernel.command(), like Laravel's Artisan::command() in routes/console.ts. */\nexport class ClosureCommand extends Command implements ClosureCommandContract {\n override readonly signature: string\n\n constructor(\n signature: string,\n private readonly handler: Handler,\n ) {\n super()\n this.signature = signature\n }\n\n /** Like Laravel's ->purpose(...). */\n purpose(description: string): this {\n this.description = description\n return this\n }\n\n override async handle(): Promise<number | void> {\n const positional = parseSignature(this.signature).arguments.map((arg) => this.argument(arg.name))\n return this.handler.call(this, ...positional)\n }\n}\n","function levenshtein(a: string, b: string): number {\n const rows: number[][] = Array.from({ length: a.length + 1 }, () => new Array<number>(b.length + 1).fill(0))\n for (let i = 0; i <= a.length; i++) rows[i]![0] = i\n for (let j = 0; j <= b.length; j++) rows[0]![j] = j\n for (let i = 1; i <= a.length; i++) {\n for (let j = 1; j <= b.length; j++) {\n rows[i]![j] =\n a[i - 1] === b[j - 1]\n ? rows[i - 1]![j - 1]!\n : 1 + Math.min(rows[i - 1]![j]!, rows[i]![j - 1]!, rows[i - 1]![j - 1]!)\n }\n }\n return rows[a.length]![b.length]!\n}\n\n/** Command names close to `name` (by edit distance, or sharing its prefix), closest first. Used for \"Did you mean?\". */\nexport function suggest(name: string, candidates: string[], limit = 3): string[] {\n return candidates\n .map((candidate) => ({ candidate, distance: levenshtein(name, candidate) }))\n .filter(({ candidate, distance }) => distance <= 3 || (name.length > 0 && candidate.startsWith(name)))\n .sort((a, b) => a.distance - b.distance)\n .slice(0, limit)\n .map(({ candidate }) => candidate)\n}\n","import { createHash } from 'node:crypto'\nimport type {\n Job,\n Lock,\n Schedule as ScheduleContract,\n ScheduledEvent as ScheduledEventContract,\n} from '@orieljs/contracts'\nimport { BusDispatcher, CacheManager, ConfigRepository, ConsoleKernel } from '@orieljs/contracts'\nimport { currentContainer, inject } from '@orieljs/container'\nimport { CronExpressionParser } from 'cron-parser'\nimport { ScheduleNameRequiredError } from './errors'\n\ntype Filter = () => boolean | Promise<boolean>\n\n/**\n * Bus's queueability rule, copied because Console can't import Bus: the `Queueable`\n * prototype marker, any ShouldQueue option with a value, or uniqueId()/retryUntil().\n */\nconst SHOULD_QUEUE = Symbol.for('oriel:bus.shouldQueue')\nconst QUEUE_OPTIONS = ['connection', 'queue', 'delay', 'tries', 'backoff', 'timeout'] as const\n\nfunction isQueueable(job: Job): boolean {\n const members = job as unknown as Record<PropertyKey, unknown>\n if (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\n/** Replaces one space-separated cron field (0 = minute … 4 = day-of-week) without touching the others. */\nfunction spliceField(expression: string, index: number, value: string): string {\n const fields = expression.split(' ')\n fields[index] = value\n return fields.join(' ')\n}\n\nfunction parseTime(time: string): [minute: string, hour: string] {\n const [hour = '0', minute = '0'] = time.split(':')\n return [minute, hour]\n}\n\nfunction sha1(value: string): string {\n return createHash('sha1').update(value).digest('hex')\n}\n\nexport class ScheduledEventImpl implements ScheduledEventContract {\n private cronExpression = '* * * * *'\n private tz: string | undefined\n private readonly filters: Filter[] = []\n private readonly rejects: Filter[] = []\n private betweenWindow: { start: string; end: string } | undefined\n private overlapExpiryMinutes: number | undefined\n private oneServer = false\n private background = false\n private eventName: string | undefined\n private eventDescription: string | undefined\n\n /**\n * `commandString` is only set for `Schedule.command()` events (the full argv, joined, e.g. \"mail:send --force\").\n * Its presence is what tells `mutexName()` and the name-required guard apart: a command event's mutex is\n * `sha1(expression + commandString)` (Laravel's `Event::mutexName()`) and never needs `name()`; a closure event\n * (`call()`/`job()`) has no `commandString`, so its mutex is `sha1(name())`, and `withoutOverlapping()`/\n * `onOneServer()` throw until `name()` has been called (Laravel's `CallbackEvent`).\n */\n constructor(\n private readonly executor: () => unknown | Promise<unknown>,\n private readonly commandString?: string,\n ) {}\n\n get expression(): string {\n return this.cronExpression\n }\n\n cron(expression: string): this {\n this.cronExpression = expression\n return this\n }\n everyMinute(): this {\n return this.cron('* * * * *')\n }\n everyFiveMinutes(): this {\n return this.cron('*/5 * * * *')\n }\n everyFifteenMinutes(): this {\n return this.cron('*/15 * * * *')\n }\n everyThirtyMinutes(): this {\n return this.cron('0,30 * * * *')\n }\n hourly(): this {\n return this.cron('0 * * * *')\n }\n hourlyAt(minute: number): this {\n return this.cron(`${minute} * * * *`)\n }\n daily(): this {\n return this.cron('0 0 * * *')\n }\n dailyAt(time: string): this {\n const [minute, hour] = parseTime(time)\n return this.cron(`${minute} ${hour} * * *`)\n }\n twiceDaily(first = 1, second = 13): this {\n return this.cron(`0 ${first},${second} * * *`)\n }\n weekly(): this {\n return this.cron('0 0 * * 0')\n }\n weeklyOn(day: number, time = '0:0'): this {\n const [minute, hour] = parseTime(time)\n return this.cron(`${minute} ${hour} * * ${day}`)\n }\n monthly(): this {\n return this.cron('0 0 1 * *')\n }\n monthlyOn(day = 1, time = '0:0'): this {\n const [minute, hour] = parseTime(time)\n return this.cron(`${minute} ${hour} ${day} * *`)\n }\n yearly(): this {\n return this.cron('0 0 1 1 *')\n }\n weekdays(): this {\n return this.cron(spliceField(this.cronExpression, 4, '1-5'))\n }\n weekends(): this {\n return this.cron(spliceField(this.cronExpression, 4, '0,6'))\n }\n timezone(timezone: string): this {\n this.tz = timezone\n return this\n }\n between(start: string, end: string): this {\n this.betweenWindow = { start, end }\n return this\n }\n when(callback: Filter): this {\n this.filters.push(callback)\n return this\n }\n skip(callback: Filter): this {\n this.rejects.push(callback)\n return this\n }\n withoutOverlapping(expiresAtMinutes = 1440): this {\n this.requireLockableName('withoutOverlapping')\n this.overlapExpiryMinutes = expiresAtMinutes\n return this\n }\n onOneServer(): this {\n this.requireLockableName('onOneServer')\n this.oneServer = true\n return this\n }\n runInBackground(): this {\n this.background = true\n return this\n }\n name(name: string): this {\n this.eventName = name\n return this\n }\n description(description: string): this {\n this.eventDescription = description\n return this\n }\n\n /** Accessors beyond the contract, read back by schedule:list and the schedule:run/schedule:work loop. */\n getName(): string | undefined {\n return this.eventName\n }\n getDescription(): string | undefined {\n return this.eventDescription\n }\n getSummary(): string {\n return this.eventName ?? this.eventDescription ?? '(closure)'\n }\n isBackground(): boolean {\n return this.background\n }\n\n /**\n * Minute precision: `now` is truncated to the start of its minute, since cron-parser's includesDate() also\n * compares seconds. Without timezone(), expressions are read in app.timezone (UTC by default), as in Laravel.\n */\n isDue(now: Date): boolean {\n const minute = new Date(Math.floor(now.getTime() / 60_000) * 60_000)\n const parsed = CronExpressionParser.parse(this.cronExpression, { tz: this.zone() })\n if (!parsed.includesDate(minute)) return false\n return !this.betweenWindow || this.isWithinWindow(now)\n }\n\n private zone(): string {\n if (this.tz !== undefined) return this.tz\n const container = currentContainer()\n return container?.bound(ConfigRepository) ? container.make(ConfigRepository).get<string>('app.timezone', 'UTC') : 'UTC'\n }\n\n private isWithinWindow(now: Date): boolean {\n const { start, end } = this.betweenWindow!\n const format = (d: Date) =>\n d.toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit', hour12: false, timeZone: this.zone() })\n const current = format(now)\n return start <= end ? current >= start && current <= end : current >= start || current <= end\n }\n\n /**\n * `startedAt` is the moment the scheduler found this event due. onOneServer() keys its lock on that minute, so\n * servers that start the event a little late still compete for the same slot.\n */\n async run(startedAt: Date = new Date()): Promise<void> {\n for (const filter of this.filters) if (!(await filter())) return\n for (const reject of this.rejects) if (await reject()) return\n\n let overlapLock: Lock | undefined\n if (this.overlapExpiryMinutes !== undefined) {\n overlapLock = this.acquireLock(this.mutexName(), this.overlapExpiryMinutes * 60)\n if (overlapLock && !(await overlapLock.get())) return\n }\n\n if (this.oneServer) {\n const minuteSlot = Math.floor(startedAt.getTime() / 60_000)\n const serverLock = this.acquireLock(`${this.mutexName()}:${minuteSlot}`, 3600)\n if (serverLock && !(await serverLock.get())) {\n if (overlapLock) await overlapLock.release()\n return\n }\n }\n\n try {\n await this.executor()\n } finally {\n if (overlapLock) await overlapLock.release()\n }\n }\n\n /**\n * Follows Laravel: a command event's mutex is `sha1(expression + full command\n * string incl. parameters)` (Laravel's `Event::mutexName()`) — no `name()` required. A closure event (`call()`/\n * `job()`) has no command string, so its mutex is `sha1(name())` (Laravel's `CallbackEvent::mutexName()`, which\n * reads the description `name()` also writes). `requireLockableName()` guarantees `eventName` is set by the time\n * this runs for a closure event.\n */\n private mutexName(): string {\n const key = this.commandString !== undefined ? this.cronExpression + this.commandString : this.eventName!\n return `framework/schedule-${sha1(key)}`\n }\n\n /**\n * Command events never need a name: their mutex is derived from the expression + command string. Closure events\n * (`call()`/`job()`) must call `name()` before `withoutOverlapping()`/`onOneServer()`, exactly like Laravel's\n * `CallbackEvent`, which throws the same message if you don't.\n */\n private requireLockableName(method: 'withoutOverlapping' | 'onOneServer'): void {\n if (this.commandString !== undefined) return\n if (this.eventName !== undefined) return\n throw new ScheduleNameRequiredError(method)\n }\n\n /** undefined when CacheManager isn't bound, so callers just skip locking. */\n private acquireLock(name: string, seconds: number): Lock | undefined {\n const container = currentContainer()\n if (!container?.bound(CacheManager)) return undefined\n return container.make(CacheManager).lock(name, seconds)\n }\n}\n\nexport class ScheduleImpl implements ScheduleContract {\n private readonly scheduledEvents: ScheduledEventImpl[] = []\n\n command(command: string, parameters: string[] = []): ScheduledEventContract {\n const argv = [...command.trim().split(/\\s+/).filter(Boolean), ...parameters]\n const commandString = argv.join(' ')\n const execute = async () => {\n const code = await inject(ConsoleKernel).handle(argv)\n if (code !== 0) throw new Error(`\"${commandString}\" exited with code ${code}.`)\n }\n return this.push(new ScheduledEventImpl(execute, commandString).description(command))\n }\n\n /**\n * Like Laravel's Schedule::job(): a queueable job is queued (with the overrides), any other job runs now. Laravel\n * also names the event after the job class by default, so `withoutOverlapping()`/`onOneServer()` work without an\n * explicit `name()` call.\n */\n job(job: Job, queue?: string, connection?: string): ScheduledEventContract {\n return this.push(\n new ScheduledEventImpl(() => {\n const bus = inject(BusDispatcher)\n // Decided before the overrides: setting `queue` would itself make the job look queueable.\n if (!isQueueable(job)) return bus.dispatchSync(job)\n if (queue !== undefined) job.queue = queue\n if (connection !== undefined) job.connection = connection\n return bus.dispatch(job)\n })\n .name(job.constructor.name)\n .description(job.constructor.name),\n )\n }\n\n call(callback: () => unknown | Promise<unknown>): ScheduledEventContract {\n return this.push(new ScheduledEventImpl(callback).description('Closure'))\n }\n\n events(): ScheduledEventContract[] {\n return [...this.scheduledEvents]\n }\n\n dueEvents(now: Date): ScheduledEventContract[] {\n return this.scheduledEvents.filter((event) => event.isDue(now))\n }\n\n private push(event: ScheduledEventImpl): ScheduledEventImpl {\n this.scheduledEvents.push(event)\n return event\n }\n}\n","import { ConsoleKernel, Schedule as ScheduleToken } from '@orieljs/contracts'\nimport { facade } from '@orieljs/support'\n\n/** Like Laravel's Artisan facade: the console kernel, under the name Laravel users expect. */\nexport const Artisan = facade(ConsoleKernel)\nexport const Schedule = facade(ScheduleToken)\n","import type { Application } from '@orieljs/contracts'\nimport { ConsoleKernel } from '@orieljs/contracts'\n\n/**\n * Bootstraps the app for the `oriel` CLI: marks it as running in the console, boots every provider (Console's\n * provider then loads routes/console.ts and app/Console/Commands), runs the command, and terminates the app, so\n * terminating callbacks close the DB pools and other handles that would keep the process alive. `boot()` runs\n * inside the try so a failure while booting still terminates the app. Relies on the process being started through\n * a loader that understands .ts (tsx on Node, native on Bun), like the rest of the skeleton.\n */\nexport async function runConsole(app: Application, argv: string[] = process.argv.slice(2)): Promise<number> {\n app.setRunningInConsole(true)\n try {\n await app.boot()\n return await app.make(ConsoleKernel).handle(argv)\n } finally {\n await app.terminate()\n }\n}\n\n/** What the skeleton's `oriel` entry calls: runConsole(), then exit with the command's exit code. */\nexport async function runConsoleAndExit(\n app: Application,\n argv: string[] = process.argv.slice(2),\n exit: (code: number) => void = (code) => process.exit(code),\n): Promise<void> {\n exit(await runConsole(app, argv))\n}\n","import type { Cookie } from '@orieljs/contracts'\n\nconst SAME_SITE = { lax: 'Lax', strict: 'Strict', none: 'None' } as const\n\n/** A Set-Cookie header value. Negative minutes delete the cookie; 0 is a session cookie. */\nexport function serializeCookie(cookie: Cookie, now: number = Date.now()): string {\n const parts: string[] = []\n if (cookie.minutes < 0) {\n parts.push(`${cookie.name}=`, 'Expires=Thu, 01 Jan 1970 00:00:00 GMT', 'Max-Age=0')\n } else {\n parts.push(`${cookie.name}=${encodeURIComponent(cookie.value)}`)\n if (cookie.minutes > 0) {\n parts.push(`Expires=${new Date(now + cookie.minutes * 60_000).toUTCString()}`, `Max-Age=${cookie.minutes * 60}`)\n }\n }\n parts.push(`Path=${cookie.path}`)\n if (cookie.domain !== undefined && cookie.domain !== '') parts.push(`Domain=${cookie.domain}`)\n if (cookie.secure) parts.push('Secure')\n if (cookie.httpOnly) parts.push('HttpOnly')\n parts.push(`SameSite=${SAME_SITE[cookie.sameSite]}`)\n return parts.join('; ')\n}\n\nexport interface ParsedSetCookie {\n name: string\n value: string\n /** Everything after the name=value pair, including the leading '; ' (empty when there are no attributes). */\n attributes: string\n}\n\nconst decode = (value: string): string => {\n try {\n return decodeURIComponent(value)\n } catch {\n return value\n }\n}\n\n/** Splits a Set-Cookie header value into its name, decoded value and untouched attributes. */\nexport function parseSetCookie(header: string): ParsedSetCookie {\n const semicolon = header.indexOf(';')\n const pair = semicolon === -1 ? header : header.slice(0, semicolon)\n const equals = pair.indexOf('=')\n return {\n name: (equals === -1 ? pair : pair.slice(0, equals)).trim(),\n value: equals === -1 ? '' : decode(pair.slice(equals + 1).trim()),\n attributes: semicolon === -1 ? '' : header.slice(semicolon),\n }\n}\n\n/** Parses a Cookie request header (`a=1; b=2`). The first occurrence of a name wins. */\nexport function parseCookieHeader(header: string | undefined): Record<string, string> {\n const cookies: Record<string, string> = {}\n for (const part of (header ?? '').split(';')) {\n const equals = part.indexOf('=')\n if (equals === -1) continue\n const name = part.slice(0, equals).trim()\n if (name === '' || Object.hasOwn(cookies, name) || name === '__proto__') continue\n cookies[name] = decode(part.slice(equals + 1).trim())\n }\n return cookies\n}\n\n/** A copy of the response whose headers can be changed (Response.redirect() and fetch() headers are immutable). */\nexport function withHeaders(response: Response, change: (headers: Headers) => void): Response {\n const headers = new Headers(response.headers)\n change(headers)\n return new Response(response.body, { status: response.status, statusText: response.statusText, headers })\n}\n","import { createHmac, timingSafeEqual } from 'node:crypto'\n\n/**\n * Laravel's CookieValuePrefix: encrypted cookie values start with hmac_sha1(name + 'v2', key) + '|', which binds\n * each value to its cookie name so an encrypted value can't be replayed under another cookie.\n */\nexport const CookieValuePrefix = {\n create(name: string, key: Uint8Array): string {\n return `${createHmac('sha1', key).update(`${name}v2`).digest('hex')}|`\n },\n\n remove(value: string): string {\n return value.slice(41)\n },\n\n /** The value without its prefix when the prefix matches one of the keys, else undefined. */\n validate(name: string, value: string, keys: Uint8Array[]): string | undefined {\n const actual = Buffer.from(value.slice(0, 41))\n for (const key of keys) {\n const expected = Buffer.from(CookieValuePrefix.create(name, key))\n if (actual.length === expected.length && timingSafeEqual(actual, expected)) return CookieValuePrefix.remove(value)\n }\n return undefined\n },\n}\n","import type { Cookie, CookieJar as CookieJarContract } from '@orieljs/contracts'\n\nexport interface CookieDefaults {\n path?: string\n domain?: string | undefined\n secure?: boolean\n sameSite?: Cookie['sameSite']\n}\n\ntype CookieOptions = Partial<Omit<Cookie, 'name' | 'value' | 'minutes'>>\n\n/** Laravel's CookieJar. One per request scope: queued cookies are attached by AddQueuedCookiesToResponse. */\nexport class CookieJar implements CookieJarContract {\n readonly #queued = new Map<string, Cookie>()\n readonly #defaults: Required<Omit<CookieDefaults, 'domain'>> & { domain: string | undefined }\n\n constructor(defaults: CookieDefaults = {}) {\n this.#defaults = {\n path: defaults.path ?? '/',\n domain: defaults.domain ?? undefined,\n secure: defaults.secure ?? false,\n sameSite: defaults.sameSite ?? 'lax',\n }\n }\n\n make(name: string, value: string, minutes = 0, options: CookieOptions = {}): Cookie {\n const domain = options.domain ?? this.#defaults.domain\n return {\n name,\n value,\n minutes,\n path: options.path ?? this.#defaults.path,\n ...(domain === undefined ? {} : { domain }),\n secure: options.secure ?? this.#defaults.secure,\n httpOnly: options.httpOnly ?? true,\n sameSite: options.sameSite ?? this.#defaults.sameSite,\n }\n }\n\n /** Five years, like Laravel. */\n forever(name: string, value: string, options: CookieOptions = {}): Cookie {\n return this.make(name, value, 576000, options)\n }\n\n /** An expired cookie that makes the browser delete it. */\n forget(name: string, options: CookieOptions = {}): Cookie {\n return this.make(name, '', -2628000, options)\n }\n\n /** Queue a cookie for the response. A cookie with the same name and path replaces the earlier one. */\n queue(cookie: Cookie): void {\n this.#queued.set(`${cookie.name}\\0${cookie.path}`, cookie)\n }\n\n queued(): Cookie[] {\n return [...this.#queued.values()]\n }\n\n hasQueued(name: string, path?: string): boolean {\n return this.queuedCookie(name, path) !== undefined\n }\n\n queuedCookie(name: string, path?: string): Cookie | undefined {\n return this.queued().find((cookie) => cookie.name === name && (path === undefined || cookie.path === path))\n }\n\n unqueue(name: string, path?: string): void {\n for (const [key, cookie] of this.#queued) {\n if (cookie.name === name && (path === undefined || cookie.path === path)) this.#queued.delete(key)\n }\n }\n}\n","import { CookieJar, type HttpRequest, type Middleware, type Next } from '@orieljs/contracts'\nimport { inject } from '@orieljs/container'\nimport { serializeCookie, withHeaders } from '../serialize'\n\n/** Laravel's AddQueuedCookiesToResponse: writes the request's queued cookies as Set-Cookie headers. */\nexport class AddQueuedCookiesToResponse implements Middleware {\n readonly #jar = inject(CookieJar)\n\n async handle(request: HttpRequest, next: Next): Promise<Response> {\n const response = await next(request)\n const cookies = this.#jar.queued()\n if (cookies.length === 0) return response\n return withHeaders(response, (headers) => {\n for (const cookie of cookies) headers.append('Set-Cookie', serializeCookie(cookie))\n })\n }\n}\n","import { Encrypter, type HttpRequest, type Middleware, type Next } from '@orieljs/contracts'\nimport { inject } from '@orieljs/container'\nimport { CookieValuePrefix } from '../CookieValuePrefix'\nimport { parseCookieHeader, parseSetCookie, withHeaders } from '../serialize'\n\nconst neverEncrypt = new Set<string>()\n\n/** Whether a Set-Cookie deletes the cookie (Max-Age <= 0, or Expires in the past): its value is left alone. */\nfunction isDeletion(attributes: string, now = Date.now()): boolean {\n for (const part of attributes.split(';')) {\n const equals = part.indexOf('=')\n if (equals === -1) continue\n const key = part.slice(0, equals).trim().toLowerCase()\n const value = part.slice(equals + 1).trim()\n if (key === 'max-age' && Number(value) <= 0) return true\n if (key === 'expires' && Date.parse(value) <= now) return true\n }\n return false\n}\n\n/**\n * Laravel's EncryptCookies: request cookies are decrypted (and dropped when they don't decrypt), and every\n * Set-Cookie on the outgoing response is encrypted, whoever wrote it (queued on the CookieJar, or written straight\n * onto the response such as RedirectResponse.withCookie()), except the names in `except` and deletions. It runs\n * once, outermost in `web`, so every cookie is encrypted exactly once.\n */\nexport class EncryptCookies implements Middleware {\n /** Cookie names that are never encrypted (Laravel 11's $middleware->encryptCookies(except: [...])). */\n static except(cookies: string | string[]): void {\n for (const name of Array.isArray(cookies) ? cookies : [cookies]) neverEncrypt.add(name)\n }\n\n /** Forget the names added with except() (for tests). */\n static flushState(): void {\n neverEncrypt.clear()\n }\n\n /** Subclasses list cookie names that are not encrypted. */\n protected except: string[] = []\n\n protected readonly encrypter = inject(Encrypter)\n\n isDisabled(name: string): boolean {\n return this.except.includes(name) || neverEncrypt.has(name)\n }\n\n async handle(request: HttpRequest, next: Next): Promise<Response> {\n this.decrypt(request)\n return this.encrypt(await next(request))\n }\n\n protected decrypt(request: HttpRequest): void {\n const keys = (this.encrypter as { getAllKeys?(): Uint8Array[] }).getAllKeys?.() ?? [this.encrypter.getKey()]\n const decrypted: Record<string, string> = {}\n for (const [name, value] of Object.entries(parseCookieHeader(request.header('cookie')))) {\n if (this.isDisabled(name)) {\n decrypted[name] = value\n continue\n }\n try {\n const plain = CookieValuePrefix.validate(name, this.encrypter.decrypt<string>(value, false), keys)\n if (plain !== undefined) decrypted[name] = plain\n } catch {\n // A cookie that doesn't decrypt reads as absent (Laravel sets it to null).\n }\n }\n request.setCookies(decrypted)\n }\n\n protected encrypt(response: Response): Response {\n const cookies = response.headers.getSetCookie()\n if (cookies.length === 0) return response\n return withHeaders(response, (headers) => {\n headers.delete('Set-Cookie')\n for (const header of cookies) {\n const { name, value, attributes } = parseSetCookie(header)\n if (this.isDisabled(name) || isDeletion(attributes)) {\n headers.append('Set-Cookie', header)\n continue\n }\n const encrypted = this.encrypter.encrypt(CookieValuePrefix.create(name, this.encrypter.getKey()) + value, false)\n headers.append('Set-Cookie', `${name}=${encodeURIComponent(encrypted)}${attributes}`)\n }\n })\n }\n}\n","import { CookieJar, HttpRequest, type Cookie as CookieShape } from '@orieljs/contracts'\nimport { inject } from '@orieljs/container'\nimport { facade } from '@orieljs/support'\n\n/** The Cookie facade: the request's jar, plus get()/has() reading the (decrypted) request cookies. */\nexport const Cookie = facade(CookieJar, {\n get: (name: string, defaultValue?: string): string | undefined => inject(HttpRequest).cookie(name) ?? defaultValue,\n has: (name: string): boolean => inject(HttpRequest).cookie(name) !== undefined,\n})\n\n/** cookie(): the jar; cookie(name, value, minutes?, options?): a new cookie (queue it, or attach it to a redirect). */\nexport function cookie(): CookieJar\nexport function cookie(name: string, value: string, minutes?: number, options?: Partial<Omit<CookieShape, 'name' | 'value' | 'minutes'>>): CookieShape\nexport function cookie(\n name?: string,\n value?: string,\n minutes?: number,\n options?: Partial<Omit<CookieShape, 'name' | 'value' | 'minutes'>>,\n): CookieJar | CookieShape {\n const jar = inject(CookieJar)\n return name === undefined ? jar : jar.make(name, value ?? '', minutes, options)\n}\n","import { ConfigRepository, CookieJar as CookieJarToken, HttpRequest, Router, type Cookie } from '@orieljs/contracts'\nimport { ServiceProvider } from '@orieljs/support'\nimport { CookieJar } from './CookieJar'\nimport { AddQueuedCookiesToResponse } from './middleware/AddQueuedCookiesToResponse'\nimport { EncryptCookies } from './middleware/EncryptCookies'\n\nexport class CookieServiceProvider extends ServiceProvider {\n override register(): void {\n // Laravel's CookieServiceProvider takes the jar's defaults from config/session.php.\n this.app.scoped(CookieJarToken, (container) => {\n const config = container.make(ConfigRepository)\n const domain = config.get<string | null | undefined>('session.domain')\n // secure defaults to null (ruling F6); an explicit true/false wins, otherwise it follows the request's scheme\n // (Symfony's setSecureDefault), so cookies built from these defaults (e.g. the remember cookie) are Secure on HTTPS.\n const secureConfig = config.get<boolean | null | undefined>('session.secure', null)\n const secure = secureConfig ?? (container.bound(HttpRequest) && container.make(HttpRequest).url().startsWith('https:'))\n return new CookieJar({\n path: config.get('session.path', '/'),\n domain: domain ?? undefined,\n secure,\n sameSite: config.get<Cookie['sameSite'] | null>('session.same_site', 'lax') ?? 'lax',\n })\n })\n }\n\n override boot(): void {\n if (!this.app.bound(Router)) return\n this.app.make(Router).pushMiddlewareToGroup('web', EncryptCookies).pushMiddlewareToGroup('web', AddQueuedCookiesToResponse)\n }\n}\n","import type { ModelNotFoundError as ModelNotFoundErrorContract, OrielError } from '@orieljs/contracts'\n\n/** Thrown by findOrFail()/firstOrFail() and route model binding. Renders as 404. */\nexport class ModelNotFoundError extends Error implements ModelNotFoundErrorContract {\n readonly kind = 'ModelNotFound' as const\n readonly status = 404\n override readonly name = 'ModelNotFoundError'\n\n constructor(\n readonly model: string,\n readonly ids: unknown[] = [],\n ) {\n super(`No query results for model [${model}]${ids.length ? ' ' + ids.map(String).join(', ') : '.'}`)\n }\n}\n\n/**\n * Base of every other Database error: a server error (bug or infrastructure failure). The exception handler reports\n * it and renders a 500, hiding the message unless app.debug is on.\n */\nexport abstract class DatabaseError extends Error implements OrielError {\n readonly kind = 'Server' as const\n readonly status = 500\n}\n\n/** A failed SQL statement, with the SQL and connection in the message (Laravel's QueryException). */\nexport class QueryError extends DatabaseError {\n override readonly name = 'QueryError'\n\n constructor(\n readonly connectionName: string,\n readonly sql: string,\n readonly bindings: readonly unknown[],\n cause: unknown,\n ) {\n super(`${cause instanceof Error ? cause.message : String(cause)} (Connection: ${connectionName}, SQL: ${sql})`, { cause })\n }\n}\n\n/** Mass assignment on a model whose `guarded` is ['*'] (Laravel's MassAssignmentException). */\nexport class MassAssignmentError extends DatabaseError {\n override readonly name = 'MassAssignmentError'\n constructor(readonly model: string, readonly attribute: string) {\n super(`Add [${attribute}] to fillable property to allow mass assignment on [${model}].`)\n }\n}\n\nexport class RelationNotFoundError extends DatabaseError {\n override readonly name = 'RelationNotFoundError'\n constructor(readonly model: string, readonly relation: string) {\n super(`Call to undefined relationship [${relation}] on model [${model}].`)\n }\n}\n\nexport class RelationNotLoadedError extends DatabaseError {\n override readonly name = 'RelationNotLoadedError'\n constructor(readonly model: string, readonly relation: string) {\n super(\n `Relation [${relation}] is not loaded on model [${model}]. Eager load it with ${model}.with('${relation}') ` +\n `or await model.load('${relation}'), or query it with model.${relation}().get().`,\n )\n }\n}\n\nexport class InvalidCastError extends DatabaseError {\n override readonly name = 'InvalidCastError'\n constructor(readonly model: string, readonly column: string, readonly castType: string) {\n super(`Call to undefined cast [${castType}] on column [${column}] in model [${model}].`)\n }\n}\n\n/** Bad or missing database configuration (unknown connection, unsupported driver). */\nexport class DatabaseConfigError extends DatabaseError {\n override readonly name = 'DatabaseConfigError'\n}\n\n/** Thrown when an operation needs a feature the model hasn't enabled (e.g. restore() without soft deletes). */\nexport class LogicError extends DatabaseError {\n override readonly name = 'LogicError'\n}\n","/** True when running on Bun (bun:sqlite is used instead of better-sqlite3). */\nexport const isBun = (): boolean => typeof (globalThis as { Bun?: unknown }).Bun !== 'undefined'\n","import type { SqliteDatabase, SqliteStatement } from 'kysely'\nimport { isBun } from '../runtime'\n\n/** The part of bun:sqlite's Statement this adapter uses. */\nexport interface BunStatement {\n readonly columnNames: string[]\n all(...parameters: unknown[]): unknown[]\n run(...parameters: unknown[]): { changes: number | bigint; lastInsertRowid: number | bigint }\n iterate(...parameters: unknown[]): IterableIterator<unknown>\n}\n\n/** The part of bun:sqlite's Database this adapter uses. */\nexport interface BunDatabase {\n prepare(sql: string): BunStatement\n close(): void\n}\n\n/** Adapts bun:sqlite to the better-sqlite3 shape Kysely's SqliteDialect expects. */\nexport class BunSqliteDatabase implements SqliteDatabase {\n constructor(private readonly database: BunDatabase) {}\n\n close(): void {\n this.database.close()\n }\n\n prepare(sql: string): SqliteStatement {\n const statement = this.database.prepare(sql)\n return {\n // A statement that returns columns (SELECT, or anything with RETURNING) is a reader.\n reader: statement.columnNames.length > 0,\n all: (parameters) => statement.all(...parameters),\n run: (parameters) => statement.run(...parameters),\n iterate: (parameters) => statement.iterate(...parameters),\n }\n }\n}\n\n/** Opens a SQLite database with bun:sqlite on Bun and better-sqlite3 on Node. */\nexport async function openSqlite(filename: string): Promise<SqliteDatabase> {\n if (isBun()) {\n // A variable specifier keeps bundlers, Vite and the dependency checker from trying to resolve bun:sqlite on Node.\n const specifier = 'bun:sqlite'\n const { Database } = (await import(/* @vite-ignore */ specifier)) as { Database: new (filename: string) => BunDatabase }\n return new BunSqliteDatabase(new Database(filename))\n }\n const { default: Database } = await import('better-sqlite3')\n return new Database(filename)\n}\n","import { CompiledQuery, MysqlDialect, PostgresDialect, SqliteDialect, type Dialect } from 'kysely'\nimport type { DriverName } from '@orieljs/contracts'\nimport { DatabaseConfigError } from '../errors'\nimport { openSqlite } from './SqliteDatabase'\n\n/** One entry of `config('database.connections')`, in Laravel's config/database.php shape. */\nexport interface ConnectionConfig {\n driver: DriverName\n url?: string\n database?: string\n host?: string\n port?: string | number\n username?: string\n password?: string\n charset?: string\n collation?: string\n /** pgsql only. */\n search_path?: string\n /** sqlite only. Defaults to true, like Laravel's DB_FOREIGN_KEYS. */\n foreign_key_constraints?: boolean\n pool?: { max?: number }\n}\n\nconst PG_INT8 = 20\nconst PG_DATE = 1082\nconst PG_TIMESTAMP = 1114\nconst PG_TIMESTAMPTZ = 1184\n\n/**\n * The mysql2 pool options for a connection. When `url` is set its parts (host, port, user, password,\n * database) win over the individual keys, like Laravel; keys it leaves out fall back to the config.\n */\nexport function mysqlPoolOptions(config: ConnectionConfig): Record<string, unknown> {\n const options: Record<string, unknown> = {}\n if (config.url) {\n try {\n const url = new URL(config.url)\n const decoded = (value: string) => (value ? decodeURIComponent(value) : undefined)\n Object.assign(options, {\n host: url.hostname || undefined,\n port: url.port ? Number(url.port) : undefined,\n database: decoded(url.pathname.slice(1)),\n user: decoded(url.username),\n password: decoded(url.password),\n })\n // Query parameters are mysql2 options; like mysql2 itself, JSON-parse the value when it is JSON.\n for (const [key, value] of [...url.searchParams.entries()]) {\n try {\n options[key] = JSON.parse(value)\n } catch {\n options[key] = value\n }\n }\n } catch {\n throw new DatabaseConfigError('Invalid database url.')\n }\n }\n const fallbacks = {\n host: config.host,\n port: config.port === undefined || config.port === '' ? undefined : Number(config.port),\n database: config.database,\n user: config.username,\n password: config.password,\n charset: config.charset ?? 'utf8mb4',\n connectionLimit: config.pool?.max ?? 10,\n dateStrings: true,\n supportBigNumbers: true,\n timezone: 'Z',\n }\n for (const [key, value] of Object.entries(fallbacks)) options[key] ??= value\n return options\n}\n\n/** Builds the Kysely dialect for a connection. Driver modules are imported lazily, on the first query. */\nexport function createDialect(config: ConnectionConfig): Dialect {\n switch (config.driver) {\n case 'sqlite': {\n const foreignKeys = config.foreign_key_constraints ?? true\n return new SqliteDialect({\n database: () => openSqlite(config.database ?? ':memory:'),\n onCreateConnection: async (connection) => {\n await connection.executeQuery(CompiledQuery.raw(`PRAGMA foreign_keys = ${foreignKeys ? 'ON' : 'OFF'}`))\n },\n })\n }\n case 'pgsql':\n return new PostgresDialect({\n pool: async () => {\n const { default: pg } = await import('pg')\n return new pg.Pool({\n connectionString: config.url,\n host: config.host,\n port: config.port === undefined ? undefined : Number(config.port),\n database: config.database,\n user: config.username,\n password: config.password,\n max: config.pool?.max ?? 10,\n types: {\n // Dates stay strings (casts parse them as UTC); bigint ids become numbers when they fit.\n getTypeParser: ((oid: number, format?: 'text' | 'binary') => {\n if (oid === PG_INT8) return (value: string) => (Number.isSafeInteger(Number(value)) ? Number(value) : value)\n if (oid === PG_DATE || oid === PG_TIMESTAMP || oid === PG_TIMESTAMPTZ) return (value: string) => value\n return pg.types.getTypeParser(oid, format)\n }) as typeof pg.types.getTypeParser,\n },\n })\n },\n onCreateConnection: async (connection) => {\n if (config.search_path) {\n await connection.executeQuery(CompiledQuery.raw(`set search_path to ${config.search_path}`))\n }\n },\n })\n case 'mysql':\n return new MysqlDialect({\n pool: async () => {\n const { createPool } = await import('mysql2')\n type PoolOptions = Parameters<typeof createPool>[0] & object\n return createPool(mysqlPoolOptions(config) as PoolOptions)\n },\n })\n default:\n throw new DatabaseConfigError(`Unsupported driver [${String((config as { driver: unknown }).driver)}].`)\n }\n}\n","import { sql, type RawBuilder } from 'kysely'\nimport { LogicError } from '../errors'\n\n/** A raw SQL fragment, never escaped: DB.raw('count(*) as total'). Use `?` placeholders for values. */\nexport class Expression {\n constructor(\n readonly value: string,\n readonly bindings: readonly unknown[] = [],\n ) {}\n\n toString(): string {\n return this.value\n }\n}\n\nexport const raw = (value: string, bindings: readonly unknown[] = []): Expression => new Expression(value, bindings)\n\n/**\n * Turns `select * from users where id = ?` + bindings into a Kysely RawBuilder, so each dialect gets its own\n * placeholders ($1 on Postgres). `?` inside quoted strings isn't special-cased: bind such values instead.\n */\nexport function rawWithBindings(query: string, bindings: readonly unknown[] = []): RawBuilder<unknown> {\n const fragments = query.split('?')\n if (fragments.length - 1 !== bindings.length) {\n throw new LogicError(`The query has ${fragments.length - 1} placeholders but ${bindings.length} bindings were given: ${query}`)\n }\n const strings = Object.assign([...fragments], { raw: [...fragments] }) as unknown as TemplateStringsArray\n return sql(strings, ...bindings)\n}\n","import { sql } from 'kysely'\nimport type { Operator, QueryBuilder, Row } from '@orieljs/contracts'\nimport { Collection, LazyCollection } from '@orieljs/collections'\nimport type { Connection } from '../Connection'\nimport { LogicError } from '../errors'\nimport { AbstractPaginator } from '../Pagination/AbstractPaginator'\nimport { Cursor, CursorPaginator } from '../Pagination/CursorPaginator'\nimport { LengthAwarePaginator } from '../Pagination/LengthAwarePaginator'\nimport { Paginator } from '../Pagination/Paginator'\nimport { Expression } from './Expression'\nimport { Grammar } from './Grammar'\n\nexport type WhereBoolean = 'and' | 'or'\nexport type Direction = 'asc' | 'desc'\nexport type ColumnRef = string | Expression\n\nexport type Where =\n | { type: 'basic'; column: ColumnRef | Builder<unknown>; operator: string; value: unknown; boolean: WhereBoolean }\n | { type: 'in'; column: ColumnRef; values: readonly unknown[] | Builder<unknown>; not: boolean; boolean: WhereBoolean }\n | { type: 'null'; column: ColumnRef; not: boolean; boolean: WhereBoolean }\n | { type: 'between'; column: ColumnRef; values: readonly [unknown, unknown]; not: boolean; boolean: WhereBoolean }\n | { type: 'column'; first: ColumnRef; operator: string; second: ColumnRef; boolean: WhereBoolean }\n | { type: 'nested'; query: Builder<unknown>; not: boolean; boolean: WhereBoolean }\n | { type: 'exists'; query: Builder<unknown>; not: boolean; boolean: WhereBoolean }\n | { type: 'raw'; sql: string; bindings: readonly unknown[]; boolean: WhereBoolean }\n\nexport type Having =\n | { column: ColumnRef; operator: string; value: unknown; boolean: WhereBoolean }\n | { raw: Expression; boolean: WhereBoolean }\n\nexport type Order = { column: ColumnRef; direction: Direction } | { raw: Expression }\nexport type SelectColumn = ColumnRef | { query: Builder<unknown>; as: string }\n\ntype NestedCallback<Q> = (query: Q) => unknown\n\n/** Pages through a query lazily, one chunk per query (lazy()). */\nasync function* chunksOf<T>(query: Builder<T>, chunkSize: number): AsyncGenerator<T> {\n for (let page = 1; ; page++) {\n const results = await query.clone().forPage(page, chunkSize).runSelect()\n yield* results\n if (results.length < chunkSize) return\n }\n}\n\n/** Pages through a query lazily by key (lazyById()). */\nasync function* chunksById<T>(query: Builder<T>, chunkSize: number, column: string, alias: string): AsyncGenerator<T> {\n let lastId: unknown\n for (;;) {\n const results = await query.clone().forPageAfterId(chunkSize, lastId, column).runSelect()\n yield* results\n if (results.length < chunkSize) return\n lastId = keyOf(results.at(-1), alias)\n }\n}\n\n/** Reads the chunkById key from a row or a model. */\nfunction keyOf(item: unknown, alias: string): unknown {\n const value = (item as Record<string, unknown> | undefined)?.[alias]\n if (value === undefined || value === null) {\n throw new LogicError(`The chunkById operation was aborted because the [${alias}] column is not present in the query result.`)\n }\n return value\n}\n\nconst isRow = (value: unknown): value is Row =>\n typeof value === 'object' && value !== null && !(value instanceof Expression) && !(value instanceof Builder) && !Array.isArray(value)\n\n/** The key a selected column comes back under: 'users.name' → 'name', 'name as n' → 'n'. */\nexport function columnKey(column: string): string {\n const alias = /\\s+as\\s+/i.exec(column)\n if (alias) return column.slice(alias.index + alias[0].length).trim()\n return column.split('.').pop()!.trim()\n}\n\n/**\n * Laravel's query builder: DB.table('users').where('votes', '>', 100).get().\n * Implements the QueryBuilder contract other components use (Queue, Cache, Session, Validation).\n */\nexport class Builder<T = Row> implements QueryBuilder<T> {\n readonly grammar: Grammar\n columns: SelectColumn[] = []\n distinctRows = false\n fromTable: string | Expression | undefined\n joins: JoinClause[] = []\n wheres: Where[] = []\n groups: ColumnRef[] = []\n havings: Having[] = []\n orders: Order[] = []\n limitValue: number | undefined\n offsetValue: number | undefined\n lockMode: 'update' | 'share' | undefined\n\n constructor(\n readonly connection: Connection,\n table?: string | Expression,\n ) {\n this.grammar = new Grammar(connection.getDriverName())\n this.fromTable = table\n }\n\n // ---------------------------------------------------------------- building\n\n from(table: string | Expression): this {\n this.fromTable = table\n return this\n }\n\n select(...columns: Array<ColumnRef | ColumnRef[]>): this {\n this.columns = columns.flat()\n return this\n }\n\n addSelect(...columns: Array<ColumnRef | ColumnRef[]>): this {\n this.columns.push(...columns.flat())\n return this\n }\n\n selectRaw(expression: string, bindings: readonly unknown[] = []): this {\n this.columns.push(new Expression(expression, bindings))\n return this\n }\n\n /** Adds `(subquery) as alias` to the select list. */\n selectSub(query: Builder<unknown>, as: string): this {\n if (!this.columns.length) this.columns.push('*')\n this.columns.push({ query, as })\n return this\n }\n\n distinct(): this {\n this.distinctRows = true\n return this\n }\n\n where(column: ColumnRef, value: unknown): this\n where(column: ColumnRef, operator: Operator | string, value: unknown): this\n where(conditions: Row): this\n where(callback: NestedCallback<Builder<T>>): this\n where(...args: unknown[]): this {\n return this.addWhere('and', args)\n }\n\n orWhere(column: ColumnRef, value: unknown): this\n orWhere(column: ColumnRef, operator: Operator | string, value: unknown): this\n orWhere(conditions: Row): this\n orWhere(callback: NestedCallback<Builder<T>>): this\n orWhere(...args: unknown[]): this {\n return this.addWhere('or', args)\n }\n\n /** where not (…): whereNot(q => q.where('a', 1).orWhere('b', 2)). */\n whereNot(callback: NestedCallback<Builder<T>>): this {\n return this.addNested(callback, 'and', true)\n }\n\n orWhereNot(callback: NestedCallback<Builder<T>>): this {\n return this.addNested(callback, 'or', true)\n }\n\n whereIn(column: ColumnRef, values: readonly unknown[] | Builder<unknown>): this {\n this.wheres.push({ type: 'in', column, values: Array.isArray(values) ? [...values] : values, not: false, boolean: 'and' })\n return this\n }\n\n orWhereIn(column: ColumnRef, values: readonly unknown[] | Builder<unknown>): this {\n this.wheres.push({ type: 'in', column, values: Array.isArray(values) ? [...values] : values, not: false, boolean: 'or' })\n return this\n }\n\n whereNotIn(column: ColumnRef, values: readonly unknown[] | Builder<unknown>): this {\n this.wheres.push({ type: 'in', column, values: Array.isArray(values) ? [...values] : values, not: true, boolean: 'and' })\n return this\n }\n\n orWhereNotIn(column: ColumnRef, values: readonly unknown[] | Builder<unknown>): this {\n this.wheres.push({ type: 'in', column, values: Array.isArray(values) ? [...values] : values, not: true, boolean: 'or' })\n return this\n }\n\n whereNull(columns: ColumnRef | ColumnRef[]): this {\n for (const column of [columns].flat()) this.wheres.push({ type: 'null', column, not: false, boolean: 'and' })\n return this\n }\n\n orWhereNull(column: ColumnRef): this {\n this.wheres.push({ type: 'null', column, not: false, boolean: 'or' })\n return this\n }\n\n whereNotNull(columns: ColumnRef | ColumnRef[]): this {\n for (const column of [columns].flat()) this.wheres.push({ type: 'null', column, not: true, boolean: 'and' })\n return this\n }\n\n orWhereNotNull(column: ColumnRef): this {\n this.wheres.push({ type: 'null', column, not: true, boolean: 'or' })\n return this\n }\n\n whereBetween(column: ColumnRef, values: readonly [unknown, unknown]): this {\n this.wheres.push({ type: 'between', column, values, not: false, boolean: 'and' })\n return this\n }\n\n orWhereBetween(column: ColumnRef, values: readonly [unknown, unknown]): this {\n this.wheres.push({ type: 'between', column, values, not: false, boolean: 'or' })\n return this\n }\n\n whereNotBetween(column: ColumnRef, values: readonly [unknown, unknown]): this {\n this.wheres.push({ type: 'between', column, values, not: true, boolean: 'and' })\n return this\n }\n\n /** Compares two columns: whereColumn('updated_at', '>', 'created_at'). */\n whereColumn(first: ColumnRef, operatorOrSecond: string, second?: ColumnRef, boolean: WhereBoolean = 'and'): this {\n const [operator, other] = second === undefined ? ['=', operatorOrSecond] : [operatorOrSecond, second]\n this.grammar.operator(operator)\n this.wheres.push({ type: 'column', first, operator, second: other, boolean })\n return this\n }\n\n orWhereColumn(first: ColumnRef, operatorOrSecond: string, second?: ColumnRef): this {\n return this.whereColumn(first, operatorOrSecond, second, 'or')\n }\n\n whereRaw(sql: string, bindings: readonly unknown[] = [], boolean: WhereBoolean = 'and'): this {\n this.wheres.push({ type: 'raw', sql, bindings, boolean })\n return this\n }\n\n orWhereRaw(sql: string, bindings: readonly unknown[] = []): this {\n return this.whereRaw(sql, bindings, 'or')\n }\n\n whereExists(query: Builder<unknown> | NestedCallback<Builder<Row>>, boolean: WhereBoolean = 'and', not = false): this {\n const sub = query instanceof Builder ? query : this.subQuery(query)\n this.wheres.push({ type: 'exists', query: sub, not, boolean })\n return this\n }\n\n orWhereExists(query: Builder<unknown> | NestedCallback<Builder<Row>>): this {\n return this.whereExists(query, 'or')\n }\n\n whereNotExists(query: Builder<unknown> | NestedCallback<Builder<Row>>): this {\n return this.whereExists(query, 'and', true)\n }\n\n /** `(select …) <operator> value`: used by has('comments', '>=', 3). */\n whereSub(query: Builder<unknown>, operator: string, value: unknown, boolean: WhereBoolean = 'and'): this {\n this.grammar.operator(operator)\n this.wheres.push({ type: 'basic', column: query, operator, value, boolean })\n return this\n }\n\n /** Appends another builder's where clauses as one nested group. */\n addNestedWhereQuery(query: Builder<unknown>, boolean: WhereBoolean = 'and', not = false): this {\n if (query.wheres.length) this.wheres.push({ type: 'nested', query, not, boolean })\n return this\n }\n\n join(table: string | Expression, first: ColumnRef | ((join: JoinClause) => unknown), operator?: string, second?: ColumnRef, type: JoinType = 'inner'): this {\n const clause = new JoinClause(this, type, table)\n if (typeof first === 'function') first(clause)\n else clause.on(first, operator!, second)\n this.joins.push(clause)\n return this\n }\n\n leftJoin(table: string | Expression, first: ColumnRef | ((join: JoinClause) => unknown), operator?: string, second?: ColumnRef): this {\n return this.join(table, first, operator, second, 'left')\n }\n\n rightJoin(table: string | Expression, first: ColumnRef | ((join: JoinClause) => unknown), operator?: string, second?: ColumnRef): this {\n return this.join(table, first, operator, second, 'right')\n }\n\n crossJoin(table: string | Expression): this {\n this.joins.push(new JoinClause(this, 'cross', table))\n return this\n }\n\n groupBy(...columns: ColumnRef[]): this {\n this.groups.push(...columns)\n return this\n }\n\n having(column: ColumnRef, operatorOrValue: unknown, value?: unknown, boolean: WhereBoolean = 'and'): this {\n const [operator, operand] = value === undefined ? ['=', operatorOrValue] : [String(operatorOrValue), value]\n this.grammar.operator(operator)\n this.havings.push({ column, operator, value: operand, boolean })\n return this\n }\n\n havingRaw(sql: string, bindings: readonly unknown[] = [], boolean: WhereBoolean = 'and'): this {\n this.havings.push({ raw: new Expression(sql, bindings), boolean })\n return this\n }\n\n orderBy(column: ColumnRef, direction: Direction | Uppercase<Direction> = 'asc'): this {\n const normalized = direction.toLowerCase()\n if (normalized !== 'asc' && normalized !== 'desc') throw new LogicError('Order direction must be \"asc\" or \"desc\".')\n this.orders.push({ column, direction: normalized })\n return this\n }\n\n orderByDesc(column: ColumnRef): this {\n return this.orderBy(column, 'desc')\n }\n\n latest(column: ColumnRef = 'created_at'): this {\n return this.orderBy(column, 'desc')\n }\n\n oldest(column: ColumnRef = 'created_at'): this {\n return this.orderBy(column, 'asc')\n }\n\n inRandomOrder(): this {\n this.orders.push({ raw: this.grammar.compileRandom() })\n return this\n }\n\n orderByRaw(sql: string, bindings: readonly unknown[] = []): this {\n this.orders.push({ raw: new Expression(sql, bindings) })\n return this\n }\n\n /** Removes existing orders, optionally adding a new one. */\n reorder(column?: ColumnRef, direction: Direction = 'asc'): this {\n this.orders = []\n return column === undefined ? this : this.orderBy(column, direction)\n }\n\n limit(count: number): this {\n this.limitValue = count >= 0 ? Math.trunc(count) : undefined\n return this\n }\n\n take(count: number): this {\n return this.limit(count)\n }\n\n offset(count: number): this {\n this.offsetValue = Math.max(0, Math.trunc(count))\n return this\n }\n\n skip(count: number): this {\n return this.offset(count)\n }\n\n forPage(page: number, perPage = 15): this {\n return this.offset((Math.max(1, page) - 1) * perPage).limit(perPage)\n }\n\n lockForUpdate(): this {\n this.lockMode = 'update'\n return this\n }\n\n sharedLock(): this {\n this.lockMode = 'share'\n return this\n }\n\n /** Calls callback(this, value) when value is truthy (or the default callback otherwise). */\n when<V>(value: V, callback: (query: this, value: V) => unknown, otherwise?: (query: this, value: V) => unknown): this {\n if (value) callback(this, value)\n else otherwise?.(this, value)\n return this\n }\n\n tap(callback: (query: this) => unknown): this {\n callback(this)\n return this\n }\n\n // ---------------------------------------------------------------- reading\n\n async get(): Promise<Collection<T>> {\n return new Collection(await this.runSelect())\n }\n\n /** The raw rows, without a Collection around them. */\n async runSelect(): Promise<T[]> {\n return (await this.connection.execute<T>(this.grammar.compileSelect(this))).rows\n }\n\n async first(): Promise<T | undefined> {\n const rows = await this.clone().limit(1).runSelect()\n return rows[0]\n }\n\n async find(id: unknown, keyName = 'id'): Promise<T | undefined> {\n return this.clone().where(keyName, '=', id).first()\n }\n\n async value<V = unknown>(column: string): Promise<V | undefined> {\n const row = (await this.clone().select(column).first()) as Row | undefined\n return row?.[columnKey(column)] as V | undefined\n }\n\n async pluck<V = unknown>(column: string): Promise<Collection<V>> {\n const rows = (await this.clone().select(column).runSelect()) as Row[]\n const key = columnKey(column)\n return new Collection(rows.map((row) => row[key] as V))\n }\n\n async count(column: ColumnRef = '*'): Promise<number> {\n return Number((await this.aggregate('count', column)) ?? 0)\n }\n\n async min<V = unknown>(column: ColumnRef): Promise<V | undefined> {\n return (await this.aggregate('min', column)) as V | undefined\n }\n\n async max<V = unknown>(column: ColumnRef): Promise<V | undefined> {\n return (await this.aggregate('max', column)) as V | undefined\n }\n\n async sum(column: ColumnRef): Promise<number> {\n return Number((await this.aggregate('sum', column)) ?? 0)\n }\n\n async avg(column: ColumnRef): Promise<number | undefined> {\n const result = await this.aggregate('avg', column)\n return result === null || result === undefined ? undefined : Number(result)\n }\n\n async aggregate(fn: 'count' | 'min' | 'max' | 'sum' | 'avg', column: ColumnRef): Promise<unknown> {\n const result = await this.connection.execute<{ aggregate: unknown }>(this.grammar.compileAggregate(this, fn, column))\n return result.rows[0]?.aggregate ?? undefined\n }\n\n async exists(): Promise<boolean> {\n const result = await this.connection.execute<{ exists: unknown }>(this.grammar.compileExists(this))\n const value = result.rows[0]?.exists\n return value === true || value === 1 || value === '1' || value === 't'\n }\n\n async doesntExist(): Promise<boolean> {\n return !(await this.exists())\n }\n\n // ---------------------------------------------------------------- writing\n\n async insert(values: Row | Row[]): Promise<void> {\n const rows = Array.isArray(values) ? values : [values]\n if (!rows.length) return\n await this.connection.execute(this.grammar.compileInsert(this, rows))\n }\n\n /** Inserts one row and returns its auto-increment id. */\n async insertGetId(values: Row, keyName = 'id'): Promise<number | string> {\n const result = await this.connection.execute<Row>(this.grammar.compileInsertGetId(this, values, keyName))\n if (this.connection.getDriverName() === 'pgsql') return result.rows[0]![keyName] as number | string\n return Number(result.insertId)\n }\n\n /** Inserts rows, skipping the ones that violate a unique constraint. Returns how many were inserted. */\n async insertOrIgnore(values: Row | Row[]): Promise<number> {\n const rows = Array.isArray(values) ? values : [values]\n if (!rows.length) return 0\n return Number((await this.connection.execute(this.grammar.compileInsertOrIgnore(this, rows))).numAffectedRows ?? 0)\n }\n\n async update(values: Row): Promise<number> {\n if (!Object.keys(values).length) return 0\n return Number((await this.connection.execute(this.grammar.compileUpdate(this, values))).numAffectedRows ?? 0)\n }\n\n /** Updates the row matching attributes, or inserts attributes + values. */\n async updateOrInsert(attributes: Row, values: Row = {}): Promise<boolean> {\n if (!(await this.clone().where(attributes).exists())) {\n await this.insert({ ...attributes, ...values })\n return true\n }\n if (!Object.keys(values).length) return true\n await this.clone().where(attributes).update(values)\n return true\n }\n\n /**\n * Inserts rows, updating `update` (default: every inserted column except uniqueBy) when a row already exists.\n * uniqueBy must be a primary key or unique index (Postgres and SQLite need it for ON CONFLICT).\n */\n async upsert(values: Row | Row[], uniqueBy: string[], update?: string[]): Promise<number> {\n const rows = Array.isArray(values) ? values : [values]\n if (!rows.length) return 0\n const columns = update ?? Object.keys(rows[0]!).filter((column) => !uniqueBy.includes(column))\n if (!columns.length) return this.insertOrIgnore(rows)\n return Number((await this.connection.execute(this.grammar.compileUpsert(this, rows, uniqueBy, columns))).numAffectedRows ?? 0)\n }\n\n async increment(column: string, amount = 1, extra: Row = {}): Promise<number> {\n return this.update({ ...extra, [column]: sql`${this.grammar.wrap(column)} + ${amount}` })\n }\n\n async decrement(column: string, amount = 1, extra: Row = {}): Promise<number> {\n return this.update({ ...extra, [column]: sql`${this.grammar.wrap(column)} - ${amount}` })\n }\n\n async delete(id?: unknown): Promise<number> {\n if (id !== undefined) this.where('id', '=', id)\n return Number((await this.connection.execute(this.grammar.compileDelete(this))).numAffectedRows ?? 0)\n }\n\n async truncate(): Promise<void> {\n for (const statement of this.grammar.compileTruncate(this)) await this.connection.execute(statement)\n if (this.connection.getDriverName() === 'sqlite') {\n const sequence = await this.connection.select(\"select name from sqlite_master where type = 'table' and name = 'sqlite_sequence'\")\n if (sequence.length) await this.connection.statement('delete from sqlite_sequence where name = ?', [String(this.requireTable())])\n }\n }\n\n // ---------------------------------------------------------------- pagination and chunking\n\n /**\n * Paginates with a total count (two queries: count, then the page). The page comes from ?page= on the current\n * request unless given: DB.table('users').orderBy('id').paginate(15).\n */\n async paginate(perPage?: number, columns: ColumnRef[] = ['*'], pageName = 'page', page?: number): Promise<LengthAwarePaginator<T>> {\n const size = perPage ?? this.defaultPerPage()\n const current = page ?? AbstractPaginator.resolveCurrentPage(pageName)\n const total = await this.clone().count()\n const items = total > 0 ? await this.clone().withColumns(columns).forPage(current, size).runSelect() : []\n return new LengthAwarePaginator(items, total, size, current, { path: AbstractPaginator.resolveCurrentPath(), pageName })\n }\n\n /** Paginates without a count: fetches perPage + 1 rows to know whether there is a next page. */\n async simplePaginate(perPage?: number, columns: ColumnRef[] = ['*'], pageName = 'page', page?: number): Promise<Paginator<T>> {\n const size = perPage ?? this.defaultPerPage()\n const current = page ?? AbstractPaginator.resolveCurrentPage(pageName)\n const items = await this.clone().withColumns(columns).offset((current - 1) * size).limit(size + 1).runSelect()\n return new Paginator(items, size, current, { path: AbstractPaginator.resolveCurrentPath(), pageName })\n }\n\n /**\n * Paginates by the ordered columns' values instead of an offset. Needs an orderBy (Eloquent adds the primary key);\n * the cursor comes from ?cursor= on the current request unless given.\n */\n async cursorPaginate(perPage?: number, columns: ColumnRef[] = ['*'], cursorName = 'cursor', cursor?: Cursor | string): Promise<CursorPaginator<T>> {\n const size = perPage ?? this.defaultPerPage()\n const current = cursor instanceof Cursor ? cursor : cursor === undefined ? CursorPaginator.resolveCurrentCursor(cursorName) : Cursor.fromEncoded(cursor)\n const query = this.clone().withColumns(columns)\n const orders = query.ordersForCursor(current?.pointsToPreviousItems() ?? false)\n if (current) query.whereCursor(current, orders, 0)\n const items = await query.limit(size + 1).runSelect()\n return new CursorPaginator(items, size, current, {\n path: AbstractPaginator.resolveCurrentPath(),\n cursorName,\n parameters: orders.map((order) => String(order.column)),\n })\n }\n\n /**\n * Runs the query page by page and passes each chunk to callback. Return false to stop. Needs an orderBy, so that\n * pages don't overlap. Don't update the ordered column inside the callback; use chunkById() for that.\n */\n async chunk(count: number, callback: (results: Collection<T>, page: number) => unknown): Promise<boolean> {\n this.enforceOrderBy()\n for (let page = 1; ; page++) {\n const results = await this.clone().forPage(page, count).runSelect()\n if (!results.length) return true\n if ((await callback(new Collection(results), page)) === false) return false\n if (results.length < count) return true\n }\n }\n\n /** Chunks by comparing the key (where id > last id), so it is safe to update or delete rows inside the callback. */\n async chunkById(\n count: number,\n callback: (results: Collection<T>, page: number) => unknown,\n column?: string,\n alias?: string,\n ): Promise<boolean> {\n const key = column ?? this.defaultKeyName()\n const aliasName = alias ?? columnKey(key)\n let lastId: unknown\n for (let page = 1; ; page++) {\n const results = await this.clone().forPageAfterId(count, lastId, key).runSelect()\n if (!results.length) return true\n if ((await callback(new Collection(results), page)) === false) return false\n if (results.length < count) return true\n lastId = keyOf(results.at(-1), aliasName)\n }\n }\n\n /** Calls callback for every row, fetching `count` rows per query. Return false to stop. */\n async each(callback: (item: T, index: number) => unknown, count = 1000): Promise<boolean> {\n return this.chunk(count, async (results) => {\n for (const [index, item] of results.all().entries()) {\n if ((await callback(item, index)) === false) return false\n }\n return true\n })\n }\n\n /** A LazyCollection that runs one query per chunk as it is iterated: for await (const user of query.lazy()). */\n lazy(chunkSize = 1000): LazyCollection<T> {\n if (chunkSize < 1) throw new LogicError('The chunk size should be at least 1')\n this.enforceOrderBy()\n const query = this.clone()\n return LazyCollection.make(() => chunksOf(query, chunkSize))\n }\n\n /** Like lazy(), but pages by key, so rows can be updated while iterating. */\n lazyById(chunkSize = 1000, column?: string, alias?: string): LazyCollection<T> {\n if (chunkSize < 1) throw new LogicError('The chunk size should be at least 1')\n const key = column ?? this.defaultKeyName()\n const query = this.clone()\n return LazyCollection.make(() => chunksById(query, chunkSize, key, alias ?? columnKey(key)))\n }\n\n /** where column > lastId order by column limit perPage (existing orders on the column are replaced). */\n forPageAfterId(perPage = 15, lastId?: unknown, column = 'id'): this {\n this.orders = this.orders.filter((order) => 'raw' in order || order.column !== column)\n if (lastId !== undefined && lastId !== null) this.where(column, '>', lastId)\n return this.orderBy(column, 'asc').limit(perPage)\n }\n\n /** chunk() and lazy() need a stable order. Eloquent orders by the primary key instead of throwing. */\n protected enforceOrderBy(): void {\n if (!this.orders.length) throw new LogicError('You must specify an orderBy clause when using this function.')\n }\n\n /** The key chunkById()/lazyById() use by default. Eloquent uses the model's key. */\n protected defaultKeyName(): string {\n return 'id'\n }\n\n /** The page size when none is given. Eloquent uses the model's perPage. */\n protected defaultPerPage(): number {\n return 15\n }\n\n /** Laravel's get($columns): only applies when no columns were selected yet. */\n private withColumns(columns: ColumnRef[]): this {\n if (!this.columns.length && !(columns.length === 1 && columns[0] === '*')) this.select(...columns)\n return this\n }\n\n /** The column orders cursor pagination compares on; reversed (in the query too) when paging backwards. */\n private ordersForCursor(reverse: boolean): Array<{ column: ColumnRef; direction: Direction }> {\n this.enforceOrderBy()\n if (this.orders.some((order) => 'raw' in order)) throw new LogicError('cursorPaginate() only supports column orders, not orderByRaw() or inRandomOrder().')\n const orders = this.orders as Array<{ column: ColumnRef; direction: Direction }>\n if (reverse) this.orders = orders.map((order) => ({ column: order.column, direction: order.direction === 'asc' ? 'desc' : 'asc' }))\n return this.orders as Array<{ column: ColumnRef; direction: Direction }>\n }\n\n /** (a > ?) or (a = ? and (b > ? or (b = ? and …))), Laravel's cursor conditions. */\n private whereCursor(cursor: Cursor, orders: Array<{ column: ColumnRef; direction: Direction }>, index: number): void {\n const { column, direction } = orders[index]!\n this.where((query) => {\n query.where(column, direction === 'asc' ? '>' : '<', cursor.parameter(String(column)))\n if (index < orders.length - 1) {\n query.orWhere((next) => {\n next.where(column, '=', cursor.parameter(String(column)))\n next.whereCursor(cursor, orders, index + 1)\n })\n }\n })\n }\n\n // ---------------------------------------------------------------- helpers\n\n /** The compiled SQL (placeholders included), for debugging and tests. */\n toSql(): string {\n return this.connection.compile(this.grammar.compileSelect(this)).sql\n }\n\n getBindings(): unknown[] {\n return [...this.connection.compile(this.grammar.compileSelect(this)).parameters]\n }\n\n clone(): Builder<T> {\n const copy = Object.create(Object.getPrototypeOf(this) as object) as Builder<T>\n Object.assign(copy, this)\n copy.columns = [...this.columns]\n copy.joins = [...this.joins]\n copy.wheres = [...this.wheres]\n copy.groups = [...this.groups]\n copy.havings = [...this.havings]\n copy.orders = [...this.orders]\n return copy\n }\n\n /** A fresh builder on the same connection and table (for nested where groups). */\n newQuery(): Builder<Row> {\n return new Builder<Row>(this.connection, this.fromTable)\n }\n\n requireTable(): string | Expression {\n if (this.fromTable === undefined) throw new LogicError('No table was given: use DB.table(name) or query.from(name).')\n return this.fromTable\n }\n\n private subQuery(callback: NestedCallback<Builder<Row>>): Builder<Row> {\n const query = new Builder<Row>(this.connection)\n callback(query)\n return query\n }\n\n private addNested(callback: NestedCallback<Builder<T>>, boolean: WhereBoolean, not = false): this {\n const query = this.newQuery() as unknown as Builder<T>\n callback(query)\n return this.addNestedWhereQuery(query as Builder<unknown>, boolean, not)\n }\n\n private addWhere(boolean: WhereBoolean, args: unknown[]): this {\n const [column, operatorOrValue, maybeValue] = args\n if (typeof column === 'function') return this.addNested(column as NestedCallback<Builder<T>>, boolean)\n if (isRow(column)) {\n return this.addNested((query) => {\n for (const [key, value] of Object.entries(column)) query.where(key, value)\n }, boolean)\n }\n const [operator, value] = args.length === 2 ? ['=', operatorOrValue] : [String(operatorOrValue).toLowerCase(), maybeValue]\n const ref = column as ColumnRef\n if (operator === 'in' || operator === 'not in') {\n this.wheres.push({ type: 'in', column: ref, values: value as unknown[], not: operator === 'not in', boolean })\n return this\n }\n if (value === null || value === undefined) {\n if (operator === '=') return this.pushNull(ref, false, boolean)\n if (operator === '!=' || operator === '<>') return this.pushNull(ref, true, boolean)\n }\n this.grammar.operator(operator)\n this.wheres.push({ type: 'basic', column: ref, operator, value, boolean })\n return this\n }\n\n private pushNull(column: ColumnRef, not: boolean, boolean: WhereBoolean): this {\n this.wheres.push({ type: 'null', column, not, boolean })\n return this\n }\n}\n\nexport type JoinType = 'inner' | 'left' | 'right' | 'cross'\n\n/** The `on …` part of a join. `where()` on a join binds a value; `on()` compares columns. */\nexport class JoinClause extends Builder<Row> {\n constructor(\n parent: Builder<unknown>,\n readonly joinType: JoinType,\n readonly table: string | Expression,\n ) {\n super(parent.connection)\n }\n\n on(first: ColumnRef, operator: string, second?: ColumnRef, boolean: WhereBoolean = 'and'): this {\n return this.whereColumn(first, operator, second, boolean)\n }\n\n orOn(first: ColumnRef, operator: string, second?: ColumnRef): this {\n return this.on(first, operator, second, 'or')\n }\n}\n","import { Collection } from '@orieljs/collections'\n\nexport interface PaginatorOptions {\n /** The base URL of the page links (default: the current request's URL, or '/'). */\n path?: string\n /** Extra query string values added to every link. */\n query?: Record<string, unknown>\n fragment?: string\n pageName?: string\n}\n\n/** Laravel's Arr::query(): nested values become key[0]=…, encoded as RFC 3986. */\nexport function buildQuery(values: Record<string, unknown>, prefix?: string): string {\n const parts: string[] = []\n for (const [key, value] of Object.entries(values)) {\n const name = prefix === undefined ? key : `${prefix}[${key}]`\n if (value === undefined || value === null) continue\n if (typeof value === 'object') {\n const nested = buildQuery(value as Record<string, unknown>, name)\n if (nested) parts.push(nested)\n } else {\n parts.push(`${encodeURIComponent(name)}=${encodeURIComponent(String(value))}`)\n }\n }\n return parts.join('&')\n}\n\nconst isArrayable = (value: unknown): value is { toArray(): unknown } =>\n typeof value === 'object' && value !== null && typeof (value as { toArray?: unknown }).toArray === 'function'\n\n/**\n * Shared paginator state and URL building (Laravel's AbstractPaginator).\n * The static resolvers read the current request; DatabaseServiceProvider points them at HttpRequest.\n */\nexport abstract class AbstractPaginator<T> implements Iterable<T> {\n static currentPathResolver: () => string = () => '/'\n static currentPageResolver: (pageName: string) => number = () => 1\n static queryStringResolver: () => Record<string, unknown> = () => ({})\n static currentCursorResolver: (cursorName: string) => unknown = () => undefined\n\n static resolveCurrentPath(): string {\n return AbstractPaginator.currentPathResolver()\n }\n\n static resolveCurrentPage(pageName = 'page'): number {\n const page = AbstractPaginator.currentPageResolver(pageName)\n return Number.isInteger(page) && page >= 1 ? page : 1\n }\n\n /** Restores the defaults (page 1, path '/'). Used by tests and when the provider is torn down. */\n static resetResolvers(): void {\n AbstractPaginator.currentPathResolver = () => '/'\n AbstractPaginator.currentPageResolver = () => 1\n AbstractPaginator.queryStringResolver = () => ({})\n AbstractPaginator.currentCursorResolver = () => undefined\n }\n\n protected collection: Collection<T>\n protected pathValue: string\n protected queryValues: Record<string, unknown>\n protected fragmentValue: string | undefined\n protected pageName: string\n /** The resolved page number: page-based paginators pass it in; cursor pagination never reads it. */\n protected readonly currentPageValue: number\n onEachSideCount = 3\n\n protected constructor(\n items: Iterable<T>,\n protected readonly perPageValue: number,\n options: PaginatorOptions,\n currentPage?: number,\n ) {\n this.collection = new Collection(items)\n const path = options.path ?? AbstractPaginator.resolveCurrentPath()\n this.pathValue = path !== '/' ? path.replace(/\\/+$/, '') : path\n this.queryValues = { ...(options.query ?? {}) }\n this.fragmentValue = options.fragment\n this.pageName = options.pageName ?? 'page'\n this.currentPageValue = currentPage !== undefined && Number.isInteger(currentPage) && currentPage >= 1\n ? currentPage\n : AbstractPaginator.resolveCurrentPage(this.pageName)\n }\n\n currentPage(): number {\n return this.currentPageValue\n }\n\n /** The 1-based position of the first item on this page, or null when the page is empty. */\n firstItem(): number | null {\n return this.count() > 0 ? (this.currentPageValue - 1) * this.perPageValue + 1 : null\n }\n\n lastItem(): number | null {\n const first = this.firstItem()\n return first === null ? null : first + this.count() - 1\n }\n\n onFirstPage(): boolean {\n return this.currentPageValue <= 1\n }\n\n previousPageUrl(): string | null {\n return this.currentPageValue > 1 ? this.url(this.currentPageValue - 1) : null\n }\n\n /** The URL for a page number: path?query&page=n#fragment. */\n url(page: number): string {\n const parameters = { ...this.queryValues, [this.pageName]: Math.max(1, page) }\n return this.pathValue + (this.pathValue.includes('?') ? '&' : '?') + buildQuery(parameters) + this.buildFragment()\n }\n\n protected buildFragment(): string {\n return this.fragmentValue ? `#${this.fragmentValue}` : ''\n }\n\n path(): string {\n return this.pathValue\n }\n\n withPath(path: string): this {\n this.pathValue = path\n return this\n }\n\n setPath(path: string): this {\n return this.withPath(path)\n }\n\n /** Adds values to every link's query string. */\n appends(key: string | Record<string, unknown>, value?: unknown): this {\n if (typeof key === 'string') this.queryValues[key] = value\n else Object.assign(this.queryValues, key)\n return this\n }\n\n /** Keeps the current request's query string on every link. */\n withQueryString(): this {\n return this.appends(AbstractPaginator.queryStringResolver())\n }\n\n fragment(fragment: string): this {\n this.fragmentValue = fragment\n return this\n }\n\n getPageName(): string {\n return this.pageName\n }\n\n setPageName(name: string): this {\n this.pageName = name\n return this\n }\n\n onEachSide(count: number): this {\n this.onEachSideCount = count\n return this\n }\n\n /** The items on this page, as an array (Laravel's items()). */\n items(): T[] {\n return this.collection.all()\n }\n\n getCollection(): Collection<T> {\n return this.collection\n }\n\n setCollection(items: Collection<T>): this {\n this.collection = items\n return this\n }\n\n /** Transforms each item in place, typically for serialization: paginator.through(post => ({ id: post.id })). */\n through(callback: (item: T, index: number) => unknown): this {\n this.collection = this.collection.map(callback) as Collection<T>\n return this\n }\n\n perPage(): number {\n return this.perPageValue\n }\n\n count(): number {\n return this.collection.count()\n }\n\n isEmpty(): boolean {\n return this.collection.isEmpty()\n }\n\n isNotEmpty(): boolean {\n return !this.collection.isEmpty()\n }\n\n [Symbol.iterator](): Iterator<T> {\n return this.collection[Symbol.iterator]()\n }\n\n protected itemsToArray(): unknown[] {\n return this.collection.all().map((item) => (isArrayable(item) ? item.toArray() : item))\n }\n\n abstract toArray(): Record<string, unknown>\n\n toJSON(): Record<string, unknown> {\n return this.toArray()\n }\n\n toJson(): string {\n return JSON.stringify(this.toArray())\n }\n}\n","import { Collection } from '@orieljs/collections'\nimport { LogicError } from '../errors'\nimport { AbstractPaginator, buildQuery, type PaginatorOptions } from './AbstractPaginator'\n\n/** A position in a cursor-paginated result: the ordered columns' values of an edge item, plus the direction. */\nexport class Cursor {\n constructor(\n protected readonly parameters: Record<string, unknown>,\n protected readonly pointsToNext = true,\n ) {}\n\n parameter(name: string): unknown {\n if (!Object.hasOwn(this.parameters, name)) throw new LogicError(`Unable to find parameter [${name}] in pagination item.`)\n return this.parameters[name]\n }\n\n pointsToNextItems(): boolean {\n return this.pointsToNext\n }\n\n pointsToPreviousItems(): boolean {\n return !this.pointsToNext\n }\n\n toArray(): Record<string, unknown> {\n return { ...this.parameters, _pointsToNextItems: this.pointsToNext }\n }\n\n /** URL-safe base64 of the JSON parameters (Laravel's format). */\n encode(): string {\n return Buffer.from(JSON.stringify(this.toArray())).toString('base64').replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '')\n }\n\n /** Decodes a cursor from the query string. Anything malformed gives undefined (the first page). */\n static fromEncoded(encoded: unknown): Cursor | undefined {\n if (typeof encoded !== 'string' || encoded === '') return undefined\n try {\n const json: unknown = JSON.parse(Buffer.from(encoded.replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'))\n if (typeof json !== 'object' || json === null || Array.isArray(json)) return undefined\n const { _pointsToNextItems: pointsToNext, ...parameters } = json as Record<string, unknown>\n if (typeof pointsToNext !== 'boolean') return undefined\n return new Cursor(parameters, pointsToNext)\n } catch {\n return undefined\n }\n }\n}\n\nexport interface CursorPaginatorOptions extends Omit<PaginatorOptions, 'pageName'> {\n cursorName?: string\n /** The ordered columns whose values make up each cursor. */\n parameters: string[]\n}\n\n/** The value of `column` on a row or a model (a model's raw stored value, so it binds exactly as stored). */\nfunction valueOf(item: unknown, column: string): unknown {\n const key = column.includes('.') ? column.slice(column.lastIndexOf('.') + 1) : column\n const source = item as { getAttributes?: () => Record<string, unknown> } & Record<string, unknown>\n const values = typeof source.getAttributes === 'function' ? source.getAttributes() : source\n if (Object.hasOwn(values, column)) return values[column]\n if (Object.hasOwn(values, key)) return values[key]\n throw new LogicError(`Unable to find parameter [${column}] in pagination item.`)\n}\n\n/**\n * cursorPaginate(): \"next\"/\"previous\" by the ordered columns' values instead of an offset, so it stays fast and\n * stable on large, changing tables (Laravel's CursorPaginator). JSON: data, path, per_page, next_cursor,\n * next_page_url, prev_cursor, prev_page_url.\n */\nexport class CursorPaginator<T> extends AbstractPaginator<T> {\n protected readonly hasMore: boolean\n protected readonly cursorName: string\n protected readonly parameters: string[]\n\n constructor(\n items: Iterable<T>,\n perPage: number,\n protected readonly cursorValue: Cursor | undefined,\n options: CursorPaginatorOptions,\n ) {\n super(items, perPage, options)\n this.cursorName = options.cursorName ?? 'cursor'\n this.parameters = options.parameters\n this.hasMore = this.collection.count() > perPage\n this.collection = this.collection.slice(0, perPage)\n // Previous pages are fetched in reverse order; flip them back.\n if (cursorValue?.pointsToPreviousItems()) this.collection = new Collection(this.collection.all().reverse())\n }\n\n /** The cursor in the current request's query string (?cursor=…), if any. */\n static resolveCurrentCursor(cursorName = 'cursor'): Cursor | undefined {\n return Cursor.fromEncoded(AbstractPaginator.currentCursorResolver(cursorName))\n }\n\n cursor(): Cursor | undefined {\n return this.cursorValue\n }\n\n getCursorName(): string {\n return this.cursorName\n }\n\n hasMorePages(): boolean {\n return (this.cursorValue === undefined && this.hasMore) ||\n (this.cursorValue !== undefined && this.cursorValue.pointsToNextItems() && this.hasMore) ||\n (this.cursorValue !== undefined && this.cursorValue.pointsToPreviousItems())\n }\n\n override onFirstPage(): boolean {\n return this.cursorValue === undefined || (this.cursorValue.pointsToPreviousItems() && !this.hasMore)\n }\n\n nextCursor(): Cursor | undefined {\n if ((this.cursorValue === undefined || this.cursorValue.pointsToNextItems()) && !this.hasMore) return undefined\n const last = this.collection.last()\n return last === undefined ? undefined : this.cursorFor(last, true)\n }\n\n previousCursor(): Cursor | undefined {\n if (this.onFirstPage()) return undefined\n const first = this.collection.first()\n return first === undefined ? undefined : this.cursorFor(first, false)\n }\n\n nextPageUrl(): string | null {\n const cursor = this.nextCursor()\n return cursor ? this.url(cursor) : null\n }\n\n override previousPageUrl(): string | null {\n const cursor = this.previousCursor()\n return cursor ? this.url(cursor) : null\n }\n\n /** The URL for a cursor: path?query&cursor=…#fragment. */\n override url(cursor: Cursor | number): string {\n const value = typeof cursor === 'number' ? undefined : cursor.encode()\n const parameters = { ...this.queryValues, [this.cursorName]: value }\n return this.pathValue + (this.pathValue.includes('?') ? '&' : '?') + buildQuery(parameters) + this.buildFragment()\n }\n\n protected cursorFor(item: T, pointsToNext: boolean): Cursor {\n return new Cursor(Object.fromEntries(this.parameters.map((column) => [column, valueOf(item, column)])), pointsToNext)\n }\n\n toArray(): Record<string, unknown> {\n return {\n data: this.itemsToArray(),\n path: this.path(),\n per_page: this.perPageValue,\n next_cursor: this.nextCursor()?.encode() ?? null,\n next_page_url: this.nextPageUrl(),\n prev_cursor: this.previousCursor()?.encode() ?? null,\n prev_page_url: this.previousPageUrl(),\n }\n }\n}\n","import { AbstractPaginator, type PaginatorOptions } from './AbstractPaginator'\n\nexport interface PaginationLink {\n url: string | null\n label: string\n active: boolean\n}\n\n/** Page number → URL, in page order. */\ntype UrlRange = Array<[number, string]>\n\n/**\n * paginate(): knows the total, so it can render every page link (Laravel's LengthAwarePaginator).\n * JSON: current_page, data, first_page_url, from, last_page, last_page_url, links, next_page_url, path, per_page,\n * prev_page_url, to, total.\n */\nexport class LengthAwarePaginator<T> extends AbstractPaginator<T> {\n protected readonly lastPageValue: number\n\n constructor(\n items: Iterable<T>,\n protected readonly totalValue: number,\n perPage: number,\n currentPage?: number,\n options: PaginatorOptions = {},\n ) {\n super(items, perPage, options, currentPage)\n this.lastPageValue = Math.max(Math.ceil(totalValue / perPage), 1)\n }\n\n total(): number {\n return this.totalValue\n }\n\n lastPage(): number {\n return this.lastPageValue\n }\n\n hasPages(): boolean {\n return this.currentPageValue !== 1 || this.hasMorePages()\n }\n\n hasMorePages(): boolean {\n return this.currentPageValue < this.lastPageValue\n }\n\n onLastPage(): boolean {\n return !this.hasMorePages()\n }\n\n nextPageUrl(): string | null {\n return this.hasMorePages() ? this.url(this.currentPageValue + 1) : null\n }\n\n /** The page links Laravel renders: previous, the page window with '...' gaps, next. */\n linkCollection(): PaginationLink[] {\n const links: PaginationLink[] = [{ url: this.previousPageUrl(), label: '« Previous', active: false }]\n for (const element of this.elements()) {\n if (element === '...') links.push({ url: null, label: '...', active: false })\n else for (const [page, url] of element) links.push({ url, label: String(page), active: page === this.currentPageValue })\n }\n links.push({ url: this.nextPageUrl(), label: 'Next »', active: false })\n return links\n }\n\n /** Laravel's UrlWindow: the first pages, the slider around the current page and the last pages, with '...' between. */\n protected elements(): Array<UrlRange | '...'> {\n const window = this.urlWindow()\n const elements: Array<UrlRange | '...' | undefined> = [\n window.first,\n window.slider ? '...' : undefined,\n window.slider,\n window.last ? '...' : undefined,\n window.last,\n ]\n return elements.filter((element): element is UrlRange | '...' => element !== undefined && element.length > 0)\n }\n\n private urlWindow(): { first?: UrlRange; slider?: UrlRange; last?: UrlRange } {\n const onEachSide = this.onEachSideCount\n const last = this.lastPageValue\n const current = this.currentPageValue\n if (last < onEachSide * 2 + 8) return { first: this.range(1, last) }\n const window = onEachSide + 4\n if (!this.hasPages()) return {}\n if (current <= window) return { first: this.range(1, window + onEachSide), last: this.range(last - 1, last) }\n if (current > last - window) return { first: this.range(1, 2), last: this.range(last - (window + (onEachSide - 1)), last) }\n return {\n first: this.range(1, 2),\n slider: this.range(current - onEachSide, current + onEachSide),\n last: this.range(last - 1, last),\n }\n }\n\n private range(from: number, to: number): UrlRange {\n const pages: UrlRange = []\n for (let page = from; page <= to; page++) pages.push([page, this.url(page)])\n return pages\n }\n\n toArray(): Record<string, unknown> {\n return {\n current_page: this.currentPageValue,\n data: this.itemsToArray(),\n first_page_url: this.url(1),\n from: this.firstItem(),\n last_page: this.lastPageValue,\n last_page_url: this.url(this.lastPageValue),\n links: this.linkCollection(),\n next_page_url: this.nextPageUrl(),\n path: this.path(),\n per_page: this.perPageValue,\n prev_page_url: this.previousPageUrl(),\n to: this.lastItem(),\n total: this.totalValue,\n }\n }\n}\n","import { AbstractPaginator, type PaginatorOptions } from './AbstractPaginator'\n\n/**\n * simplePaginate(): no total, only \"is there a next page\". The query fetches perPage + 1 rows; the extra row only\n * sets hasMorePages() (Laravel's Paginator).\n */\nexport class Paginator<T> extends AbstractPaginator<T> {\n protected readonly hasMore: boolean\n\n constructor(items: Iterable<T>, perPage: number, currentPage?: number, options: PaginatorOptions = {}) {\n super(items, perPage, options, currentPage)\n this.hasMore = this.collection.count() > perPage\n this.collection = this.collection.slice(0, perPage)\n }\n\n hasMorePages(): boolean {\n return this.hasMore\n }\n\n hasPages(): boolean {\n return this.currentPageValue !== 1 || this.hasMore\n }\n\n onLastPage(): boolean {\n return !this.hasMore\n }\n\n nextPageUrl(): string | null {\n return this.hasMore ? this.url(this.currentPageValue + 1) : null\n }\n\n toArray(): Record<string, unknown> {\n return {\n current_page: this.currentPageValue,\n current_page_url: this.url(this.currentPageValue),\n data: this.itemsToArray(),\n first_page_url: this.url(1),\n from: this.firstItem(),\n next_page_url: this.nextPageUrl(),\n path: this.path(),\n per_page: this.perPageValue,\n prev_page_url: this.previousPageUrl(),\n to: this.lastItem(),\n }\n }\n}\n","import { sql, type RawBuilder } from 'kysely'\nimport type { DriverName, Row } from '@orieljs/contracts'\nimport { LogicError } from '../errors'\nimport { Expression, rawWithBindings } from './Expression'\nimport { prepareValue } from './values'\nimport type { Builder, Having, JoinClause, Where } from './Builder'\n\ntype Sql = RawBuilder<unknown>\n\n/** The operators accepted by where()/having(). Anything else is rejected: operators are written into the SQL. */\nexport const OPERATORS = new Set(['=', '<', '>', '<=', '>=', '<>', '!=', 'like', 'not like', 'ilike', 'not ilike'])\n\nconst EMPTY: Sql = sql.raw('')\nconst isSqlFragment = (value: unknown): value is Sql =>\n typeof value === 'object' && value !== null && typeof (value as Partial<Sql>).toOperationNode === 'function'\nconst join = (parts: Sql[], separator = ', '): Sql => sql.join(parts, sql.raw(separator))\n/** Joins non-empty clauses with single spaces. */\nconst clauses = (parts: Array<Sql | undefined>): Sql => join(parts.filter((part): part is Sql => part !== undefined), ' ')\n\n/**\n * Compiles a query builder's state into a Kysely `sql` template for one driver, like Laravel's Query\\Grammars.\n * Identifiers go through sql.id() (quoted per dialect); values are always bound parameters.\n */\nexport class Grammar {\n constructor(readonly driver: DriverName) {}\n\n /** 'users.name' → \"users\".\"name\", 'users.*' → \"users\".*, 'name as n' → \"name\" as \"n\". Expressions pass through raw. */\n wrap(value: string | Expression): Sql {\n if (value instanceof Expression) return rawWithBindings(value.value, value.bindings.map((v) => this.prepare(v)))\n const alias = /\\s+as\\s+/i.exec(value)\n if (alias) {\n const left = value.slice(0, alias.index)\n const right = value.slice(alias.index + alias[0].length)\n return sql`${this.wrap(left)} as ${sql.id(right.trim())}`\n }\n return join(\n value.split('.').map((segment) => (segment === '*' ? sql.raw('*') : sql.id(segment))),\n '.',\n )\n }\n\n wrapTable(table: string | Expression): Sql {\n return this.wrap(table)\n }\n\n prepare(value: unknown): unknown {\n return prepareValue(value, this.driver)\n }\n\n /** A bound value, the raw SQL of an Expression, or a Kysely sql fragment as-is. */\n parameter(value: unknown): Sql {\n if (value instanceof Expression) return this.wrap(value)\n if (isSqlFragment(value)) return value\n return sql`${this.prepare(value)}`\n }\n\n operator(operator: string): string {\n const normalized = operator.toLowerCase()\n if (!OPERATORS.has(normalized)) throw new LogicError(`Illegal operator [${operator}].`)\n if (this.driver !== 'pgsql' && normalized.endsWith('ilike')) return normalized.replace('ilike', 'like')\n return normalized\n }\n\n columnize(columns: ReadonlyArray<string | Expression>): Sql {\n return join(columns.map((column) => this.wrap(column)))\n }\n\n compileSelect(query: Builder<unknown>): Sql {\n const columns = query.columns.length\n ? join(query.columns.map((column) => (typeof column === 'object' && 'query' in column\n ? sql`(${this.compileSelect(column.query)}) as ${sql.id(column.as)}`\n : this.wrap(column))))\n : sql.raw('*')\n return clauses([query.distinctRows ? sql`select distinct ${columns}` : sql`select ${columns}`, this.compileComponents(query)])\n }\n\n /** Everything after the select list: from, joins, where, group by, having, order by, limit/offset, lock. */\n compileComponents(query: Builder<unknown>): Sql {\n return clauses([\n query.fromTable === undefined ? undefined : sql`from ${this.wrapTable(query.fromTable)}`,\n ...query.joins.map((joinClause) => this.compileJoin(joinClause)),\n this.compileWheres(query.wheres, 'where'),\n query.groups.length ? sql`group by ${this.columnize(query.groups)}` : undefined,\n this.compileHavings(query.havings),\n this.compileOrders(query),\n this.compileLimitOffset(query.limitValue, query.offsetValue),\n this.compileLock(query.lockMode),\n ])\n }\n\n compileOrders(query: Builder<unknown>): Sql | undefined {\n if (!query.orders.length) return undefined\n return sql`order by ${join(query.orders.map((order) => ('raw' in order ? this.wrap(order.raw) : sql`${this.wrap(order.column)} ${sql.raw(order.direction)}`)))}`\n }\n\n compileWheres(wheres: readonly Where[], keyword?: 'where' | 'on'): Sql | undefined {\n if (!wheres.length) return undefined\n const body = join(wheres.map((where, i) => (i === 0 ? this.compileWhere(where) : sql`${sql.raw(where.boolean)} ${this.compileWhere(where)}`)), ' ')\n return keyword ? sql`${sql.raw(keyword)} ${body}` : body\n }\n\n compileWhere(where: Where): Sql {\n switch (where.type) {\n case 'basic': {\n const column = typeof where.column === 'object' && !(where.column instanceof Expression)\n ? sql`(${this.compileSelect(where.column)})`\n : this.wrap(where.column)\n return sql`${column} ${sql.raw(this.operator(where.operator))} ${this.parameter(where.value)}`\n }\n case 'in': {\n const keyword = sql.raw(where.not ? 'not in' : 'in')\n if (!Array.isArray(where.values)) return sql`${this.wrap(where.column)} ${keyword} (${this.compileSelect(where.values as Builder<unknown>)})`\n if (where.values.length === 0) return sql.raw(where.not ? '1 = 1' : '0 = 1')\n return sql`${this.wrap(where.column)} ${keyword} (${join(where.values.map((value) => this.parameter(value)))})`\n }\n case 'null':\n return sql`${this.wrap(where.column)} ${sql.raw(where.not ? 'is not null' : 'is null')}`\n case 'between':\n return sql`${this.wrap(where.column)} ${sql.raw(where.not ? 'not between' : 'between')} ${this.parameter(where.values[0])} and ${this.parameter(where.values[1])}`\n case 'column':\n return sql`${this.wrap(where.first)} ${sql.raw(this.operator(where.operator))} ${this.wrap(where.second)}`\n case 'nested':\n return sql`${sql.raw(where.not ? 'not ' : '')}(${this.compileWheres(where.query.wheres) ?? EMPTY})`\n case 'exists':\n return sql`${sql.raw(where.not ? 'not exists' : 'exists')} (${this.compileSelect(where.query)})`\n case 'raw':\n return rawWithBindings(where.sql, where.bindings.map((value) => this.prepare(value)))\n }\n }\n\n compileJoin(joinClause: JoinClause): Sql {\n if (joinClause.joinType === 'cross') return sql`cross join ${this.wrapTable(joinClause.table)}`\n return sql`${sql.raw(joinClause.joinType)} join ${this.wrapTable(joinClause.table)} ${this.compileWheres(joinClause.wheres, 'on') ?? EMPTY}`\n }\n\n compileHavings(havings: readonly Having[]): Sql | undefined {\n if (!havings.length) return undefined\n const parts = havings.map((having, i) => {\n const body = 'raw' in having\n ? this.wrap(having.raw)\n : sql`${this.wrap(having.column)} ${sql.raw(this.operator(having.operator))} ${this.parameter(having.value)}`\n return i === 0 ? body : sql`${sql.raw(having.boolean)} ${body}`\n })\n return sql`having ${join(parts, ' ')}`\n }\n\n compileLimitOffset(limit: number | undefined, offset: number | undefined): Sql | undefined {\n if (limit === undefined && offset === undefined) return undefined\n const parts: Sql[] = []\n if (limit !== undefined) parts.push(sql`limit ${sql.lit(limit)}`)\n // SQLite and MySQL can't OFFSET without a LIMIT.\n else if (this.driver === 'sqlite') parts.push(sql.raw('limit -1'))\n else if (this.driver === 'mysql') parts.push(sql.raw('limit 18446744073709551615'))\n if (offset !== undefined) parts.push(sql`offset ${sql.lit(offset)}`)\n return join(parts, ' ')\n }\n\n compileLock(mode: 'update' | 'share' | undefined): Sql | undefined {\n if (mode === undefined || this.driver === 'sqlite') return undefined\n if (mode === 'update') return sql.raw('for update')\n return sql.raw(this.driver === 'pgsql' ? 'for share' : 'lock in share mode')\n }\n\n /** `select count(*) as aggregate …`. Orders, limit and offset are dropped; grouped or distinct queries are wrapped. */\n compileAggregate(query: Builder<unknown>, fn: string, column: string | Expression): Sql {\n const inner = query.clone()\n inner.orders = []\n inner.limitValue = undefined\n inner.offsetValue = undefined\n inner.lockMode = undefined\n const target = column === '*' ? sql.raw('*') : this.wrap(column)\n if (inner.groups.length || inner.distinctRows) {\n if (fn === 'count') return sql`select count(*) as ${sql.id('aggregate')} from (${this.compileSelect(inner)}) as ${sql.id('temp_table')}`\n if (column instanceof Expression) {\n throw new LogicError(`${fn}() can't target a raw expression over a distinct or grouped query: select it as an aliased column instead.`)\n }\n if (!inner.columns.length) inner.columns = [column]\n const unqualified = column.split('.').pop()!.trim()\n return sql`select ${sql.raw(fn)}(${sql.id(unqualified)}) as ${sql.id('aggregate')} from (${this.compileSelect(inner)}) as ${sql.id('temp_table')}`\n }\n return sql`select ${sql.raw(fn)}(${target}) as ${sql.id('aggregate')} ${this.compileComponents(inner)}`\n }\n\n compileExists(query: Builder<unknown>): Sql {\n return sql`select exists(${this.compileSelect(query)}) as ${sql.id('exists')}`\n }\n\n compileInsert(query: Builder<unknown>, rows: readonly Row[]): Sql {\n if (rows.every((row) => !Object.keys(row).length)) {\n const table = this.wrapTable(query.requireTable())\n return this.driver === 'mysql' ? sql`insert into ${table} () values ()` : sql`insert into ${table} default values`\n }\n return sql`insert ${this.compileInsertBody(query, rows)}`\n }\n\n compileInsertOrIgnore(query: Builder<unknown>, rows: readonly Row[]): Sql {\n const body = this.compileInsertBody(query, rows)\n if (this.driver === 'mysql') return sql`insert ignore ${body}`\n if (this.driver === 'sqlite') return sql`insert or ignore ${body}`\n return sql`insert ${body} on conflict do nothing`\n }\n\n /** `into \"table\" (\"a\", \"b\") values (?, ?), (?, ?)`. Columns are the union of every row's keys; a missing key binds null. */\n compileInsertBody(query: Builder<unknown>, rows: readonly Row[]): Sql {\n const columns = [...new Set(rows.flatMap((row) => Object.keys(row)))]\n const values = join(rows.map((row) => sql`(${join(columns.map((column) => this.parameter(row[column])))})`))\n return sql`into ${this.wrapTable(query.requireTable())} (${this.columnize(columns)}) values ${values}`\n }\n\n compileInsertGetId(query: Builder<unknown>, row: Row, keyName: string): Sql {\n const insert = this.compileInsert(query, [row])\n return this.driver === 'pgsql' ? sql`${insert} returning ${this.wrap(keyName)}` : insert\n }\n\n compileUpsert(query: Builder<unknown>, rows: readonly Row[], uniqueBy: readonly string[], update: readonly string[]): Sql {\n const insert = this.compileInsert(query, rows)\n if (this.driver === 'mysql') {\n const alias = 'laravel_upsert_alias'\n const sets = join(update.map((column) => sql`${this.wrap(column)} = ${sql.id(alias, column)}`))\n return sql`${insert} as ${sql.id(alias)} on duplicate key update ${sets}`\n }\n const sets = join(update.map((column) => sql`${this.wrap(column)} = ${sql.id('excluded', column)}`))\n return sql`${insert} on conflict (${this.columnize(uniqueBy)}) do update set ${sets}`\n }\n\n compileUpdate(query: Builder<unknown>, values: Row): Sql {\n this.assertSimpleMutation(query, 'update')\n const sets = join(Object.entries(values).map(([column, value]) => sql`${this.wrap(column.split('.').pop()!)} = ${this.parameter(value)}`))\n return clauses([\n sql`update ${this.wrapTable(query.requireTable())} set ${sets}`,\n this.compileWheres(query.wheres, 'where'),\n ...this.mysqlOrderAndLimit(query),\n ])\n }\n\n compileDelete(query: Builder<unknown>): Sql {\n this.assertSimpleMutation(query, 'delete')\n return clauses([\n sql`delete from ${this.wrapTable(query.requireTable())}`,\n this.compileWheres(query.wheres, 'where'),\n ...this.mysqlOrderAndLimit(query),\n ])\n }\n\n compileTruncate(query: Builder<unknown>): Sql[] {\n const table = this.wrapTable(query.requireTable())\n if (this.driver === 'pgsql') return [sql`truncate table ${table} restart identity cascade`]\n if (this.driver === 'mysql') return [sql`truncate table ${table}`]\n return [sql`delete from ${table}`]\n }\n\n compileRandom(): Expression {\n return new Expression(this.driver === 'mysql' ? 'RAND()' : 'random()')\n }\n\n private assertSimpleMutation(query: Builder<unknown>, action: string): void {\n if (query.joins.length || query.offsetValue !== undefined || (query.limitValue !== undefined && this.driver !== 'mysql')) {\n throw new LogicError(`${action}() with joins, offset or (except on MySQL) limit isn't supported. Select the keys first, then ${action} with whereIn().`)\n }\n }\n\n private mysqlOrderAndLimit(query: Builder<unknown>): Array<Sql | undefined> {\n if (this.driver !== 'mysql') return []\n return [\n this.compileOrders(query),\n query.limitValue === undefined ? undefined : sql`limit ${sql.lit(query.limitValue)}`,\n ]\n }\n}\n","import type { DriverName } from '@orieljs/contracts'\nimport { LogicError } from '../errors'\n\nconst pad = (n: number, width = 2) => String(n).padStart(width, '0')\n\n/** Laravel's storage format ('Y-m-d H:i:s'), in UTC. */\nexport function formatDateTime(date: Date): string {\n return (\n `${pad(date.getUTCFullYear(), 4)}-${pad(date.getUTCMonth() + 1)}-${pad(date.getUTCDate())} ` +\n `${pad(date.getUTCHours())}:${pad(date.getUTCMinutes())}:${pad(date.getUTCSeconds())}`\n )\n}\n\nexport function formatDate(date: Date): string {\n return formatDateTime(date).slice(0, 10)\n}\n\n/**\n * Parses a stored date/time as UTC. Accepts Dates, epoch milliseconds, 'Y-m-d', 'Y-m-d H:i:s' and ISO strings\n * (the last two with or without a zone suffix; a missing zone means UTC).\n */\nexport function parseDateTime(value: unknown): Date {\n if (value instanceof Date) return new Date(value.getTime())\n if (typeof value === 'number') return new Date(value)\n const text = String(value).trim()\n const match = /^(\\d{4}-\\d{2}-\\d{2})(?:[ T](\\d{2}:\\d{2}(?::\\d{2}(?:\\.\\d+)?)?))?\\s*(Z|[+-]\\d{2}(?::?\\d{2})?)?$/i.exec(text)\n if (match) {\n const [, day, time = '00:00:00', zone] = match\n let offset = 'Z'\n if (zone && zone.toUpperCase() !== 'Z') offset = zone.length === 3 ? `${zone}:00` : zone.includes(':') ? zone : `${zone.slice(0, 3)}:${zone.slice(3)}`\n return new Date(`${day}T${time.length === 5 ? `${time}:00` : time}${offset}`)\n }\n const parsed = new Date(text)\n if (Number.isNaN(parsed.getTime())) throw new LogicError(`Unable to parse [${text}] as a date.`)\n return parsed\n}\n\nconst isPlainObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && Object.getPrototypeOf(value) === Object.prototype\n\n/** Normalizes one binding for the driver: booleans, dates, JSON and undefined. */\nexport function prepareValue(value: unknown, driver: DriverName): unknown {\n if (value === undefined) return null\n if (typeof value === 'boolean') return driver === 'pgsql' ? value : value ? 1 : 0\n if (value instanceof Date) return formatDateTime(value)\n if (Array.isArray(value) || isPlainObject(value)) return JSON.stringify(value)\n return value\n}\n","import { AsyncLocalStorage } from 'node:async_hooks'\nimport { Kysely, sql, type CompiledQuery, type ControlledTransaction, type QueryResult, type RawBuilder } from 'kysely'\nimport type { DatabaseConnection, DriverName, Row } from '@orieljs/contracts'\nimport { createDialect, type ConnectionConfig } from './Connectors/dialect'\nimport { QueryError } from './errors'\nimport { Builder } from './Query/Builder'\nimport { Expression, rawWithBindings } from './Query/Expression'\nimport { prepareValue } from './Query/values'\nimport { SchemaBuilder } from './Schema/Builder'\n\n/** One open transaction level. Level 1 is the real transaction; deeper levels are savepoints named trans<level>. */\ninterface TransactionFrame {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n readonly trx: ControlledTransaction<any>\n readonly level: number\n}\n\nexport interface LoggedQuery {\n query: string\n bindings: readonly unknown[]\n time: number\n}\n\n/**\n * A named database connection on Kysely.\n *\n * Transactions: `transaction(fn)` is bound to the async context that called it (AsyncLocalStorage), so a\n * transaction in one request never captures another request's queries. `beginTransaction()` instead pins the\n * transaction to the whole connection until `commit()`/`rollBack()`; that is what RefreshDatabase needs.\n * Nested levels use savepoints (trans2, trans3, …) either way.\n */\nexport class Connection implements DatabaseConnection {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n protected readonly db: Kysely<any>\n private readonly context = new AsyncLocalStorage<TransactionFrame>()\n private readonly pinned: TransactionFrame[] = []\n private loggingQueries = false\n private queryLog: LoggedQuery[] = []\n\n constructor(\n protected readonly name: string,\n protected readonly config: ConnectionConfig,\n ) {\n this.db = new Kysely({ dialect: createDialect(config) })\n }\n\n getName(): string {\n return this.name\n }\n\n getDriverName(): DriverName {\n return this.config.driver\n }\n\n getConfig(): ConnectionConfig {\n return this.config\n }\n\n /** A query builder for a table: connection.table('users').where('votes', '>', 100).get(). */\n table<T = Row>(table: string | Expression): Builder<T> {\n return new Builder<T>(this, table)\n }\n\n /** A query builder with no table yet (use from()). */\n query<T = Row>(): Builder<T> {\n return new Builder<T>(this)\n }\n\n /** Schema operations on this connection (Laravel's getSchemaBuilder()). */\n getSchemaBuilder(): SchemaBuilder {\n return new SchemaBuilder(this)\n }\n\n /** Raw Kysely access. Inside a transaction this is the transaction, so queries join it. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n kysely(): Kysely<any> {\n return this.current()?.trx ?? this.db\n }\n\n /** Normalizes a value for this driver (booleans, Dates, JSON). */\n prepareValue(value: unknown): unknown {\n return prepareValue(value, this.config.driver)\n }\n\n /** Compiles a Kysely raw builder against this connection's dialect. */\n compile(query: RawBuilder<unknown>): CompiledQuery {\n return query.compile(this.db)\n }\n\n /** Runs a compiled statement on the current executor (the transaction, when one is open). */\n async execute<T = Row>(query: RawBuilder<unknown> | CompiledQuery): Promise<QueryResult<T>> {\n const compiled = 'compile' in query ? this.compile(query) : query\n const started = performance.now()\n try {\n return await this.kysely().executeQuery<T>(compiled)\n } catch (error) {\n throw new QueryError(this.name, compiled.sql, compiled.parameters, error)\n } finally {\n if (this.loggingQueries) {\n this.queryLog.push({ query: compiled.sql, bindings: compiled.parameters, time: performance.now() - started })\n }\n }\n }\n\n /** Raw select with `?` placeholders. */\n async select<T = Row>(query: string, bindings: readonly unknown[] = []): Promise<T[]> {\n return (await this.execute<T>(this.raw(query, bindings))).rows\n }\n\n /** Raw statement with `?` placeholders. */\n async statement(query: string, bindings: readonly unknown[] = []): Promise<void> {\n await this.execute(this.raw(query, bindings))\n }\n\n /** Raw statement; returns the number of affected rows. */\n async affectingStatement(query: string, bindings: readonly unknown[] = []): Promise<number> {\n return Number((await this.execute(this.raw(query, bindings))).numAffectedRows ?? 0)\n }\n\n private raw(query: string, bindings: readonly unknown[]): RawBuilder<unknown> {\n return rawWithBindings(query, bindings.map((value) => this.prepareValue(value)))\n }\n\n /** Runs fn in a transaction (a savepoint when nested). Commits when fn resolves, rolls back and rethrows when it throws. */\n async transaction<R>(fn: (connection: this) => Promise<R>): Promise<R> {\n const frame = await this.open()\n let result: R\n try {\n result = await this.context.run(frame, () => fn(this))\n } catch (error) {\n await this.close(frame, 'rollback')\n throw error\n }\n await this.close(frame, 'commit')\n return result\n }\n\n /** Starts a transaction that stays open, for every async context, until commit()/rollBack(). */\n async beginTransaction(): Promise<void> {\n this.pinned.push(await this.open())\n }\n\n async commit(): Promise<void> {\n const frame = this.pinned.pop()\n if (frame) await this.close(frame, 'commit')\n }\n\n /** Rolls back the innermost level opened by beginTransaction(). Does nothing when none is open. */\n async rollBack(): Promise<void> {\n const frame = this.pinned.pop()\n if (frame) await this.close(frame, 'rollback')\n }\n\n transactionLevel(): number {\n return this.current()?.level ?? 0\n }\n\n enableQueryLog(): void {\n this.loggingQueries = true\n }\n\n disableQueryLog(): void {\n this.loggingQueries = false\n }\n\n getQueryLog(): LoggedQuery[] {\n return [...this.queryLog]\n }\n\n flushQueryLog(): void {\n this.queryLog = []\n }\n\n async disconnect(): Promise<void> {\n await this.db.destroy()\n }\n\n /** The innermost open level: the context's own transaction or a pinned one, whichever is deeper. */\n private current(): TransactionFrame | undefined {\n const own = this.context.getStore()\n const pinned = this.pinned.at(-1)\n if (!own) return pinned\n if (!pinned) return own\n return pinned.level > own.level ? pinned : own\n }\n\n private async open(): Promise<TransactionFrame> {\n const parent = this.current()\n if (!parent) return { trx: await this.db.startTransaction().execute(), level: 1 }\n const level = parent.level + 1\n await sql.raw(`SAVEPOINT trans${level}`).execute(parent.trx)\n return { trx: parent.trx, level }\n }\n\n private async close(frame: TransactionFrame, action: 'commit' | 'rollback'): Promise<void> {\n if (frame.level === 1) {\n await (action === 'commit' ? frame.trx.commit() : frame.trx.rollback()).execute()\n } else if (action === 'commit') {\n await sql.raw(`RELEASE SAVEPOINT trans${frame.level}`).execute(frame.trx)\n } else {\n await sql.raw(`ROLLBACK TO SAVEPOINT trans${frame.level}`).execute(frame.trx)\n }\n }\n}\n","import { sql, type RawBuilder } from 'kysely'\nimport type { Connection } from '../Connection'\nimport { LogicError } from '../errors'\nimport { Blueprint } from './Blueprint'\nimport { SchemaGrammar, type ColumnInfo } from './Grammar'\n\n/**\n * Laravel's Schema builder for one connection: Schema.create('posts', (t) => { t.id(); t.string('title') }).\n * Each blueprint compiles to one or more statements, run in order.\n */\nexport class SchemaBuilder {\n readonly grammar: SchemaGrammar\n\n constructor(\n protected readonly db: Connection,\n private readonly resolveConnection?: (name: string) => Connection,\n ) {\n this.grammar = SchemaGrammar.for(db.getDriverName(), db.getConfig())\n }\n\n getConnection(): Connection {\n return this.db\n }\n\n /** The schema builder of another connection: Schema.connection('pgsql').create(…). */\n connection(name: string): SchemaBuilder {\n if (!this.resolveConnection) throw new LogicError('This schema builder has no connection resolver.')\n return new SchemaBuilder(this.resolveConnection(name), this.resolveConnection)\n }\n\n async create(table: string, callback: (table: Blueprint) => void): Promise<void> {\n const blueprint = new Blueprint(table, true)\n callback(blueprint)\n await this.build(blueprint)\n }\n\n /** Changes an existing table: add columns, indexes and foreign keys, drop or rename columns. */\n async table(table: string, callback: (table: Blueprint) => void): Promise<void> {\n const blueprint = new Blueprint(table)\n callback(blueprint)\n await this.build(blueprint)\n }\n\n async drop(table: string): Promise<void> {\n await this.run([this.grammar.compileDrop(table)])\n }\n\n async dropIfExists(table: string): Promise<void> {\n await this.run([this.grammar.compileDropIfExists(table)])\n }\n\n async rename(from: string, to: string): Promise<void> {\n await this.run([this.grammar.compileRename(from, to)])\n }\n\n /** Runs a blueprint's statements. Also useful to inspect the DDL: grammar.compile(blueprint). */\n async build(blueprint: Blueprint): Promise<void> {\n await this.run(this.grammar.compile(blueprint))\n }\n\n /** The table names of the connection's database (or current schema on Postgres). */\n async getTables(): Promise<string[]> {\n const rows = (await this.db.execute<{ name: string }>(this.grammar.compileTables())).rows\n return rows.map((row) => String(row.name))\n }\n\n async hasTable(table: string): Promise<boolean> {\n return (await this.getTables()).includes(table)\n }\n\n async getColumns(table: string): Promise<ColumnInfo[]> {\n const rows = (await this.db.execute<Record<string, unknown>>(this.grammar.compileColumns(table))).rows\n return this.grammar.normalizeColumns(rows)\n }\n\n async getColumnListing(table: string): Promise<string[]> {\n return (await this.getColumns(table)).map((column) => column.name)\n }\n\n /** Case-insensitive, like Laravel. */\n async hasColumn(table: string, column: string): Promise<boolean> {\n return this.hasColumns(table, [column])\n }\n\n async hasColumns(table: string, columns: string[]): Promise<boolean> {\n const existing = (await this.getColumnListing(table)).map((name) => name.toLowerCase())\n return columns.every((column) => existing.includes(column.toLowerCase()))\n }\n\n async enableForeignKeyConstraints(): Promise<void> {\n await this.run([this.grammar.compileEnableForeignKeyConstraints()])\n }\n\n async disableForeignKeyConstraints(): Promise<void> {\n await this.run([this.grammar.compileDisableForeignKeyConstraints()])\n }\n\n /**\n * Runs fn with foreign key checks off. On MySQL and Postgres the connection is pinned (a transaction) so the\n * setting and fn's statements share one pooled connection; SQLite has a single connection already.\n */\n async withoutForeignKeyConstraints<R>(fn: () => Promise<R>): Promise<R> {\n const run = async () => {\n await this.disableForeignKeyConstraints()\n try {\n return await fn()\n } finally {\n await this.enableForeignKeyConstraints()\n }\n }\n return this.db.getDriverName() === 'sqlite' ? run() : this.db.transaction(run)\n }\n\n /** Drops every table (migrate:fresh). */\n async dropAllTables(): Promise<void> {\n const tables = await this.getTables()\n if (!tables.length) return\n if (this.db.getDriverName() === 'pgsql') {\n await this.run([sql`drop table ${sql.join(tables.map((table) => sql.id(table)))} cascade`])\n return\n }\n await this.withoutForeignKeyConstraints(async () => {\n for (const table of tables) await this.run([this.grammar.compileDrop(table)])\n })\n }\n\n private async run(statements: Array<RawBuilder<unknown>>): Promise<void> {\n for (const statement of statements) await this.db.execute(statement)\n }\n}\n","import { Expression } from '../Query/Expression'\n\nexport type ColumnType =\n | 'bigInteger' | 'integer' | 'mediumInteger' | 'smallInteger' | 'tinyInteger'\n | 'string' | 'char' | 'text' | 'mediumText' | 'longText'\n | 'boolean' | 'date' | 'dateTime' | 'time' | 'timestamp'\n | 'decimal' | 'float' | 'double'\n | 'json' | 'jsonb' | 'uuid' | 'ulid' | 'binary' | 'enum'\n\n/** Everything a column definition can carry. Grammars read these; the fluent methods set them. */\nexport interface ColumnAttributes {\n type: ColumnType\n name: string\n length?: number\n total?: number\n places?: number\n precision?: number\n allowed?: readonly string[]\n autoIncrement?: boolean\n unsigned?: boolean\n nullable?: boolean\n default?: unknown\n primary?: boolean\n unique?: boolean | string\n index?: boolean | string\n comment?: string\n after?: string\n first?: boolean\n onUpdate?: Expression\n}\n\n/** A column in a Blueprint, with Laravel's fluent modifiers: t.string('email').nullable().unique(). */\nexport class ColumnDefinition {\n constructor(readonly attributes: ColumnAttributes) {}\n\n get name(): string {\n return this.attributes.name\n }\n\n /** Allows NULL (the default is NOT NULL). */\n nullable(value = true): this {\n this.attributes.nullable = value\n return this\n }\n\n /** A default value. Strings, numbers and booleans are quoted as literals; DB.raw() passes through unescaped. */\n default(value: unknown): this {\n this.attributes.default = value\n return this\n }\n\n unsigned(): this {\n this.attributes.unsigned = true\n return this\n }\n\n autoIncrement(): this {\n this.attributes.autoIncrement = true\n return this\n }\n\n primary(value = true): this {\n this.attributes.primary = value\n return this\n }\n\n /** Adds a unique index on this column, optionally with a name. */\n unique(name?: string): this {\n this.attributes.unique = name ?? true\n return this\n }\n\n /** Adds a plain index on this column, optionally with a name. */\n index(name?: string): this {\n this.attributes.index = name ?? true\n return this\n }\n\n /** Column comment (MySQL and Postgres; ignored on SQLite). */\n comment(text: string): this {\n this.attributes.comment = text\n return this\n }\n\n /** MySQL only: place the column after another one. Ignored elsewhere. */\n after(column: string): this {\n this.attributes.after = column\n return this\n }\n\n /** MySQL only: place the column first. Ignored elsewhere. */\n first(): this {\n this.attributes.first = true\n return this\n }\n\n /** default CURRENT_TIMESTAMP. */\n useCurrent(): this {\n this.attributes.default = new Expression('CURRENT_TIMESTAMP')\n return this\n }\n\n /** MySQL only: on update CURRENT_TIMESTAMP. */\n useCurrentOnUpdate(): this {\n this.attributes.onUpdate = new Expression('CURRENT_TIMESTAMP')\n return this\n }\n}\n","import { Str } from '@orieljs/support'\nimport { ColumnDefinition, type ColumnAttributes } from './ColumnDefinition'\n\nexport type ReferentialAction = 'cascade' | 'restrict' | 'set null' | 'no action' | 'set default'\n\n/** t.foreign('user_id').references('id').on('users').cascadeOnDelete() */\nexport class ForeignKeyDefinition {\n referencedColumns: string[] = ['id']\n referencedTable: string | undefined\n deleteAction: ReferentialAction | undefined\n updateAction: ReferentialAction | undefined\n\n constructor(\n readonly columns: string[],\n public indexName: string,\n ) {}\n\n references(columns: string | string[]): this {\n this.referencedColumns = [columns].flat()\n return this\n }\n\n on(table: string): this {\n this.referencedTable = table\n return this\n }\n\n onDelete(action: ReferentialAction): this {\n this.deleteAction = action\n return this\n }\n\n onUpdate(action: ReferentialAction): this {\n this.updateAction = action\n return this\n }\n\n cascadeOnDelete(): this {\n return this.onDelete('cascade')\n }\n\n restrictOnDelete(): this {\n return this.onDelete('restrict')\n }\n\n nullOnDelete(): this {\n return this.onDelete('set null')\n }\n\n noActionOnDelete(): this {\n return this.onDelete('no action')\n }\n\n cascadeOnUpdate(): this {\n return this.onUpdate('cascade')\n }\n\n restrictOnUpdate(): this {\n return this.onUpdate('restrict')\n }\n\n nullOnUpdate(): this {\n return this.onUpdate('set null')\n }\n\n noActionOnUpdate(): this {\n return this.onUpdate('no action')\n }\n\n /** Overrides the constraint name (default: {table}_{columns}_foreign). */\n name(name: string): this {\n this.indexName = name\n return this\n }\n}\n\n/** foreignId('user_id').constrained(): the column plus, on demand, its foreign key. */\nexport class ForeignIdColumnDefinition extends ColumnDefinition {\n constructor(\n attributes: ColumnAttributes,\n private readonly addForeign: (column: string) => ForeignKeyDefinition,\n ) {\n super(attributes)\n }\n\n /**\n * A foreign key to `table` (default: the column name without `_id`, pluralized: user_id → users) on `column`.\n * Chain cascadeOnDelete() etc. on the returned definition.\n */\n constrained(table?: string, column = 'id', indexName?: string): ForeignKeyDefinition {\n const foreign = this.addForeign(this.name).references(column).on(table ?? Str.plural(this.name.replace(/_id$/, '')))\n if (indexName) foreign.name(indexName)\n return foreign\n }\n\n /** A foreign key on this column to `column`; chain on('table'). */\n references(column: string): ForeignKeyDefinition {\n return this.addForeign(this.name).references(column)\n }\n}\n","import { ColumnDefinition, type ColumnAttributes, type ColumnType } from './ColumnDefinition'\nimport { ForeignIdColumnDefinition, ForeignKeyDefinition } from './ForeignKeyDefinition'\n\nexport type IndexType = 'primary' | 'unique' | 'index'\n\nexport type BlueprintCommand =\n | { name: 'create' }\n | { name: IndexType; columns: string[]; index: string }\n | { name: 'foreign'; foreign: ForeignKeyDefinition }\n | { name: 'dropColumn'; columns: string[] }\n | { name: 'renameColumn'; from: string; to: string }\n | { name: 'dropPrimary' | 'dropUnique' | 'dropIndex' | 'dropForeign'; index: string }\n | { name: 'rename'; to: string }\n | { name: 'drop' | 'dropIfExists' }\n\n/**\n * The table definition passed to Schema.create()/Schema.table() callbacks, with Laravel's column types and\n * commands. It only records; the schema grammar turns it into DDL for one driver.\n */\nexport class Blueprint {\n readonly columns: ColumnDefinition[] = []\n readonly commands: BlueprintCommand[] = []\n\n constructor(\n readonly table: string,\n readonly creating = false,\n ) {\n if (creating) this.commands.push({ name: 'create' })\n }\n\n // ---------------------------------------------------------------- columns\n\n addColumn(type: ColumnType, name: string, attributes: Partial<ColumnAttributes> = {}): ColumnDefinition {\n const column = new ColumnDefinition({ type, name, ...attributes })\n this.columns.push(column)\n return column\n }\n\n /** An auto-incrementing unsigned big integer primary key (Laravel's id()). */\n id(column = 'id'): ColumnDefinition {\n return this.bigIncrements(column)\n }\n\n increments(column: string): ColumnDefinition {\n return this.addColumn('integer', column, { autoIncrement: true, unsigned: true })\n }\n\n bigIncrements(column: string): ColumnDefinition {\n return this.addColumn('bigInteger', column, { autoIncrement: true, unsigned: true })\n }\n\n integer(column: string, autoIncrement = false, unsigned = false): ColumnDefinition {\n return this.addColumn('integer', column, { autoIncrement, unsigned })\n }\n\n bigInteger(column: string, autoIncrement = false, unsigned = false): ColumnDefinition {\n return this.addColumn('bigInteger', column, { autoIncrement, unsigned })\n }\n\n mediumInteger(column: string, autoIncrement = false, unsigned = false): ColumnDefinition {\n return this.addColumn('mediumInteger', column, { autoIncrement, unsigned })\n }\n\n smallInteger(column: string, autoIncrement = false, unsigned = false): ColumnDefinition {\n return this.addColumn('smallInteger', column, { autoIncrement, unsigned })\n }\n\n tinyInteger(column: string, autoIncrement = false, unsigned = false): ColumnDefinition {\n return this.addColumn('tinyInteger', column, { autoIncrement, unsigned })\n }\n\n unsignedInteger(column: string): ColumnDefinition {\n return this.integer(column, false, true)\n }\n\n unsignedBigInteger(column: string): ColumnDefinition {\n return this.bigInteger(column, false, true)\n }\n\n unsignedSmallInteger(column: string): ColumnDefinition {\n return this.smallInteger(column, false, true)\n }\n\n unsignedTinyInteger(column: string): ColumnDefinition {\n return this.tinyInteger(column, false, true)\n }\n\n /** An unsigned big integer meant for a foreign key: t.foreignId('user_id').constrained().cascadeOnDelete(). */\n foreignId(column: string): ForeignIdColumnDefinition {\n const definition = new ForeignIdColumnDefinition({ type: 'bigInteger', name: column, unsigned: true }, (name) => this.foreign(name))\n this.columns.push(definition)\n return definition\n }\n\n string(column: string, length = 255): ColumnDefinition {\n return this.addColumn('string', column, { length })\n }\n\n char(column: string, length = 255): ColumnDefinition {\n return this.addColumn('char', column, { length })\n }\n\n text(column: string): ColumnDefinition {\n return this.addColumn('text', column)\n }\n\n mediumText(column: string): ColumnDefinition {\n return this.addColumn('mediumText', column)\n }\n\n longText(column: string): ColumnDefinition {\n return this.addColumn('longText', column)\n }\n\n boolean(column: string): ColumnDefinition {\n return this.addColumn('boolean', column)\n }\n\n date(column: string): ColumnDefinition {\n return this.addColumn('date', column)\n }\n\n dateTime(column: string, precision = 0): ColumnDefinition {\n return this.addColumn('dateTime', column, { precision })\n }\n\n time(column: string, precision = 0): ColumnDefinition {\n return this.addColumn('time', column, { precision })\n }\n\n timestamp(column: string, precision = 0): ColumnDefinition {\n return this.addColumn('timestamp', column, { precision })\n }\n\n /** Nullable created_at and updated_at. */\n timestamps(precision = 0): void {\n this.timestamp('created_at', precision).nullable()\n this.timestamp('updated_at', precision).nullable()\n }\n\n nullableTimestamps(precision = 0): void {\n this.timestamps(precision)\n }\n\n /** A nullable deleted_at timestamp for soft deletes. */\n softDeletes(column = 'deleted_at', precision = 0): ColumnDefinition {\n return this.timestamp(column, precision).nullable()\n }\n\n decimal(column: string, total = 8, places = 2): ColumnDefinition {\n return this.addColumn('decimal', column, { total, places })\n }\n\n float(column: string, precision = 53): ColumnDefinition {\n return this.addColumn('float', column, { precision })\n }\n\n double(column: string): ColumnDefinition {\n return this.addColumn('double', column)\n }\n\n json(column: string): ColumnDefinition {\n return this.addColumn('json', column)\n }\n\n jsonb(column: string): ColumnDefinition {\n return this.addColumn('jsonb', column)\n }\n\n uuid(column = 'uuid'): ColumnDefinition {\n return this.addColumn('uuid', column)\n }\n\n ulid(column = 'ulid'): ColumnDefinition {\n return this.addColumn('ulid', column)\n }\n\n binary(column: string): ColumnDefinition {\n return this.addColumn('binary', column)\n }\n\n enum(column: string, allowed: readonly string[]): ColumnDefinition {\n return this.addColumn('enum', column, { allowed })\n }\n\n /** remember_token varchar(100) null. */\n rememberToken(): ColumnDefinition {\n return this.string('remember_token', 100).nullable()\n }\n\n /** {name}_type + {name}_id, indexed together: the columns of a polymorphic relation. */\n morphs(name: string, indexName?: string): void {\n this.string(`${name}_type`)\n this.unsignedBigInteger(`${name}_id`)\n this.index([`${name}_type`, `${name}_id`], indexName)\n }\n\n nullableMorphs(name: string, indexName?: string): void {\n this.string(`${name}_type`).nullable()\n this.unsignedBigInteger(`${name}_id`).nullable()\n this.index([`${name}_type`, `${name}_id`], indexName)\n }\n\n // ---------------------------------------------------------------- indexes and keys\n\n primary(columns: string | string[], name?: string): void {\n this.indexCommand('primary', columns, name)\n }\n\n unique(columns: string | string[], name?: string): void {\n this.indexCommand('unique', columns, name)\n }\n\n index(columns: string | string[], name?: string): void {\n this.indexCommand('index', columns, name)\n }\n\n /** t.foreign('user_id').references('id').on('users') */\n foreign(columns: string | string[], name?: string): ForeignKeyDefinition {\n const list = [columns].flat()\n const foreign = new ForeignKeyDefinition(list, name ?? this.createIndexName('foreign', list))\n this.commands.push({ name: 'foreign', foreign })\n return foreign\n }\n\n // ---------------------------------------------------------------- changes to an existing table\n\n dropColumn(...columns: Array<string | string[]>): void {\n this.commands.push({ name: 'dropColumn', columns: columns.flat() })\n }\n\n renameColumn(from: string, to: string): void {\n this.commands.push({ name: 'renameColumn', from, to })\n }\n\n dropPrimary(name?: string): void {\n this.commands.push({ name: 'dropPrimary', index: name ?? `${this.table}_pkey` })\n }\n\n /** By name, or by columns (the conventional {table}_{columns}_unique name). */\n dropUnique(index: string | string[]): void {\n this.commands.push({ name: 'dropUnique', index: this.indexNameFor('unique', index) })\n }\n\n dropIndex(index: string | string[]): void {\n this.commands.push({ name: 'dropIndex', index: this.indexNameFor('index', index) })\n }\n\n dropForeign(index: string | string[]): void {\n this.commands.push({ name: 'dropForeign', index: this.indexNameFor('foreign', index) })\n }\n\n /** Drops the foreign key on the column, then the column. */\n dropConstrainedForeignId(column: string): void {\n this.dropForeign([column])\n this.dropColumn(column)\n }\n\n dropTimestamps(): void {\n this.dropColumn('created_at', 'updated_at')\n }\n\n dropSoftDeletes(column = 'deleted_at'): void {\n this.dropColumn(column)\n }\n\n dropRememberToken(): void {\n this.dropColumn('remember_token')\n }\n\n dropMorphs(name: string, indexName?: string): void {\n this.dropIndex(indexName ?? this.createIndexName('index', [`${name}_type`, `${name}_id`]))\n this.dropColumn(`${name}_type`, `${name}_id`)\n }\n\n rename(to: string): void {\n this.commands.push({ name: 'rename', to })\n }\n\n drop(): void {\n this.commands.push({ name: 'drop' })\n }\n\n dropIfExists(): void {\n this.commands.push({ name: 'dropIfExists' })\n }\n\n // ---------------------------------------------------------------- helpers\n\n /** Laravel's default index name: {table}_{columns}_{type}, lowercased, with - and . replaced by _. */\n createIndexName(type: IndexType | 'foreign', columns: string[]): string {\n return `${this.table}_${columns.join('_')}_${type}`.toLowerCase().replace(/[-.]/g, '_')\n }\n\n /** The index commands implied by column modifiers (t.string('email').unique()), in column order. */\n fluentIndexCommands(): BlueprintCommand[] {\n const commands: BlueprintCommand[] = []\n for (const column of this.columns) {\n for (const type of ['primary', 'unique', 'index'] as const) {\n const value = column.attributes[type]\n if (!value) continue\n const index = typeof value === 'string' ? value : this.createIndexName(type, [column.name])\n commands.push({ name: type, columns: [column.name], index })\n }\n }\n return commands\n }\n\n private indexCommand(type: IndexType, columns: string | string[], name?: string): void {\n const list = [columns].flat()\n this.commands.push({ name: type, columns: list, index: name ?? this.createIndexName(type, list) })\n }\n\n private indexNameFor(type: IndexType | 'foreign', index: string | string[]): string {\n return Array.isArray(index) ? this.createIndexName(type, index) : index\n }\n}\n","import { sql, type RawBuilder } from 'kysely'\nimport type { DriverName } from '@orieljs/contracts'\nimport type { ConnectionConfig } from '../Connectors/dialect'\nimport { LogicError } from '../errors'\nimport { Expression, rawWithBindings } from '../Query/Expression'\nimport type { Blueprint, BlueprintCommand } from './Blueprint'\nimport type { ColumnDefinition } from './ColumnDefinition'\nimport type { ForeignKeyDefinition } from './ForeignKeyDefinition'\n\ntype Sql = RawBuilder<unknown>\n\n/** One column of an existing table, as reported by Schema.getColumns(). */\nexport interface ColumnInfo {\n name: string\n /** The base type, lowercased: 'varchar', 'bigint', 'int8', 'tinyint', 'timestamp', … (driver-specific). */\n type_name: string\n /** The full type, lowercased: 'varchar(255)', 'tinyint(1)', 'timestamp(0) without time zone', … */\n type: string\n nullable: boolean\n default: string | null\n auto_increment: boolean\n}\n\nconst join = (parts: Sql[], separator = ', '): Sql => sql.join(parts, sql.raw(separator))\nconst columnList = (columns: readonly string[]): Sql => join(columns.map((column) => sql.id(column)))\n\n/**\n * Turns a Blueprint into DDL for one driver (Laravel's Schema\\Grammars). Identifiers go through sql.id();\n * default values and comments are quoted literals (sql.lit); only DB.raw() defaults are written as-is.\n */\nexport abstract class SchemaGrammar {\n abstract readonly driver: DriverName\n\n constructor(protected readonly config: Partial<ConnectionConfig> = {}) {}\n\n static for(driver: DriverName, config: Partial<ConnectionConfig> = {}): SchemaGrammar {\n if (driver === 'pgsql') return new PostgresSchemaGrammar(config)\n if (driver === 'mysql') return new MySqlSchemaGrammar(config)\n return new SqliteSchemaGrammar(config)\n }\n\n /** Every statement for the blueprint: create/add first, then commands in order, then indexes from column modifiers. */\n compile(blueprint: Blueprint): Sql[] {\n const statements: Sql[] = []\n const commands = [...blueprint.commands, ...blueprint.fluentIndexCommands()]\n const handled = new Set<BlueprintCommand>()\n if (blueprint.creating) {\n statements.push(this.compileCreate(blueprint, commands, handled))\n } else if (blueprint.columns.length) {\n statements.push(...this.compileAdd(blueprint, commands, handled))\n }\n for (const command of commands) {\n if (command.name === 'create' || handled.has(command)) continue\n statements.push(...this.compileCommand(blueprint, command))\n }\n if (blueprint.creating || blueprint.columns.length) statements.push(...this.compileComments(blueprint))\n return statements\n }\n\n protected compileCreate(blueprint: Blueprint, _commands: BlueprintCommand[], _handled: Set<BlueprintCommand>): Sql {\n return sql`create table ${sql.id(blueprint.table)} (${join(blueprint.columns.map((column) => this.columnDefinition(column)))})`\n }\n\n protected compileAdd(blueprint: Blueprint, _commands: BlueprintCommand[], _handled: Set<BlueprintCommand>): Sql[] {\n return blueprint.columns.map((column) => sql`alter table ${sql.id(blueprint.table)} add column ${this.columnDefinition(column)}`)\n }\n\n protected compileCommand(blueprint: Blueprint, command: BlueprintCommand): Sql[] {\n const table = sql.id(blueprint.table)\n switch (command.name) {\n case 'primary':\n return [sql`alter table ${table} add primary key (${columnList(command.columns)})`]\n case 'unique':\n return [this.compileUnique(blueprint, command.index, command.columns)]\n case 'index':\n return [this.compileIndex(blueprint, command.index, command.columns)]\n case 'foreign':\n return [sql`alter table ${table} add constraint ${sql.id(command.foreign.indexName)} ${this.foreignKeyClause(command.foreign)}`]\n case 'dropColumn':\n return command.columns.map((column) => sql`alter table ${table} drop column ${sql.id(column)}`)\n case 'renameColumn':\n return [sql`alter table ${table} rename column ${sql.id(command.from)} to ${sql.id(command.to)}`]\n case 'dropPrimary':\n return [this.compileDropPrimary(blueprint, command.index)]\n case 'dropUnique':\n return [this.compileDropUnique(blueprint, command.index)]\n case 'dropIndex':\n return [this.compileDropIndex(blueprint, command.index)]\n case 'dropForeign':\n return [this.compileDropForeign(blueprint, command.index)]\n case 'rename':\n return [this.compileRename(blueprint.table, command.to)]\n case 'drop':\n return [this.compileDrop(blueprint.table)]\n case 'dropIfExists':\n return [this.compileDropIfExists(blueprint.table)]\n case 'create':\n return []\n }\n }\n\n compileRename(from: string, to: string): Sql {\n return sql`alter table ${sql.id(from)} rename to ${sql.id(to)}`\n }\n\n compileDrop(table: string): Sql {\n return sql`drop table ${sql.id(table)}`\n }\n\n compileDropIfExists(table: string): Sql {\n return sql`drop table if exists ${sql.id(table)}`\n }\n\n protected compileUnique(blueprint: Blueprint, index: string, columns: string[]): Sql {\n return sql`alter table ${sql.id(blueprint.table)} add constraint ${sql.id(index)} unique (${columnList(columns)})`\n }\n\n protected compileIndex(blueprint: Blueprint, index: string, columns: string[]): Sql {\n return sql`create index ${sql.id(index)} on ${sql.id(blueprint.table)} (${columnList(columns)})`\n }\n\n protected compileDropPrimary(blueprint: Blueprint, index: string): Sql {\n return sql`alter table ${sql.id(blueprint.table)} drop constraint ${sql.id(index)}`\n }\n\n protected compileDropUnique(blueprint: Blueprint, index: string): Sql {\n return sql`alter table ${sql.id(blueprint.table)} drop constraint ${sql.id(index)}`\n }\n\n protected compileDropIndex(_blueprint: Blueprint, index: string): Sql {\n return sql`drop index ${sql.id(index)}`\n }\n\n protected compileDropForeign(blueprint: Blueprint, index: string): Sql {\n return sql`alter table ${sql.id(blueprint.table)} drop constraint ${sql.id(index)}`\n }\n\n protected compileComments(_blueprint: Blueprint): Sql[] {\n return []\n }\n\n /** `foreign key (\"user_id\") references \"users\" (\"id\") on delete cascade` */\n protected foreignKeyClause(foreign: ForeignKeyDefinition): Sql {\n return sql`foreign key (${columnList(foreign.columns)}) ${this.referencesClause(foreign)}`\n }\n\n /** `references \"users\" (\"id\") on delete cascade on update …` */\n protected referencesClause(foreign: ForeignKeyDefinition): Sql {\n if (!foreign.referencedTable) {\n throw new LogicError(`Foreign key [${foreign.indexName}] has no referenced table: call on('table') or constrained().`)\n }\n const parts: Sql[] = [sql`references ${sql.id(foreign.referencedTable)} (${columnList(foreign.referencedColumns)})`]\n if (foreign.deleteAction) parts.push(sql.raw(`on delete ${foreign.deleteAction}`))\n if (foreign.updateAction) parts.push(sql.raw(`on update ${foreign.updateAction}`))\n return join(parts, ' ')\n }\n\n /** `\"name\" type modifiers` */\n columnDefinition(column: ColumnDefinition): Sql {\n return join([sql`${sql.id(column.name)} ${this.type(column)}`, ...this.modifiers(column)], '')\n }\n\n protected abstract type(column: ColumnDefinition): Sql\n protected abstract modifiers(column: ColumnDefinition): Sql[]\n\n /** Laravel's getDefaultValue(): raw expressions as-is, booleans as '1'/'0', everything else as a quoted literal. */\n protected defaultValue(value: unknown): Sql {\n if (value instanceof Expression) return rawWithBindings(value.value, value.bindings)\n if (typeof value === 'boolean') return sql.lit(value ? '1' : '0')\n return sql.lit(String(value))\n }\n\n protected nullable(column: ColumnDefinition): Sql {\n return sql.raw(column.attributes.nullable ? ' null' : ' not null')\n }\n\n protected default(column: ColumnDefinition): Sql | undefined {\n const value = column.attributes.default\n return value === undefined || value === null ? undefined : sql` default ${this.defaultValue(value)}`\n }\n\n protected enumCheck(column: ColumnDefinition, type: string): Sql {\n const allowed = join((column.attributes.allowed ?? []).map((value) => sql.lit(value)))\n return sql`${sql.raw(type)} check (${sql.id(column.name)} in (${allowed}))`\n }\n\n // ---------------------------------------------------------------- introspection\n\n abstract compileTables(): Sql\n abstract compileColumns(table: string): Sql\n abstract normalizeColumns(rows: Array<Record<string, unknown>>, tableSql?: string): ColumnInfo[]\n abstract compileEnableForeignKeyConstraints(): Sql\n abstract compileDisableForeignKeyConstraints(): Sql\n}\n\nconst present = (parts: Array<Sql | undefined>): Sql[] => parts.filter((part): part is Sql => part !== undefined)\n\nexport class SqliteSchemaGrammar extends SchemaGrammar {\n readonly driver = 'sqlite' as const\n\n /** SQLite can't add keys to an existing table, so primary and foreign keys go inside create table. */\n protected override compileCreate(blueprint: Blueprint, commands: BlueprintCommand[], handled: Set<BlueprintCommand>): Sql {\n const parts = blueprint.columns.map((column) => this.columnDefinition(column))\n for (const command of commands) {\n if (command.name === 'primary') {\n parts.push(sql`primary key (${columnList(command.columns)})`)\n handled.add(command)\n } else if (command.name === 'foreign') {\n parts.push(this.foreignKeyClause(command.foreign))\n handled.add(command)\n }\n }\n return sql`create table ${sql.id(blueprint.table)} (${join(parts)})`\n }\n\n /** New columns may carry an inline `references` clause (the only foreign key SQLite can add later). */\n protected override compileAdd(blueprint: Blueprint, commands: BlueprintCommand[], handled: Set<BlueprintCommand>): Sql[] {\n return blueprint.columns.map((column) => {\n const foreign = commands.find(\n (command): command is Extract<BlueprintCommand, { name: 'foreign' }> =>\n command.name === 'foreign' && command.foreign.columns.length === 1 && command.foreign.columns[0] === column.name,\n )\n let definition = this.columnDefinition(column)\n if (foreign) {\n definition = sql`${definition} ${this.referencesClause(foreign.foreign)}`\n handled.add(foreign)\n }\n return sql`alter table ${sql.id(blueprint.table)} add column ${definition}`\n })\n }\n\n protected override compileCommand(blueprint: Blueprint, command: BlueprintCommand): Sql[] {\n const unsupported: Partial<Record<BlueprintCommand['name'], string>> = {\n primary: 'adding a primary key to an existing table',\n foreign: 'adding a foreign key to an existing column',\n dropPrimary: 'dropping a primary key',\n dropForeign: 'dropping a foreign key',\n }\n const action = unsupported[command.name]\n if (action) throw new LogicError(`SQLite doesn't support ${action}. Recreate the table instead.`)\n return super.compileCommand(blueprint, command)\n }\n\n protected override compileUnique(blueprint: Blueprint, index: string, columns: string[]): Sql {\n return sql`create unique index ${sql.id(index)} on ${sql.id(blueprint.table)} (${columnList(columns)})`\n }\n\n protected override compileDropUnique(_blueprint: Blueprint, index: string): Sql {\n return sql`drop index ${sql.id(index)}`\n }\n\n protected type(column: ColumnDefinition): Sql {\n const { type } = column.attributes\n switch (type) {\n case 'bigInteger': case 'integer': case 'mediumInteger': case 'smallInteger': case 'tinyInteger':\n return sql.raw('integer')\n case 'string': case 'char': case 'uuid': case 'ulid':\n return sql.raw('varchar')\n case 'text': case 'mediumText': case 'longText': case 'json': case 'jsonb':\n return sql.raw('text')\n case 'boolean':\n return sql.raw('tinyint(1)')\n case 'date':\n return sql.raw('date')\n case 'dateTime': case 'timestamp':\n return sql.raw('datetime')\n case 'time':\n return sql.raw('time')\n case 'decimal':\n return sql.raw('numeric')\n case 'float':\n return sql.raw('float')\n case 'double':\n return sql.raw('double')\n case 'binary':\n return sql.raw('blob')\n case 'enum':\n return this.enumCheck(column, 'varchar')\n }\n }\n\n protected modifiers(column: ColumnDefinition): Sql[] {\n const increment = column.attributes.autoIncrement ? sql.raw(' primary key autoincrement') : undefined\n return present([increment, column.attributes.nullable ? undefined : sql.raw(' not null'), this.default(column)])\n }\n\n compileTables(): Sql {\n return sql`select name from sqlite_master where type = 'table' and name not like 'sqlite_%' order by name`\n }\n\n compileColumns(table: string): Sql {\n return sql`select name, type, \"notnull\", dflt_value, pk, (select sql from sqlite_master where type = 'table' and name = ${table}) as table_sql from pragma_table_info(${table}) order by cid`\n }\n\n normalizeColumns(rows: Array<Record<string, unknown>>): ColumnInfo[] {\n return rows.map((row) => {\n const type = String(row.type).toLowerCase()\n const autoIncrement = Number(row.pk) === 1 && type === 'integer' && /autoincrement/i.test(String(row.table_sql ?? ''))\n return {\n name: String(row.name),\n type_name: type.replace(/\\(.*$/, '').trim(),\n type,\n nullable: Number(row.notnull) === 0 && !autoIncrement,\n default: row.dflt_value === null || row.dflt_value === undefined ? null : String(row.dflt_value),\n auto_increment: autoIncrement,\n }\n })\n }\n\n compileEnableForeignKeyConstraints(): Sql {\n return sql.raw('PRAGMA foreign_keys = ON')\n }\n\n compileDisableForeignKeyConstraints(): Sql {\n return sql.raw('PRAGMA foreign_keys = OFF')\n }\n}\n\nexport class PostgresSchemaGrammar extends SchemaGrammar {\n readonly driver = 'pgsql' as const\n\n protected override compileComments(blueprint: Blueprint): Sql[] {\n return blueprint.columns\n .filter((column) => column.attributes.comment !== undefined)\n .map((column) => sql`comment on column ${sql.id(blueprint.table, column.name)} is ${sql.lit(column.attributes.comment!)}`)\n }\n\n protected type(column: ColumnDefinition): Sql {\n const { type, autoIncrement, length, total, places, precision } = column.attributes\n switch (type) {\n case 'bigInteger':\n return sql.raw(autoIncrement ? 'bigserial' : 'bigint')\n case 'integer': case 'mediumInteger':\n return sql.raw(autoIncrement ? 'serial' : 'integer')\n case 'smallInteger': case 'tinyInteger':\n return sql.raw(autoIncrement ? 'smallserial' : 'smallint')\n case 'string':\n return sql.raw(`varchar(${length ?? 255})`)\n case 'char':\n return sql.raw(`char(${length ?? 255})`)\n case 'text': case 'mediumText': case 'longText':\n return sql.raw('text')\n case 'boolean':\n return sql.raw('boolean')\n case 'date':\n return sql.raw('date')\n case 'dateTime': case 'timestamp':\n return sql.raw(`timestamp(${precision ?? 0}) without time zone`)\n case 'time':\n return sql.raw(`time(${precision ?? 0}) without time zone`)\n case 'decimal':\n return sql.raw(`decimal(${total ?? 8}, ${places ?? 2})`)\n case 'float':\n return sql.raw(precision ? `float(${precision})` : 'real')\n case 'double':\n return sql.raw('double precision')\n case 'json':\n return sql.raw('json')\n case 'jsonb':\n return sql.raw('jsonb')\n case 'uuid':\n return sql.raw('uuid')\n case 'ulid':\n return sql.raw('char(26)')\n case 'binary':\n return sql.raw('bytea')\n case 'enum':\n return this.enumCheck(column, 'varchar(255)')\n }\n }\n\n protected modifiers(column: ColumnDefinition): Sql[] {\n return present([this.nullable(column), this.default(column), column.attributes.autoIncrement ? sql.raw(' primary key') : undefined])\n }\n\n compileTables(): Sql {\n return sql`select tablename as name from pg_tables where schemaname = current_schema() order by tablename`\n }\n\n compileColumns(table: string): Sql {\n return sql`select a.attname as name, t.typname as type_name, format_type(a.atttypid, a.atttypmod) as type, not a.attnotnull as nullable, pg_get_expr(d.adbin, d.adrelid) as ${sql.id('default')}\n from pg_attribute a\n join pg_class c on c.oid = a.attrelid\n join pg_namespace n on n.oid = c.relnamespace\n join pg_type t on t.oid = a.atttypid\n left join pg_attrdef d on d.adrelid = a.attrelid and d.adnum = a.attnum\n where c.relname = ${table} and n.nspname = current_schema() and a.attnum > 0 and not a.attisdropped\n order by a.attnum`\n }\n\n normalizeColumns(rows: Array<Record<string, unknown>>): ColumnInfo[] {\n return rows.map((row) => {\n const defaultValue = row.default === null || row.default === undefined ? null : String(row.default)\n return {\n name: String(row.name),\n type_name: String(row.type_name).toLowerCase(),\n type: String(row.type).toLowerCase(),\n nullable: row.nullable === true,\n default: defaultValue,\n auto_increment: defaultValue !== null && defaultValue.startsWith('nextval('),\n }\n })\n }\n\n compileEnableForeignKeyConstraints(): Sql {\n return sql.raw('SET CONSTRAINTS ALL IMMEDIATE')\n }\n\n compileDisableForeignKeyConstraints(): Sql {\n return sql.raw('SET CONSTRAINTS ALL DEFERRED')\n }\n}\n\nexport class MySqlSchemaGrammar extends SchemaGrammar {\n readonly driver = 'mysql' as const\n\n protected override compileCreate(blueprint: Blueprint, commands: BlueprintCommand[], handled: Set<BlueprintCommand>): Sql {\n const charset = this.config.charset ?? 'utf8mb4'\n const collation = this.config.collation ?? 'utf8mb4_unicode_ci'\n return sql`${super.compileCreate(blueprint, commands, handled)} default character set ${sql.raw(charset.replace(/[^\\w]/g, ''))} collate ${sql.lit(collation)}`\n }\n\n protected override compileAdd(blueprint: Blueprint): Sql[] {\n return blueprint.columns.map((column) => sql`alter table ${sql.id(blueprint.table)} add ${this.columnDefinition(column)}`)\n }\n\n protected override compileUnique(blueprint: Blueprint, index: string, columns: string[]): Sql {\n return sql`alter table ${sql.id(blueprint.table)} add unique ${sql.id(index)}(${columnList(columns)})`\n }\n\n protected override compileIndex(blueprint: Blueprint, index: string, columns: string[]): Sql {\n return sql`alter table ${sql.id(blueprint.table)} add index ${sql.id(index)}(${columnList(columns)})`\n }\n\n protected override compileDropPrimary(blueprint: Blueprint): Sql {\n return sql`alter table ${sql.id(blueprint.table)} drop primary key`\n }\n\n protected override compileDropUnique(blueprint: Blueprint, index: string): Sql {\n return sql`alter table ${sql.id(blueprint.table)} drop index ${sql.id(index)}`\n }\n\n protected override compileDropIndex(blueprint: Blueprint, index: string): Sql {\n return sql`alter table ${sql.id(blueprint.table)} drop index ${sql.id(index)}`\n }\n\n protected override compileDropForeign(blueprint: Blueprint, index: string): Sql {\n return sql`alter table ${sql.id(blueprint.table)} drop foreign key ${sql.id(index)}`\n }\n\n protected type(column: ColumnDefinition): Sql {\n const { type, length, total, places, precision, allowed } = column.attributes\n switch (type) {\n case 'bigInteger':\n return sql.raw('bigint')\n case 'integer':\n return sql.raw('int')\n case 'mediumInteger':\n return sql.raw('mediumint')\n case 'smallInteger':\n return sql.raw('smallint')\n case 'tinyInteger':\n return sql.raw('tinyint')\n case 'string':\n return sql.raw(`varchar(${length ?? 255})`)\n case 'char':\n return sql.raw(`char(${length ?? 255})`)\n case 'text':\n return sql.raw('text')\n case 'mediumText':\n return sql.raw('mediumtext')\n case 'longText':\n return sql.raw('longtext')\n case 'boolean':\n return sql.raw('tinyint(1)')\n case 'date':\n return sql.raw('date')\n case 'dateTime':\n return sql.raw(precision ? `datetime(${precision})` : 'datetime')\n case 'timestamp':\n return sql.raw(precision ? `timestamp(${precision})` : 'timestamp')\n case 'time':\n return sql.raw(precision ? `time(${precision})` : 'time')\n case 'decimal':\n return sql.raw(`decimal(${total ?? 8}, ${places ?? 2})`)\n case 'float':\n return sql.raw(precision ? `float(${precision})` : 'float')\n case 'double':\n return sql.raw('double')\n case 'json': case 'jsonb':\n return sql.raw('json')\n case 'uuid':\n return sql.raw('char(36)')\n case 'ulid':\n return sql.raw('char(26)')\n case 'binary':\n return sql.raw('blob')\n case 'enum':\n return sql`enum(${join((allowed ?? []).map((value) => sql.lit(value)))})`\n }\n }\n\n protected modifiers(column: ColumnDefinition): Sql[] {\n const { unsigned, autoIncrement, onUpdate, comment, after, first } = column.attributes\n return present([\n unsigned ? sql.raw(' unsigned') : undefined,\n this.nullable(column),\n this.default(column),\n onUpdate ? sql` on update ${this.defaultValue(onUpdate)}` : undefined,\n autoIncrement ? sql.raw(' auto_increment primary key') : undefined,\n comment === undefined ? undefined : sql` comment ${sql.lit(comment)}`,\n after === undefined ? undefined : sql` after ${sql.id(after)}`,\n first ? sql.raw(' first') : undefined,\n ])\n }\n\n compileTables(): Sql {\n return sql`select table_name as name from information_schema.tables where table_schema = database() and table_type = 'BASE TABLE' order by table_name`\n }\n\n compileColumns(table: string): Sql {\n return sql`select column_name as name, data_type as type_name, column_type as type, is_nullable = 'YES' as nullable, column_default as ${sql.id('default')}, extra like '%auto_increment%' as auto_increment\n from information_schema.columns where table_schema = database() and table_name = ${table} order by ordinal_position`\n }\n\n normalizeColumns(rows: Array<Record<string, unknown>>): ColumnInfo[] {\n return rows.map((row) => ({\n name: String(row.name),\n type_name: String(row.type_name).toLowerCase(),\n type: String(row.type).toLowerCase(),\n nullable: Number(row.nullable) === 1,\n default: row.default === null || row.default === undefined ? null : String(row.default),\n auto_increment: Number(row.auto_increment) === 1,\n }))\n }\n\n compileEnableForeignKeyConstraints(): Sql {\n return sql.raw('SET FOREIGN_KEY_CHECKS=1')\n }\n\n compileDisableForeignKeyConstraints(): Sql {\n return sql.raw('SET FOREIGN_KEY_CHECKS=0')\n }\n}\n","import type { DatabaseManager as DatabaseManagerContract, DriverName, Row } from '@orieljs/contracts'\nimport type { ConnectionConfig } from './Connectors/dialect'\nimport { Connection, type LoggedQuery } from './Connection'\nimport { DatabaseConfigError } from './errors'\nimport type { Builder } from './Query/Builder'\nimport { Expression } from './Query/Expression'\nimport { SchemaBuilder } from './Schema/Builder'\n\n/** `config('database')`, in Laravel's config/database.php shape. */\nexport interface DatabaseConfig {\n default: string\n connections: Record<string, ConnectionConfig>\n /** Laravel 11: { table: 'migrations' }. A plain string (older Laravel) is accepted too. */\n migrations?: { table?: string } | string\n}\n\n/**\n * The DatabaseManager contract: named connections from config('database'), created on first use and cached.\n * Everything a connection does is also available here and runs on the default connection, as with Laravel's DB facade.\n * Named DatabaseManagerImpl so it never shadows the DatabaseManager token when both are re-exported.\n */\nexport class DatabaseManagerImpl implements DatabaseManagerContract {\n private readonly connections = new Map<string, Connection>()\n private defaultName: string | undefined\n\n /** Pass the config, or a function that reads it (the provider reads config('database') lazily). */\n constructor(private readonly config: DatabaseConfig | (() => DatabaseConfig)) {}\n\n private settings(): DatabaseConfig {\n return typeof this.config === 'function' ? this.config() : this.config\n }\n\n /** A connection by name (default: config('database.default')). */\n connection(name?: string): Connection {\n const key = name ?? this.getDefaultConnection()\n let connection = this.connections.get(key)\n if (!connection) {\n const config = this.settings().connections[key]\n if (!config) throw new DatabaseConfigError(`Database connection [${key}] not configured.`)\n connection = new Connection(key, config)\n this.connections.set(key, connection)\n }\n return connection\n }\n\n getDefaultConnection(): string {\n return this.defaultName ?? this.settings().default\n }\n\n /** Overrides config('database.default'); undefined clears the override. */\n setDefaultConnection(name: string | undefined): void {\n this.defaultName = name\n }\n\n /**\n * Runs `callback` with `name` as the default connection (Laravel's usingConnection()), then restores the previous\n * override, or none, so the default follows config('database.default') again. Without a name, just runs it.\n */\n async usingConnection<T>(name: string | undefined, callback: () => Promise<T>): Promise<T> {\n if (!name) return callback()\n const previous = this.defaultName\n this.defaultName = name\n try {\n return await callback()\n } finally {\n this.defaultName = previous\n }\n }\n\n /** The connections opened so far. */\n getConnections(): Record<string, Connection> {\n return Object.fromEntries(this.connections)\n }\n\n /** The migrations table name (config('database.migrations.table'), default 'migrations'). */\n migrationsTable(): string {\n const migrations = this.settings().migrations\n return (typeof migrations === 'string' ? migrations : migrations?.table) ?? 'migrations'\n }\n\n /** Closes a connection's pool and forgets it; the next connection(name) opens a new one. */\n async disconnect(name?: string): Promise<void> {\n const key = name ?? this.getDefaultConnection()\n const connection = this.connections.get(key)\n this.connections.delete(key)\n await connection?.disconnect()\n }\n\n /** Laravel's purge(): the same as disconnect() here. */\n purge(name?: string): Promise<void> {\n return this.disconnect(name)\n }\n\n /** Closes every open connection (app shutdown, the end of a test). */\n async disconnectAll(): Promise<void> {\n const open = [...this.connections.values()]\n this.connections.clear()\n await Promise.all(open.map((connection) => connection.disconnect()))\n }\n\n /** The default connection's schema builder; Schema.connection(name) switches connections through this manager. */\n getSchemaBuilder(): SchemaBuilder {\n return new SchemaBuilder(this.connection(), (name) => this.connection(name))\n }\n\n /** A raw SQL fragment: DB.raw('count(*) as total'). */\n raw(value: string, bindings: readonly unknown[] = []): Expression {\n return new Expression(value, bindings)\n }\n\n // ---------------------------------------------------------------- the default connection\n\n getName(): string {\n return this.connection().getName()\n }\n\n getDriverName(): DriverName {\n return this.connection().getDriverName()\n }\n\n kysely(): ReturnType<Connection['kysely']> {\n return this.connection().kysely()\n }\n\n table<T = Row>(table: string | Expression): Builder<T> {\n return this.connection().table<T>(table)\n }\n\n query<T = Row>(): Builder<T> {\n return this.connection().query<T>()\n }\n\n select<T = Row>(query: string, bindings?: readonly unknown[]): Promise<T[]> {\n return this.connection().select<T>(query, bindings)\n }\n\n /** The first row of a raw select, or undefined. */\n async selectOne<T = Row>(query: string, bindings?: readonly unknown[]): Promise<T | undefined> {\n return (await this.connection().select<T>(query, bindings))[0]\n }\n\n /** Raw insert. Returns true, like Laravel's DB::insert(). */\n async insert(query: string, bindings?: readonly unknown[]): Promise<boolean> {\n await this.connection().statement(query, bindings)\n return true\n }\n\n /** Raw update; returns the number of affected rows. */\n update(query: string, bindings?: readonly unknown[]): Promise<number> {\n return this.connection().affectingStatement(query, bindings)\n }\n\n /** Raw delete; returns the number of affected rows. */\n delete(query: string, bindings?: readonly unknown[]): Promise<number> {\n return this.connection().affectingStatement(query, bindings)\n }\n\n statement(query: string, bindings?: readonly unknown[]): Promise<void> {\n return this.connection().statement(query, bindings)\n }\n\n affectingStatement(query: string, bindings?: readonly unknown[]): Promise<number> {\n return this.connection().affectingStatement(query, bindings)\n }\n\n transaction<R>(fn: (connection: Connection) => Promise<R>): Promise<R> {\n return this.connection().transaction(fn)\n }\n\n beginTransaction(): Promise<void> {\n return this.connection().beginTransaction()\n }\n\n commit(): Promise<void> {\n return this.connection().commit()\n }\n\n rollBack(): Promise<void> {\n return this.connection().rollBack()\n }\n\n transactionLevel(): number {\n return this.connection().transactionLevel()\n }\n\n enableQueryLog(): void {\n this.connection().enableQueryLog()\n }\n\n disableQueryLog(): void {\n this.connection().disableQueryLog()\n }\n\n getQueryLog(): LoggedQuery[] {\n return this.connection().getQueryLog()\n }\n\n flushQueryLog(): void {\n this.connection().flushQueryLog()\n }\n}\n","import { DatabaseManager, token, type Token } from '@orieljs/contracts'\nimport { facade } from '@orieljs/support'\nimport type { DatabaseManagerImpl } from './DatabaseManager'\nimport { raw } from './Query/Expression'\nimport type { SchemaBuilder } from './Schema/Builder'\n\n/**\n * The DB facade: DB.table('users').get(), DB.transaction(fn), DB.connection('pgsql'), DB.kysely().\n * DB.raw() works without an application (it only builds an Expression).\n */\nexport const DB = facade(DatabaseManager as unknown as Token<DatabaseManagerImpl>, { raw } as { raw: typeof raw })\n\n/** The Schema facade's binding: the default connection's SchemaBuilder (DatabaseServiceProvider binds it). */\nexport const SchemaBuilderToken = token<SchemaBuilder>('Database.SchemaBuilder')\n\n/** The Schema facade: Schema.create('posts', (t) => { … }), Schema.table(…), Schema.dropIfExists(…). */\nexport const Schema = facade(SchemaBuilderToken)\n","import { AsyncLocalStorage } from 'node:async_hooks'\nimport { DatabaseManager, type ModelInstance, type Row } from '@orieljs/contracts'\nimport { Collection, type LazyCollection } from '@orieljs/collections'\nimport { currentContainer, inject } from '@orieljs/container'\nimport { Str } from '@orieljs/support'\nimport { Connection } from '../Connection'\nimport { DatabaseConfigError, LogicError, MassAssignmentError, RelationNotFoundError, RelationNotLoadedError } from '../errors'\nimport type { CursorPaginator, Cursor } from '../Pagination/CursorPaginator'\nimport type { LengthAwarePaginator } from '../Pagination/LengthAwarePaginator'\nimport type { Paginator } from '../Pagination/Paginator'\nimport type { Direction } from '../Query/Builder'\nimport type { Expression } from '../Query/Expression'\nimport { Builder, type EagerLoadSpec, type RelationConstraint } from './Builder'\nimport { castGet, castSet, isEquivalent, isJsonCast, type CastDefinition } from './casts'\nimport { Factory, type Many, type State } from './Factories/Factory'\nimport {\n eventDispatcher, MODEL_EVENTS, modelEventName, modelEventsMuted, requireEventDispatcher, withoutModelEvents,\n type ModelEvent, type ModelListener,\n} from './events'\nimport { BelongsTo } from './Relations/BelongsTo'\nimport { BelongsToMany } from './Relations/BelongsToMany'\nimport { HasMany } from './Relations/HasMany'\nimport { HasManyThrough } from './Relations/HasManyThrough'\nimport { HasOne } from './Relations/HasOne'\nimport { MorphMany } from './Relations/MorphMany'\nimport { MorphOne } from './Relations/MorphOne'\nimport { MorphTo } from './Relations/MorphTo'\nimport { getMorphAlias, rememberModelClass, resolveMorphClass, setModelBaseClass } from './Relations/morphMap'\nimport { Relation } from './Relations/Relation'\nimport type { GlobalScope, Scope, ScopeCallback } from './Scope'\nimport { SoftDeletingScope } from './SoftDeletingScope'\nimport type { Column, ModelBuilder, RelationNames, RelationValue, Scopes, WhereArgs } from './types'\n\ntype AnyFunction = (...args: unknown[]) => unknown\n\n/**\n * Every model instance is a Proxy. Real members (fields, methods, getters, config such as `fillable`) are read and\n * written normally; any other property is an attribute: `post.title` → getAttribute('title') (accessors, casts),\n * `post.title = 'x'` → setAttribute('title', 'x') (mutators, casts).\n */\nconst handler: ProxyHandler<Model> = {\n get(target, key, receiver) {\n if (typeof key === 'symbol' || key in target) return Reflect.get(target, key, receiver)\n return (receiver as Model).getAttribute(key)\n },\n set(target, key, value, receiver) {\n if (typeof key === 'symbol' || key in target) return Reflect.set(target, key, value, receiver)\n ;(receiver as Model).setAttribute(key, value)\n return true\n },\n}\n\nconst bootedModels = new Set<typeof Model>()\nconst prototypes = new Map<typeof Model, Model>()\nconst unguardedGlobally = { value: false }\n/** Model classes whose default withCount is being added (breaks recursion through their relations). */\nconst addingDefaultCounts = new Set<typeof Model>()\n/** The only keys a guarded-list model accepts from fill(): a plain column name, no spaces, dots or quoting tricks. */\nconst PLAIN_COLUMN = /^[A-Za-z_][A-Za-z0-9_]*$/\nconst unguardedScope = new AsyncLocalStorage<boolean>()\nconst globalScopes = new Map<typeof Model, Map<string, GlobalScope>>()\nlet anonymousScopes = 0\n\ntype Instance<C extends typeof Model> = InstanceType<C>\ntype ScopeClass = abstract new (...args: never[]) => unknown\n\n/** Post.published() for every static scopePublished() (installed when the class boots). */\nfunction installScopeProxies(cls: typeof Model): void {\n for (let current: unknown = cls; current && current !== Model; current = Object.getPrototypeOf(current)) {\n for (const key of Object.getOwnPropertyNames(current)) {\n if (!key.startsWith('scope') || key.length <= 5) continue\n if (typeof Reflect.get(current as object, key) !== 'function') continue\n const name = Str.lcfirst(key.slice(5))\n if (name in cls) continue\n Object.defineProperty(cls, name, {\n configurable: true,\n writable: true,\n value(this: typeof Model, ...args: unknown[]) {\n const query = this.query() as unknown as Record<string, (...a: unknown[]) => unknown>\n return query[name]!(...args)\n },\n })\n }\n }\n}\n\n/** A method defined on the model's class (never an attribute), e.g. getFullNameAttribute. */\nfunction methodOf(model: Model, name: string): AnyFunction | undefined {\n const value: unknown = Reflect.get(Object.getPrototypeOf(model) as object, name)\n return typeof value === 'function' ? (value as AnyFunction) : undefined\n}\n\n/** Laravel's date serialization: ISO 8601 in UTC with microseconds (2026-01-02T03:04:05.000000Z). */\nexport function serializeDate(date: Date): string {\n return date.toISOString().replace(/\\.(\\d{3})Z$/, '.$1000Z')\n}\n\n/**\n * Eloquent's Model: an Active Record over one table.\n *\n * Config lives in instance fields, as in Laravel: `protected fillable = ['title']`, `protected casts = {…}`,\n * `protected hidden = ['password']`, `protected table = 'posts'`. Attribute columns are never declared as class\n * fields (they would shadow the Proxy); their types come from `oriel model:types`, or from `declare title: string`.\n * `new Post()` takes no arguments: use Post.make(attrs), Post.create(attrs) or new Post().fill(attrs).\n */\nexport class Model implements ModelInstance {\n static CREATED_AT: string | null = 'created_at'\n static UPDATED_AT: string | null = 'updated_at'\n static DELETED_AT = 'deleted_at'\n\n // ---------------------------------------------------------------- config (override in subclasses)\n\n /** The table (default: the snake_case plural of the class name: BlogPost → blog_posts). */\n protected table: string | undefined = undefined\n protected primaryKey = 'id'\n protected keyType: 'int' | 'string' = 'int'\n incrementing = true\n /** Attributes that fill()/create() may set. */\n protected fillable: string[] = []\n /** Attributes fill() never sets. ['*'] (the default) guards everything that isn't fillable. */\n protected guarded: string[] = ['*']\n protected casts: Readonly<Record<string, CastDefinition>> = {}\n /** Left out of toArray()/toJSON(). */\n protected hidden: string[] = []\n /** When non-empty, only these are in toArray()/toJSON(). */\n protected visible: string[] = []\n /** Accessor-only attributes added to toArray()/toJSON(). */\n protected appends: string[] = []\n timestamps = true\n /** Turns on soft deletes (Laravel's `use SoftDeletes`): deleted_at instead of a real delete. */\n protected softDeletes = false\n /** The connection name (default: config('database.default')). */\n protected connection: string | undefined = undefined\n protected perPage = 15\n /** Relations every query of this model eager loads (Laravel's $with). */\n protected with: string[] = []\n /** Relation counts every query of this model adds (Laravel's $withCount). */\n protected withCount: string[] = []\n\n // ---------------------------------------------------------------- state\n\n exists = false\n wasRecentlyCreated = false\n protected forceDeleting = false\n protected attributes: Row = {}\n protected original: Row = {}\n protected changes: Row = {}\n protected relations: Record<string, unknown> = {}\n /** Decoded json/array/object/collection values, so in-place changes are seen by save(). */\n protected castCache = new Map<string, { raw: unknown; value: unknown }>()\n\n constructor() {\n ;(this.constructor as typeof Model).bootIfNotBooted()\n return new Proxy(this, handler)\n }\n\n // ---------------------------------------------------------------- booting\n\n /** Runs booting()/booted() once per class, the first time the class is instantiated. */\n static bootIfNotBooted(): void {\n if (bootedModels.has(this)) return\n bootedModels.add(this)\n rememberModelClass(this)\n this.booting()\n this.boot()\n this.booted()\n }\n\n /**\n * Framework hook: installs the static scope proxies (Post.published()) and, with `softDeletes = true`, the soft\n * delete scope. Overrides must call super.boot().\n */\n static boot(): void {\n installScopeProxies(this)\n if (this.prototypeInstance().usesSoftDeletes()) this.addGlobalScope(new SoftDeletingScope())\n }\n\n /** Runs before boot(). */\n static booting(): void {}\n\n /** Register global scopes and model event listeners here: static booted() { this.addGlobalScope(…) }. */\n static booted(): void {}\n\n /**\n * Forgets which classes are booted, and their global scopes (Laravel's clearBootedModels()), so the next use boots\n * them again: booted() re-registers its scopes and event listeners against the current application. Every new\n * application does this (DatabaseServiceProvider.register()).\n */\n static clearBootedModels(): void {\n bootedModels.clear()\n prototypes.clear()\n globalScopes.clear()\n }\n\n /** One cached instance per class, used by static methods to read config (table, key, casts, …). */\n static prototypeInstance<M extends Model>(this: new () => M): M {\n const cls = this as unknown as typeof Model\n let instance = prototypes.get(cls)\n if (!instance) {\n instance = new cls()\n prototypes.set(cls, instance)\n }\n return instance as M\n }\n\n /** A new, unsaved model filled with attributes (mass assignment rules apply). */\n static make<M extends Model>(this: new () => M, attributes: Row = {}): M {\n return new this().fill(attributes)\n }\n\n // ---------------------------------------------------------------- global scopes\n\n /**\n * Adds a global scope to every query of this class: addGlobalScope('published', q => …),\n * addGlobalScope(new ActiveScope()) (named after its class) or addGlobalScope(q => …).\n */\n static addGlobalScope(scope: Scope | ScopeCallback): string\n static addGlobalScope(name: string, scope: GlobalScope): string\n static addGlobalScope(nameOrScope: string | GlobalScope, implementation?: GlobalScope): string {\n let name: string\n let scope: GlobalScope\n if (typeof nameOrScope === 'string') {\n name = nameOrScope\n scope = implementation!\n } else {\n scope = nameOrScope\n name = typeof scope === 'function' ? `closure#${++anonymousScopes}` : scope.constructor.name\n }\n let scopes = globalScopes.get(this)\n if (!scopes) globalScopes.set(this, (scopes = new Map()))\n scopes.set(name, scope)\n return name\n }\n\n static hasGlobalScope(scope: string | ScopeClass): boolean {\n return globalScopes.get(this)?.has(typeof scope === 'string' ? scope : scope.name) ?? false\n }\n\n static getGlobalScopes(): Map<string, GlobalScope> {\n return new Map(globalScopes.get(this))\n }\n\n // ---------------------------------------------------------------- model events and observers\n\n /** Registers a listener for one of this model's events ('eloquent.<event>: <Class>'). Needs an EventDispatcher. */\n static registerModelEvent<C extends typeof Model>(this: C, event: ModelEvent, callback: ModelListener<InstanceType<C>>): void {\n requireEventDispatcher(this.name).listen(modelEventName(event, this.name), (model: unknown) => callback(model as InstanceType<C>))\n }\n\n static retrieved<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void {\n this.registerModelEvent('retrieved', callback)\n }\n\n static creating<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void {\n this.registerModelEvent('creating', callback)\n }\n\n static created<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void {\n this.registerModelEvent('created', callback)\n }\n\n static updating<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void {\n this.registerModelEvent('updating', callback)\n }\n\n static updated<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void {\n this.registerModelEvent('updated', callback)\n }\n\n static saving<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void {\n this.registerModelEvent('saving', callback)\n }\n\n static saved<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void {\n this.registerModelEvent('saved', callback)\n }\n\n static deleting<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void {\n this.registerModelEvent('deleting', callback)\n }\n\n static deleted<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void {\n this.registerModelEvent('deleted', callback)\n }\n\n static restoring<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void {\n this.registerModelEvent('restoring', callback)\n }\n\n static restored<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void {\n this.registerModelEvent('restored', callback)\n }\n\n static forceDeleting<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void {\n this.registerModelEvent('forceDeleting', callback)\n }\n\n static forceDeleted<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void {\n this.registerModelEvent('forceDeleted', callback)\n }\n\n /**\n * Registers observers: every method named after a model event (created, updating, …) becomes a listener.\n * Observer classes are resolved from the container.\n */\n static observe(...observers: Array<object | (new () => object)>): void {\n const dispatcher = requireEventDispatcher(this.name)\n for (const entry of observers) {\n const observer = (typeof entry === 'function' ? (currentContainer()?.make(entry as new () => object) ?? new (entry as new () => object)()) : entry) as Record<string, unknown>\n for (const event of MODEL_EVENTS) {\n const method = observer[event]\n if (typeof method !== 'function') continue\n dispatcher.listen(modelEventName(event, this.name), (model: unknown) => (method as (m: unknown) => unknown).call(observer, model))\n }\n }\n }\n\n /** Runs fn with model events off, for this async context only. */\n static withoutEvents<R>(fn: () => R): R {\n return withoutModelEvents(fn)\n }\n\n // ---------------------------------------------------------------- static query API (Post.where(…), Post.find(…))\n\n /** A new query of this model, with its global scopes. */\n static query<C extends typeof Model>(this: C): ModelBuilder<C> {\n return (this as typeof Model).prototypeInstance().newQuery() as unknown as ModelBuilder<C>\n }\n\n static where<C extends typeof Model>(this: C, ...args: WhereArgs<Instance<C>, ModelBuilder<C>>): ModelBuilder<C> {\n const query = this.query()\n return Reflect.apply(query.where, query, args) as ModelBuilder<C>\n }\n\n static whereKey<C extends typeof Model>(this: C, id: unknown): ModelBuilder<C> {\n return this.query().whereKey(id)\n }\n\n static whereIn<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression, values: readonly unknown[]): ModelBuilder<C> {\n return this.query().whereIn(column, values)\n }\n\n static whereNotIn<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression, values: readonly unknown[]): ModelBuilder<C> {\n return this.query().whereNotIn(column, values)\n }\n\n static whereNull<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression): ModelBuilder<C> {\n return this.query().whereNull(column)\n }\n\n static whereNotNull<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression): ModelBuilder<C> {\n return this.query().whereNotNull(column)\n }\n\n static whereBetween<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression, values: readonly [unknown, unknown]): ModelBuilder<C> {\n return this.query().whereBetween(column, values)\n }\n\n static whereColumn<C extends typeof Model>(this: C, first: Column<Instance<C>>, operatorOrSecond: string, second?: Column<Instance<C>>): ModelBuilder<C> {\n return this.query().whereColumn(first, operatorOrSecond, second)\n }\n\n static whereRaw<C extends typeof Model>(this: C, sql: string, bindings: readonly unknown[] = []): ModelBuilder<C> {\n return this.query().whereRaw(sql, bindings)\n }\n\n static select<C extends typeof Model>(this: C, ...columns: Array<Column<Instance<C>> | Expression>): ModelBuilder<C> {\n return this.query().select(...columns)\n }\n\n static orderBy<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression, direction: Direction = 'asc'): ModelBuilder<C> {\n return this.query().orderBy(column, direction)\n }\n\n static latest<C extends typeof Model>(this: C, column?: Column<Instance<C>>): ModelBuilder<C> {\n return this.query().latest(column)\n }\n\n static oldest<C extends typeof Model>(this: C, column?: Column<Instance<C>>): ModelBuilder<C> {\n return this.query().oldest(column)\n }\n\n static inRandomOrder<C extends typeof Model>(this: C): ModelBuilder<C> {\n return this.query().inRandomOrder()\n }\n\n static limit<C extends typeof Model>(this: C, count: number): ModelBuilder<C> {\n return this.query().limit(count)\n }\n\n static take<C extends typeof Model>(this: C, count: number): ModelBuilder<C> {\n return this.query().take(count)\n }\n\n static withoutGlobalScope<C extends typeof Model>(this: C, scope: string | ScopeClass): ModelBuilder<C> {\n return this.query().withoutGlobalScope(scope)\n }\n\n static withoutGlobalScopes<C extends typeof Model>(this: C, scopes?: Array<string | ScopeClass>): ModelBuilder<C> {\n return this.query().withoutGlobalScopes(scopes)\n }\n\n /** Eager loads relations: Post.with('author', 'comments.user').get(). */\n static with<C extends typeof Model>(this: C, ...relations: EagerLoadSpec[]): ModelBuilder<C> {\n return this.query().with(...relations)\n }\n\n static withCount<C extends typeof Model>(this: C, ...relations: EagerLoadSpec[]): ModelBuilder<C> {\n return this.query().withCount(...relations)\n }\n\n static has<C extends typeof Model>(this: C, relation: string, operator = '>=', count = 1): ModelBuilder<C> {\n return this.query().has(relation, operator, count)\n }\n\n static whereHas<C extends typeof Model>(this: C, relation: string, callback?: RelationConstraint, operator = '>=', count = 1): ModelBuilder<C> {\n return this.query().whereHas(relation, callback, operator, count)\n }\n\n static doesntHave<C extends typeof Model>(this: C, relation: string): ModelBuilder<C> {\n return this.query().doesntHave(relation)\n }\n\n static whereDoesntHave<C extends typeof Model>(this: C, relation: string, callback?: RelationConstraint): ModelBuilder<C> {\n return this.query().whereDoesntHave(relation, callback)\n }\n\n /** Soft deletes: include trashed rows. */\n static withTrashed<C extends typeof Model>(this: C): ModelBuilder<C> {\n return this.query().withTrashed()\n }\n\n /** Soft deletes: only trashed rows. */\n static onlyTrashed<C extends typeof Model>(this: C): ModelBuilder<C> {\n return this.query().onlyTrashed()\n }\n\n static withoutTrashed<C extends typeof Model>(this: C): ModelBuilder<C> {\n return this.query().withoutTrashed()\n }\n\n static all<C extends typeof Model>(this: C): Promise<Collection<Instance<C>>> {\n return this.query().get()\n }\n\n static find<C extends typeof Model>(this: C, id: unknown): Promise<Instance<C> | undefined> {\n return this.query().find(id)\n }\n\n static findOrFail<C extends typeof Model>(this: C, ids: readonly unknown[]): Promise<Collection<Instance<C>>>\n static findOrFail<C extends typeof Model>(this: C, id: unknown): Promise<Instance<C>>\n static findOrFail<C extends typeof Model>(this: C, id: unknown): Promise<Instance<C> | Collection<Instance<C>>> {\n return this.query().findOrFail(id)\n }\n\n static findMany<C extends typeof Model>(this: C, ids: readonly unknown[]): Promise<Collection<Instance<C>>> {\n return this.query().findMany(ids)\n }\n\n static first<C extends typeof Model>(this: C): Promise<Instance<C> | undefined> {\n return this.query().first()\n }\n\n static firstOrFail<C extends typeof Model>(this: C): Promise<Instance<C>> {\n return this.query().firstOrFail()\n }\n\n static firstWhere<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression, operatorOrValue: unknown, value?: unknown): Promise<Instance<C> | undefined> {\n return this.query().firstWhere(column, operatorOrValue, value)\n }\n\n static count(): Promise<number> {\n return this.query().count()\n }\n\n static exists(): Promise<boolean> {\n return this.query().exists()\n }\n\n static pluck<C extends typeof Model, V = unknown>(this: C, column: Column<Instance<C>>): Promise<Collection<V>> {\n return this.query().pluck<V>(column)\n }\n\n static paginate<C extends typeof Model>(this: C, perPage?: number, columns?: string[], pageName?: string, page?: number): Promise<LengthAwarePaginator<Instance<C>>> {\n return this.query().paginate(perPage, columns, pageName, page)\n }\n\n static simplePaginate<C extends typeof Model>(this: C, perPage?: number, columns?: string[], pageName?: string, page?: number): Promise<Paginator<Instance<C>>> {\n return this.query().simplePaginate(perPage, columns, pageName, page)\n }\n\n static cursorPaginate<C extends typeof Model>(this: C, perPage?: number, columns?: string[], cursorName?: string, cursor?: Cursor | string): Promise<CursorPaginator<Instance<C>>> {\n return this.query().cursorPaginate(perPage, columns, cursorName, cursor)\n }\n\n static chunk<C extends typeof Model>(this: C, count: number, callback: (models: Collection<Instance<C>>, page: number) => unknown): Promise<boolean> {\n return this.query().chunk(count, callback)\n }\n\n static chunkById<C extends typeof Model>(this: C, count: number, callback: (models: Collection<Instance<C>>, page: number) => unknown): Promise<boolean> {\n return this.query().chunkById(count, callback)\n }\n\n static each<C extends typeof Model>(this: C, callback: (model: Instance<C>, index: number) => unknown, count?: number): Promise<boolean> {\n return this.query().each(callback, count)\n }\n\n static lazy<C extends typeof Model>(this: C, chunkSize?: number): LazyCollection<Instance<C>> {\n return this.query().lazy(chunkSize)\n }\n\n static lazyById<C extends typeof Model>(this: C, chunkSize?: number): LazyCollection<Instance<C>> {\n return this.query().lazyById(chunkSize)\n }\n\n /** Creates and saves a model (mass assignment rules apply). */\n static create<C extends typeof Model>(this: C, attributes: Row = {}): Promise<Instance<C>> {\n return this.query().create(attributes)\n }\n\n static forceCreate<C extends typeof Model>(this: C, attributes: Row): Promise<Instance<C>> {\n return this.query().forceCreate(attributes)\n }\n\n static firstOrNew<C extends typeof Model>(this: C, attributes: Row, values: Row = {}): Promise<Instance<C>> {\n return this.query().firstOrNew(attributes, values)\n }\n\n static firstOrCreate<C extends typeof Model>(this: C, attributes: Row, values: Row = {}): Promise<Instance<C>> {\n return this.query().firstOrCreate(attributes, values)\n }\n\n static updateOrCreate<C extends typeof Model>(this: C, attributes: Row, values: Row = {}): Promise<Instance<C>> {\n return this.query().updateOrCreate(attributes, values)\n }\n\n /**\n * The model's registered factory (database/factories/<Model>Factory.ts): await User.factory().create(),\n * await User.factory(3).create(). Use UserFactory.new() to reach the factory's own state methods with their types.\n */\n static factory<C extends typeof Model>(this: C): Factory<InstanceType<C>>\n static factory<C extends typeof Model>(this: C, count: number, state?: State): Factory<InstanceType<C>> & Many\n static factory<C extends typeof Model>(this: C, count?: number, state?: State): Factory<InstanceType<C>> {\n let factory = Factory.forModel(this as unknown as new () => InstanceType<C>)\n if (count !== undefined) factory = factory.count(count)\n if (state) factory = factory.state(state)\n return factory\n }\n\n /** Deletes models by key, one by one, so model events fire. Returns how many were deleted. */\n static async destroy(...ids: Array<unknown | unknown[]>): Promise<number> {\n const keys = ids.flat()\n if (!keys.length) return 0\n let count = 0\n for (const model of await this.query().whereKey(keys).get()) if (await model.delete()) count++\n return count\n }\n\n // ---------------------------------------------------------------- mass assignment\n\n /** Disables mass assignment protection everywhere until reguard(). */\n static unguard(state = true): void {\n unguardedGlobally.value = state\n }\n\n static reguard(): void {\n unguardedGlobally.value = false\n }\n\n static isUnguarded(): boolean {\n return unguardedGlobally.value || unguardedScope.getStore() === true\n }\n\n /** Runs fn with mass assignment protection off, for this async context only (seeders, factories). */\n static unguarded<R>(fn: () => R): R {\n return unguardedScope.run(true, fn)\n }\n\n /** Sets the fillable attributes; the others are dropped, or throw MassAssignmentError on a totally guarded model. */\n fill(attributes: Row): this {\n const totallyGuarded = this.totallyGuarded()\n for (const [key, value] of Object.entries(attributes)) {\n if (this.isFillable(key)) this.setAttribute(key, value)\n else if (totallyGuarded) throw new MassAssignmentError(this.constructor.name, key)\n }\n return this\n }\n\n /** Sets attributes with no mass assignment check. Never pass it request input. */\n forceFill(attributes: Row): this {\n for (const [key, value] of Object.entries(attributes)) this.setAttribute(key, value)\n return this\n }\n\n isFillable(key: string): boolean {\n if (Model.isUnguarded()) return true\n if (this.fillable.includes(key)) return true\n if (this.fillable.length > 0 || this.isGuarded(key)) return false\n return PLAIN_COLUMN.test(key) && !key.startsWith('_')\n }\n\n /** Guarded names match case-insensitively: SQLite and MySQL column names are case-insensitive. */\n isGuarded(key: string): boolean {\n if (this.guarded.length === 0) return false\n const lower = key.toLowerCase()\n return this.guarded.some((guarded) => guarded === '*' || guarded.toLowerCase() === lower)\n }\n\n totallyGuarded(): boolean {\n return !Model.isUnguarded() && this.fillable.length === 0 && this.guarded.length === 1 && this.guarded[0] === '*'\n }\n\n getFillable(): string[] {\n return [...this.fillable]\n }\n\n getGuarded(): string[] {\n return [...this.guarded]\n }\n\n // ---------------------------------------------------------------- attributes\n\n /** An attribute through its accessor or cast; undefined when the model doesn't have it. */\n getAttribute<T = unknown>(key: string): T {\n if (!key) return undefined as T\n if (Object.hasOwn(this.attributes, key) || this.hasGetMutator(key) || this.hasCast(key)) return this.getAttributeValue(key) as T\n return undefined as T\n }\n\n /** The attribute's value after its accessor (get<Name>Attribute) or cast. */\n getAttributeValue(key: string): unknown {\n const value = this.attributes[key]\n const accessor = this.mutatorFor('get', key)\n if (accessor) return accessor.call(this, value)\n return this.castAttribute(key, value)\n }\n\n /** Sets an attribute through its mutator (set<Name>Attribute) or cast. */\n setAttribute(key: string, value: unknown): this {\n const mutator = this.mutatorFor('set', key)\n if (mutator) {\n mutator.call(this, value)\n return this\n }\n const cast = this.getCasts()[key]\n this.castCache.delete(key)\n this.attributes[key] = cast === undefined ? value : castSet(this, key, cast, value, this.attributes, this.constructor.name)\n return this\n }\n\n hasGetMutator(key: string): boolean {\n return this.mutatorFor('get', key) !== undefined\n }\n\n hasSetMutator(key: string): boolean {\n return this.mutatorFor('set', key) !== undefined\n }\n\n /** Every cast, including the implied ones: the incrementing key (int) and the timestamp columns (datetime). */\n getCasts(): Record<string, CastDefinition> {\n const implied: Record<string, CastDefinition> = {}\n if (this.incrementing) implied[this.getKeyName()] = this.keyType === 'int' ? 'int' : 'string'\n if (this.usesTimestamps()) {\n const created = this.getCreatedAtColumn()\n const updated = this.getUpdatedAtColumn()\n if (created) implied[created] = 'datetime'\n if (updated) implied[updated] = 'datetime'\n }\n if (this.softDeletes) implied[this.getDeletedAtColumn()] = 'datetime'\n return { ...implied, ...this.casts }\n }\n\n hasCast(key: string, types?: string[]): boolean {\n const cast = this.getCasts()[key]\n if (cast === undefined) return false\n return types === undefined || (typeof cast === 'string' && types.includes(cast))\n }\n\n /** The stored attributes, with in-place changes to json casts written back. */\n getAttributes(): Row {\n this.mergeCachedCasts()\n return { ...this.attributes }\n }\n\n /** Replaces the stored attributes as-is (no casts or mutators); sync = also make them the original. */\n setRawAttributes(attributes: Row, sync = false): this {\n this.attributes = { ...attributes }\n this.castCache.clear()\n if (sync) this.syncOriginal()\n return this\n }\n\n /** The original value (cast), or every original value. */\n getOriginal(): Row\n getOriginal<T = unknown>(key: string): T\n getOriginal(key?: string): unknown {\n if (key !== undefined) return this.castAttribute(key, this.original[key], false)\n return Object.fromEntries(Object.keys(this.original).map((name) => [name, this.castAttribute(name, this.original[name], false)]))\n }\n\n getRawOriginal(): Row\n getRawOriginal<T = unknown>(key: string): T\n getRawOriginal(key?: string): unknown {\n return key === undefined ? { ...this.original } : this.original[key]\n }\n\n syncOriginal(): this {\n this.original = this.getAttributes()\n return this\n }\n\n syncOriginalAttributes(...keys: string[]): this {\n const current = this.getAttributes()\n for (const key of keys) this.original[key] = current[key]\n return this\n }\n\n /** The attributes that changed since the model was loaded or saved, compared by meaning (casts), not representation. */\n getDirty(): Row {\n this.mergeCachedCasts()\n const casts = this.getCasts()\n const dirty: Row = {}\n for (const [key, value] of Object.entries(this.attributes)) {\n const unchanged = Object.hasOwn(this.original, key) &&\n isEquivalent(casts[key], value, this.original[key], this, key, this.constructor.name)\n if (!unchanged) dirty[key] = value\n }\n return dirty\n }\n\n isDirty(...keys: Array<string | string[]>): boolean {\n const dirty = this.getDirty()\n const names = keys.flat()\n return names.length ? names.some((key) => Object.hasOwn(dirty, key)) : Object.keys(dirty).length > 0\n }\n\n isClean(...keys: Array<string | string[]>): boolean {\n return !this.isDirty(...keys)\n }\n\n /** The attributes the last save() changed. */\n getChanges(): Row {\n return { ...this.changes }\n }\n\n wasChanged(...keys: Array<string | string[]>): boolean {\n const names = keys.flat()\n return names.length ? names.some((key) => Object.hasOwn(this.changes, key)) : Object.keys(this.changes).length > 0\n }\n\n syncChanges(): this {\n this.changes = this.getDirty()\n return this\n }\n\n /** The given attributes (through accessors and casts). */\n only(...keys: Array<string | string[]>): Row {\n return Object.fromEntries(keys.flat().map((key) => [key, this.getAttribute(key)]))\n }\n\n /**\n * useCache = false skips the json-cast decode cache entirely (both reading and writing it): used by getOriginal(),\n * so a decoded original never aliases the live attribute's cached (and possibly in-place-mutated) object, even\n * when their raw stored strings are equal right after load/save.\n */\n protected castAttribute(key: string, value: unknown, useCache = true): unknown {\n const cast = this.getCasts()[key]\n if (cast === undefined) return value\n if (useCache && isJsonCast(cast) && value !== null && value !== undefined) {\n const cached = this.castCache.get(key)\n if (cached && cached.raw === value) return cached.value\n const decoded = castGet(this, key, cast, value, this.attributes, this.constructor.name)\n if (value === this.attributes[key]) this.castCache.set(key, { raw: value, value: decoded })\n return decoded\n }\n return castGet(this, key, cast, value, this.attributes, this.constructor.name)\n }\n\n /** Writes json casts that were changed in place (post.meta.views++) back into the stored attributes. */\n protected mergeCachedCasts(): void {\n const casts = this.getCasts()\n for (const [key, entry] of this.castCache) {\n if (this.attributes[key] !== entry.raw) {\n this.castCache.delete(key)\n continue\n }\n const encoded = castSet(this, key, casts[key]!, entry.value, this.attributes, this.constructor.name)\n if (encoded !== entry.raw) {\n this.attributes[key] = encoded\n entry.raw = encoded\n }\n }\n }\n\n private mutatorFor(kind: 'get' | 'set', key: string): AnyFunction | undefined {\n return methodOf(this, `${kind}${Str.studly(key)}Attribute`)\n }\n\n // ---------------------------------------------------------------- keys, table and naming\n\n getKeyName(): string {\n return this.primaryKey\n }\n\n getKeyType(): 'int' | 'string' {\n return this.keyType\n }\n\n getIncrementing(): boolean {\n return this.incrementing\n }\n\n getKey(): unknown {\n return this.getAttribute(this.getKeyName())\n }\n\n getTable(): string {\n return this.table ?? Str.snake(Str.plural(this.constructor.name))\n }\n\n getConnectionName(): string | undefined {\n return this.connection\n }\n\n getPerPage(): number {\n return this.perPage\n }\n\n /** 'posts.title' for 'title'. Already-qualified columns are returned as-is. */\n qualifyColumn(column: string): string {\n return column.includes('.') ? column : `${this.getTable()}.${column}`\n }\n\n getQualifiedKeyName(): string {\n return this.qualifyColumn(this.getKeyName())\n }\n\n /** The conventional foreign key pointing at this model: user_id for User. */\n getForeignKey(): string {\n return `${Str.snake(this.constructor.name)}_${this.getKeyName()}`\n }\n\n getRouteKeyName(): string {\n return this.getKeyName()\n }\n\n getRouteKey(): unknown {\n return this.getAttribute(this.getRouteKeyName())\n }\n\n /**\n * The model a route parameter value points at: where <field or route key> = value (global scopes apply, so a\n * soft-deleted row isn't found). A non-numeric value for an integer primary key finds nothing without a query.\n */\n async resolveRouteBinding(value: string, field?: string): Promise<this | undefined> {\n const column = field ?? this.getRouteKeyName()\n if (column === this.getKeyName() && this.keyType === 'int' && !/^-?\\d+$/.test(value)) return undefined\n return this.resolveRouteBindingQuery(this.newQuery(), value, column).first()\n }\n\n /** Override to customize the binding query (Laravel's resolveRouteBindingQuery()). */\n resolveRouteBindingQuery(query: Builder<this>, value: string, field: string): Builder<this> {\n return query.where(this.qualifyColumn(field) as Column<this>, value)\n }\n\n usesTimestamps(): boolean {\n return this.timestamps\n }\n\n usesSoftDeletes(): boolean {\n return this.softDeletes\n }\n\n getCreatedAtColumn(): string | null {\n return (this.constructor as typeof Model).CREATED_AT\n }\n\n getUpdatedAtColumn(): string | null {\n return (this.constructor as typeof Model).UPDATED_AT\n }\n\n getDeletedAtColumn(): string {\n return (this.constructor as typeof Model).DELETED_AT\n }\n\n // ---------------------------------------------------------------- connection and queries\n\n /** The model's database connection, from the DatabaseManager binding. */\n getConnection(): Connection {\n const connection = inject(DatabaseManager).connection(this.getConnectionName())\n if (!(connection instanceof Connection)) {\n throw new DatabaseConfigError('Models need the DatabaseManager from @orieljs/database. Is DatabaseServiceProvider registered?')\n }\n return connection\n }\n\n setConnection(name: string | undefined): this {\n this.connection = name\n return this\n }\n\n setTable(table: string): this {\n this.table = table\n return this\n }\n\n /** A new instance of the same class, connection and table (mass assignment rules apply to attributes). */\n newInstance(attributes: Row = {}, exists = false): this {\n const model = new (this.constructor as new () => this)()\n model.exists = exists\n model.setConnection(this.getConnectionName())\n model.setTable(this.getTable())\n return model.fill(attributes)\n }\n\n /** An existing model from a database row (no casts or mutators applied to the row). */\n newFromBuilder(attributes: Row): this {\n const model = this.newInstance({}, true)\n model.setRawAttributes(attributes, true)\n return model\n }\n\n /** A query of this model with its global scopes and default eager loads. */\n newQuery(): Builder<this> {\n return this.registerGlobalScopes(this.newQueryWithoutScopes())\n }\n\n /** A query with the default eager loads (`with`, `withCount`) but no global scopes. */\n newQueryWithoutScopes(): Builder<this> {\n return this.registerDefaultEagerLoads(this.newModelQuery())\n }\n\n /** A query with the global scopes but no default eager loads. */\n newQueryWithoutRelationships(): Builder<this> {\n return this.registerGlobalScopes(this.newModelQuery())\n }\n\n /** Adds this class's global scopes to a builder (relations use it for the related model's scopes). */\n registerGlobalScopes<B extends Builder<Model>>(builder: B): B {\n for (const [name, scope] of globalScopes.get(this.constructor as typeof Model) ?? []) builder.withGlobalScope(name, scope)\n return builder\n }\n\n /**\n * Adds this class's default `with` and `withCount` to a builder (relations use it for the related model's\n * defaults). A default count that reaches the same class again while it is being added (a self-referencing\n * relation, or two models counting each other) is skipped there instead of recursing forever.\n */\n registerDefaultEagerLoads<B extends Builder<Model>>(builder: B): B {\n if (this.with.length) builder.with(...this.with)\n const cls = this.constructor as typeof Model\n if (!this.withCount.length || addingDefaultCounts.has(cls)) return builder\n addingDefaultCounts.add(cls)\n try {\n builder.withCount(...this.withCount)\n } finally {\n addingDefaultCounts.delete(cls)\n }\n return builder\n }\n\n /** A bare builder for this model: no global scopes, no default eager loads. */\n newModelQuery(): Builder<this> {\n return new Builder<this>(this)\n }\n\n // ---------------------------------------------------------------- persistence\n\n /**\n * Inserts the model, or updates its dirty attributes. Only changed columns are written; an unchanged model\n * runs no query at all. Returns false when a saving/creating/updating listener cancels.\n */\n async save(): Promise<boolean> {\n const query = this.newModelQuery()\n if ((await this.fireModelEvent('saving')) === false) return false\n let saved: boolean\n if (this.exists) saved = this.isDirty() ? await this.performUpdate(query) : true\n else saved = await this.performInsert(query)\n if (saved) await this.finishSave()\n return saved\n }\n\n /** Fills and saves an existing model. */\n async update(attributes: Row = {}): Promise<boolean> {\n if (!this.exists) return false\n return this.fill(attributes).save()\n }\n\n /**\n * Deletes the model's row, or sets deleted_at with soft deletes. Returns false for a model that isn't saved, or\n * when a deleting listener cancels.\n */\n async delete(): Promise<boolean> {\n if (!this.exists) return false\n if ((await this.fireModelEvent('deleting')) === false) return false\n await this.performDeleteOnModel()\n await this.fireModelEvent('deleted', false)\n return true\n }\n\n /** save() without model events. */\n saveQuietly(): Promise<boolean> {\n return withoutModelEvents(() => this.save())\n }\n\n /** delete() without model events. */\n deleteQuietly(): Promise<boolean> {\n return withoutModelEvents(() => this.delete())\n }\n\n // ---------------------------------------------------------------- soft deletes\n\n /** True when the model is soft deleted. Only for models with `softDeletes = true`. */\n trashed(): boolean {\n this.assertSoftDeletes('trashed')\n const value = this.getAttribute(this.getDeletedAtColumn())\n return value !== null && value !== undefined\n }\n\n /** Clears deleted_at and saves. Fires restoring (can cancel) and restored. */\n async restore(): Promise<boolean> {\n this.assertSoftDeletes('restore')\n if ((await this.fireModelEvent('restoring')) === false) return false\n this.setAttribute(this.getDeletedAtColumn(), null)\n this.exists = true\n const saved = await this.save()\n await this.fireModelEvent('restored', false)\n return saved\n }\n\n /** Deletes the row for real, even with soft deletes. Fires forceDeleting (can cancel) and forceDeleted. */\n async forceDelete(): Promise<boolean> {\n if (!this.usesSoftDeletes()) return this.delete()\n if ((await this.fireModelEvent('forceDeleting')) === false) return false\n this.forceDeleting = true\n try {\n const deleted = await this.delete()\n if (deleted) await this.fireModelEvent('forceDeleted', false)\n return deleted\n } finally {\n this.forceDeleting = false\n }\n }\n\n isForceDeleting(): boolean {\n return this.forceDeleting\n }\n\n getQualifiedDeletedAtColumn(): string {\n return this.qualifyColumn(this.getDeletedAtColumn())\n }\n\n private assertSoftDeletes(method: string): void {\n if (!this.usesSoftDeletes()) {\n throw new LogicError(`${method}() needs soft deletes: set \\`protected softDeletes = true\\` on [${this.constructor.name}].`)\n }\n }\n\n /** Reloads the attributes and the loaded relations from the database (including a soft-deleted row). */\n async refresh(): Promise<this> {\n if (!this.exists) return this\n const fresh = await this.newModelQuery().whereKey(this.getKey()).firstOrFail()\n this.setRawAttributes(fresh.getAttributes(), true)\n const loaded = Object.keys(this.relations)\n if (loaded.length) await this.load(loaded)\n return this\n }\n\n /** A fresh copy from the database, or undefined when the row is gone. */\n async fresh(): Promise<this | undefined> {\n if (!this.exists) return undefined\n return this.newModelQuery().whereKey(this.getKey()).first()\n }\n\n /** Updates updated_at (and saves). */\n async touch(): Promise<boolean> {\n if (!this.usesTimestamps()) return false\n this.updateTimestamps()\n return this.save()\n }\n\n /** column = column + amount in the database, mirrored on the model without marking it dirty. */\n async increment(column: string, amount = 1, extra: Row = {}): Promise<number> {\n return this.incrementOrDecrement(column, amount, extra)\n }\n\n async decrement(column: string, amount = 1, extra: Row = {}): Promise<number> {\n return this.incrementOrDecrement(column, -amount, extra)\n }\n\n /** Same table, connection and key. */\n is(other: Model | null | undefined): boolean {\n return !!other && other.getKey() === this.getKey() && other.getTable() === this.getTable() &&\n other.getConnectionName() === this.getConnectionName()\n }\n\n isNot(other: Model | null | undefined): boolean {\n return !this.is(other)\n }\n\n /** The current time, to the second (the storage precision). */\n freshTimestamp(): Date {\n const now = new Date()\n now.setMilliseconds(0)\n return now\n }\n\n updateTimestamps(): void {\n const time = this.freshTimestamp()\n const updated = this.getUpdatedAtColumn()\n const created = this.getCreatedAtColumn()\n if (updated && !this.isDirty(updated)) this.setAttribute(updated, time)\n if (!this.exists && created && !this.isDirty(created)) this.setAttribute(created, time)\n }\n\n protected async performInsert(query: Builder<this>): Promise<boolean> {\n if ((await this.fireModelEvent('creating')) === false) return false\n if (this.usesTimestamps()) this.updateTimestamps()\n const attributes = this.getAttributes()\n if (this.getIncrementing()) {\n const id = await query.insertGetId(attributes, this.getKeyName())\n this.setAttribute(this.getKeyName(), id)\n } else {\n if (!Object.keys(attributes).length) return true\n await query.insert(attributes)\n }\n this.exists = true\n this.wasRecentlyCreated = true\n await this.fireModelEvent('created', false)\n return true\n }\n\n protected async performUpdate(query: Builder<this>): Promise<boolean> {\n if ((await this.fireModelEvent('updating')) === false) return false\n if (this.usesTimestamps()) this.updateTimestamps()\n const dirty = this.getDirty()\n if (Object.keys(dirty).length) {\n await this.setKeysForSaveQuery(query).update(dirty)\n this.syncChanges()\n await this.fireModelEvent('updated', false)\n }\n return true\n }\n\n protected async finishSave(): Promise<void> {\n await this.fireModelEvent('saved', false)\n this.syncOriginal()\n }\n\n protected async performDeleteOnModel(): Promise<void> {\n if (this.usesSoftDeletes() && !this.forceDeleting) return this.runSoftDelete()\n await this.setKeysForSaveQuery(this.newModelQuery()).forceDelete()\n this.exists = false\n }\n\n /** deleted_at (and updated_at) = now, on this row only. The model still exists, as a trashed model. */\n protected async runSoftDelete(): Promise<void> {\n const time = this.freshTimestamp()\n const columns = [this.getDeletedAtColumn()]\n this.setAttribute(this.getDeletedAtColumn(), time)\n const updated = this.getUpdatedAtColumn()\n if (this.usesTimestamps() && updated) {\n this.setAttribute(updated, time)\n columns.push(updated)\n }\n const values = Object.fromEntries(columns.map((column) => [column, this.getAttributes()[column]]))\n await this.setKeysForSaveQuery(this.newModelQuery()).update(values)\n this.syncOriginalAttributes(...columns)\n }\n\n /** where key = the key the row was loaded with (the original, in case the key itself changed). */\n protected setKeysForSaveQuery(query: Builder<this>): Builder<this> {\n const key = Object.hasOwn(this.original, this.getKeyName()) ? this.original[this.getKeyName()] : this.getKey()\n if (key === undefined || key === null) throw new LogicError(`Model [${this.constructor.name}] has no primary key value.`)\n return query.where(this.getKeyName() as Column<this>, '=', key)\n }\n\n protected async incrementOrDecrement(column: string, amount: number, extra: Row): Promise<number> {\n // An unsaved model updates every row its global scopes allow (never trashed rows); a saved one updates its own row.\n if (!this.exists) return this.newQueryWithoutRelationships().increment(column, amount, extra)\n const affected = await this.setKeysForSaveQuery(this.newModelQuery()).increment(column, amount, extra)\n this.forceFill({ ...extra, [column]: Number(this.getAttribute(column) ?? 0) + amount })\n this.syncOriginalAttributes(column, ...Object.keys(extra))\n return affected\n }\n\n /**\n * Dispatches 'eloquent.<event>: <Class>' with the model as payload. Halting events return false when a listener\n * returned false. A no-op without an EventDispatcher binding, or inside withoutEvents().\n */\n async fireModelEvent(event: ModelEvent, halt = true): Promise<boolean> {\n if (modelEventsMuted()) return true\n const dispatcher = eventDispatcher()\n if (!dispatcher) return true\n const name = modelEventName(event, this.constructor.name)\n if (halt) return (await dispatcher.until(name, [this])) !== false\n await dispatcher.dispatch(name, [this])\n return true\n }\n\n /** Whether any listener is registered for one of this model's events (retrieved is skipped when none is). */\n hasModelListeners(event: ModelEvent): boolean {\n return !modelEventsMuted() && (eventDispatcher()?.hasListeners(modelEventName(event, this.constructor.name)) ?? false)\n }\n\n // ---------------------------------------------------------------- relations\n\n /**\n * One related row holds this model's key: user.profile() → hasOne(Profile) (profiles.user_id = users.id).\n * @param foreignKey on the related table (default: this model's foreign key, e.g. user_id)\n * @param localKey on this model (default: the primary key)\n */\n hasOne<C extends typeof Model>(related: C, foreignKey?: string, localKey?: string): HasOne<InstanceType<C>, this> & Scopes<C> {\n const instance = this.newRelatedInstance(related)\n const relation = new HasOne(instance, this, instance.qualifyColumn(foreignKey ?? this.getForeignKey()), localKey ?? this.getKeyName())\n return relation as HasOne<InstanceType<C>, this> & Scopes<C>\n }\n\n /** Many related rows hold this model's key: post.comments() → hasMany(Comment) (comments.post_id = posts.id). */\n hasMany<C extends typeof Model>(related: C, foreignKey?: string, localKey?: string): HasMany<InstanceType<C>, this> & Scopes<C> {\n const instance = this.newRelatedInstance(related)\n const relation = new HasMany(instance, this, instance.qualifyColumn(foreignKey ?? this.getForeignKey()), localKey ?? this.getKeyName())\n return relation as HasMany<InstanceType<C>, this> & Scopes<C>\n }\n\n /**\n * This model holds the related model's key: post.author() → belongsTo(User, 'user_id').\n * @param foreignKey on this model (default: the related model's foreign key, e.g. user_id)\n * @param ownerKey on the related model (default: its primary key)\n * @param relation the loaded-relation name associate() sets (default: the resolved name, else the class in camelCase)\n */\n belongsTo<C extends typeof Model>(related: C, foreignKey?: string, ownerKey?: string, relation?: string): BelongsTo<InstanceType<C>, this> & Scopes<C> {\n const instance = this.newRelatedInstance(related)\n const belongsTo = new BelongsTo(instance, this, foreignKey ?? instance.getForeignKey(), ownerKey ?? instance.getKeyName(), relation)\n return belongsTo as BelongsTo<InstanceType<C>, this> & Scopes<C>\n }\n\n /**\n * Many-to-many through a pivot table: post.tags() → belongsToMany(Tag) over post_tag (post_id, tag_id).\n * @param table default: the two singular snake names in alphabetical order (post_tag)\n * @param foreignPivotKey the pivot column pointing at this model (default: post_id)\n * @param relatedPivotKey the pivot column pointing at the related model (default: tag_id)\n */\n belongsToMany<C extends typeof Model>(\n related: C,\n table?: string,\n foreignPivotKey?: string,\n relatedPivotKey?: string,\n parentKey?: string,\n relatedKey?: string,\n ): BelongsToMany<InstanceType<C>, this> & Scopes<C> {\n const instance = this.newRelatedInstance(related)\n const joining = table ?? [Str.snake(this.constructor.name), Str.snake(related.name)].sort().join('_').toLowerCase()\n const relation = new BelongsToMany(\n instance,\n this,\n joining,\n foreignPivotKey ?? this.getForeignKey(),\n relatedPivotKey ?? instance.getForeignKey(),\n parentKey ?? this.getKeyName(),\n relatedKey ?? instance.getKeyName(),\n )\n return relation as BelongsToMany<InstanceType<C>, this> & Scopes<C>\n }\n\n /**\n * Related rows through an intermediate model: country.posts() → hasManyThrough(Post, User).\n * @param firstKey on the through table (default: this model's foreign key, country_id)\n * @param secondKey on the related table (default: the through model's foreign key, user_id)\n */\n hasManyThrough<C extends typeof Model, T extends typeof Model>(\n related: C,\n through: T,\n firstKey?: string,\n secondKey?: string,\n localKey?: string,\n secondLocalKey?: string,\n ): HasManyThrough<InstanceType<C>, this, InstanceType<T>> & Scopes<C> {\n const instance = this.newRelatedInstance(related)\n const throughParent = this.newRelatedInstance(through)\n const relation = new HasManyThrough(\n instance,\n this,\n throughParent,\n firstKey ?? this.getForeignKey(),\n secondKey ?? throughParent.getForeignKey(),\n localKey ?? this.getKeyName(),\n secondLocalKey ?? throughParent.getKeyName(),\n )\n return relation as HasManyThrough<InstanceType<C>, this, InstanceType<T>> & Scopes<C>\n }\n\n /** A polymorphic one-to-one: user.image() → morphOne(Image, 'imageable') (images.imageable_id/_type). */\n morphOne<C extends typeof Model>(related: C, name: string, type?: string, id?: string, localKey?: string): MorphOne<InstanceType<C>, this> & Scopes<C> {\n const instance = this.newRelatedInstance(related)\n const relation = new MorphOne(instance, this, instance.qualifyColumn(type ?? `${name}_type`), instance.qualifyColumn(id ?? `${name}_id`), localKey ?? this.getKeyName())\n return relation as MorphOne<InstanceType<C>, this> & Scopes<C>\n }\n\n /** A polymorphic one-to-many: post.comments() → morphMany(Comment, 'commentable'). */\n morphMany<C extends typeof Model>(related: C, name: string, type?: string, id?: string, localKey?: string): MorphMany<InstanceType<C>, this> & Scopes<C> {\n const instance = this.newRelatedInstance(related)\n const relation = new MorphMany(instance, this, instance.qualifyColumn(type ?? `${name}_type`), instance.qualifyColumn(id ?? `${name}_id`), localKey ?? this.getKeyName())\n return relation as MorphMany<InstanceType<C>, this> & Scopes<C>\n }\n\n /**\n * The inverse of morphOne/morphMany: comment.commentable() → morphTo('commentable'). The name is required\n * (Laravel reads it from the calling method, which JavaScript can't do reliably).\n */\n morphTo<R extends Model = Model>(name: string, type?: string, id?: string, ownerKey?: string): MorphTo<R, this> {\n const typeColumn = type ?? `${name}_type`\n const value = this.getAttribute(typeColumn)\n const related = (value ? this.newRelatedInstance(resolveMorphClass(String(value))) : this.newInstance()) as unknown as R\n return new MorphTo<R, this>(related, this, id ?? `${name}_id`, typeColumn, ownerKey, name)\n }\n\n /** The value stored in *_type columns for this model: its morph map alias, or its class name. */\n getMorphClass(): string {\n const cls = this.constructor as typeof Model\n return getMorphAlias(cls) ?? cls.name\n }\n\n /** The pivot row of a model loaded through belongsToMany (tag.pivot.getAttribute('created_at')). */\n get pivot(): Model | undefined {\n return this.relations.pivot as Model | undefined\n }\n\n /** A related model instance on this model's connection when it has none of its own. */\n protected newRelatedInstance<C extends typeof Model>(related: C): InstanceType<C> {\n const instance = new related() as InstanceType<C>\n if (!instance.getConnectionName()) instance.setConnection(this.getConnectionName())\n return instance\n }\n\n /** Calls the relation method `name` (post.comments()) and checks that it returns a relation. */\n getRelationInstance(name: string): Relation {\n if (name in Model.prototype) throw new RelationNotFoundError(this.constructor.name, name)\n const method = methodOf(this, name)\n const relation = method?.call(this)\n if (!(relation instanceof Relation)) throw new RelationNotFoundError(this.constructor.name, name)\n relation.relationName = name\n return relation\n }\n\n /**\n * A loaded relation, typed from the relation method: post.getRelation('author') is User | null,\n * post.getRelation('comments') is Collection<Comment>. Throws RelationNotLoadedError when it isn't loaded\n * (JavaScript can't lazy-load synchronously: use with(), load() or post.comments().get()).\n */\n getRelation<K extends RelationNames<this>>(name: K): RelationValue<this, K> {\n if (!Object.hasOwn(this.relations, name)) throw new RelationNotLoadedError(this.constructor.name, name)\n return this.relations[name] as RelationValue<this, K>\n }\n\n /** Eager loads relations onto this model: await post.load('comments.author'). */\n async load(...relations: EagerLoadSpec[]): Promise<this> {\n await this.newQueryWithoutRelationships().with(...relations).eagerLoadRelations([this])\n return this\n }\n\n /** Loads only the relations that aren't loaded yet (nested paths are followed into loaded relations). */\n async loadMissing(...relations: string[]): Promise<this> {\n await loadMissingOn([this], relations)\n return this\n }\n\n /** Loads <relation>_count attributes: await post.loadCount('comments'). */\n async loadCount(...relations: EagerLoadSpec[]): Promise<this> {\n const row = await this.newQueryWithoutRelationships()\n .whereKey(this.getKey())\n .select(this.getKeyName() as Column<this>)\n .withCount(...relations)\n .first()\n if (row) {\n const counts = Object.fromEntries(Object.entries(row.getAttributes()).filter(([key]) => key !== this.getKeyName()))\n this.forceFill(counts).syncOriginalAttributes(...Object.keys(counts))\n }\n return this\n }\n\n // ---------------------------------------------------------------- relations storage\n\n /** Stores a loaded relation (eager loading and load() use this). */\n setRelation(name: string, value: unknown): this {\n this.relations[name] = value\n return this\n }\n\n relationLoaded(name: string): boolean {\n return Object.hasOwn(this.relations, name)\n }\n\n unsetRelation(name: string): this {\n delete this.relations[name]\n return this\n }\n\n getRelations(): Record<string, unknown> {\n return { ...this.relations }\n }\n\n // ---------------------------------------------------------------- serialization\n\n getHidden(): string[] {\n return [...this.hidden]\n }\n\n setHidden(hidden: string[]): this {\n this.hidden = [...hidden]\n return this\n }\n\n getVisible(): string[] {\n return [...this.visible]\n }\n\n setVisible(visible: string[]): this {\n this.visible = [...visible]\n return this\n }\n\n /** Hides attributes for this instance only. */\n makeHidden(...attributes: Array<string | string[]>): this {\n const names = attributes.flat()\n this.hidden = [...new Set([...this.hidden, ...names])]\n this.visible = this.visible.filter((name) => !names.includes(name))\n return this\n }\n\n /** Un-hides attributes for this instance only. */\n makeVisible(...attributes: Array<string | string[]>): this {\n const names = attributes.flat()\n this.hidden = this.hidden.filter((name) => !names.includes(name))\n if (this.visible.length) this.visible = [...new Set([...this.visible, ...names])]\n return this\n }\n\n getAppends(): string[] {\n return [...this.appends]\n }\n\n setAppends(appends: string[]): this {\n this.appends = [...appends]\n return this\n }\n\n /** Adds accessor-only attributes to the serialized form of this instance. */\n append(...attributes: Array<string | string[]>): this {\n this.appends = [...new Set([...this.appends, ...attributes.flat()])]\n return this\n }\n\n /** Attributes (through accessors and casts, dates as ISO strings), appends and loaded relations, minus hidden ones. */\n toArray(): Row {\n return { ...this.attributesToArray(), ...this.relationsToArray() }\n }\n\n toJSON(): Row {\n return this.toArray()\n }\n\n attributesToArray(): Row {\n const casts = this.getCasts()\n const result: Row = {}\n for (const [key, raw] of Object.entries(this.arrayable(this.getAttributes()))) {\n const accessor = this.mutatorFor('get', key)\n if (accessor) result[key] = this.serializeValue(accessor.call(this, raw))\n else if (casts[key] !== undefined) result[key] = this.serializeValue(this.castAttribute(key, raw))\n else result[key] = raw\n }\n for (const key of this.appends) {\n if (this.isArrayableKey(key)) result[key] = this.serializeValue(this.getAttribute(key))\n }\n return result\n }\n\n /** Loaded relations under their snake_case names: a model → its array, a collection → an array of arrays. */\n relationsToArray(): Row {\n const result: Row = {}\n for (const [name, value] of Object.entries(this.relations)) {\n const key = Str.snake(name)\n if (!this.isArrayableKey(key)) continue\n if (value === null || value === undefined) result[key] = null\n else if (value instanceof Collection) result[key] = value.toArray()\n else if (typeof (value as { toArray?: unknown }).toArray === 'function') result[key] = (value as { toArray(): unknown }).toArray()\n else result[key] = value\n }\n return result\n }\n\n protected serializeValue(value: unknown): unknown {\n if (value instanceof Date) return serializeDate(value)\n if (value instanceof Collection) return value.toArray()\n return value\n }\n\n private isArrayableKey(key: string): boolean {\n if (this.visible.length && !this.visible.includes(key)) return false\n return !this.hidden.includes(key)\n }\n\n private arrayable(values: Row): Row {\n return Object.fromEntries(Object.entries(values).filter(([key]) => this.isArrayableKey(key)))\n }\n}\n\nsetModelBaseClass(Model)\n\n/** Eager loads relations onto models you already have (Laravel's $collection->load()). */\nexport async function loadRelations<M extends Model>(models: Iterable<M>, ...relations: EagerLoadSpec[]): Promise<M[]> {\n const list = [...models]\n if (!list.length) return list\n await list[0]!.newQueryWithoutRelationships().with(...relations).eagerLoadRelations(list)\n return list\n}\n\nasync function loadMissingOn(models: Model[], paths: string[]): Promise<void> {\n for (const path of paths) {\n const [head = '', ...rest] = path.split('.')\n const missing = models.filter((model) => !model.relationLoaded(head))\n if (missing.length) await loadRelations(missing, path)\n if (!rest.length) continue\n const related = models.flatMap((model) => {\n const value = model.getRelations()[head]\n if (value instanceof Collection) return value.all() as Model[]\n return value instanceof Model ? [value] : []\n })\n if (related.length) await loadMissingOn(related, [rest.join('.')])\n }\n}\n\n/** A row of a belongsToMany pivot table, available as related.pivot (unguarded, no key, no timestamps by default). */\nexport class Pivot extends Model {\n protected override guarded: string[] = []\n override incrementing = false\n override timestamps = false\n}\n","import type { Operator, Row } from '@orieljs/contracts'\nimport { Collection } from '@orieljs/collections'\nimport { Str } from '@orieljs/support'\nimport { ModelNotFoundError, QueryError } from '../errors'\nimport { Builder as QueryBuilder, type ColumnRef, type Direction, type Where } from '../Query/Builder'\nimport type { Expression } from '../Query/Expression'\nimport { formatDateTime } from '../Query/values'\nimport type { Model } from './Model'\nimport { withoutRelationConstraints } from './Relations/constraints'\nimport type { Relation } from './Relations/Relation'\nimport type { GlobalScope } from './Scope'\nimport { SoftDeletingScope } from './SoftDeletingScope'\nimport type { Column } from './types'\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyRelation = Relation<any, any, any>\n/** A constraint on an eager load, withCount() or whereHas(): (query) => query.where(…). */\nexport type RelationConstraint = (query: AnyRelation) => unknown\n/** with('author'), with(['author', 'comments.user']), with({ comments: (q) => q.latest() }), with('author:id,name'). */\nexport type EagerLoadSpec = string | string[] | Record<string, RelationConstraint>\n\ntype AnyFunction = (...args: unknown[]) => unknown\n\n/** Unknown properties of an Eloquent builder resolve to the model's local scopes: query.published() → scopePublished. */\nconst handler: ProxyHandler<Builder<Model>> = {\n get(target, key, receiver) {\n if (typeof key === 'symbol' || key in target) return Reflect.get(target, key, receiver)\n const scope = target.localScope(key)\n if (!scope) return undefined\n return (...args: unknown[]) => (receiver as Builder<Model>).callScope((query) => scope.call(target.model.constructor, query, ...args))\n },\n}\n\n/** Unique-constraint violations on each driver (createOrFirst()). */\nfunction isUniqueViolation(error: unknown): boolean {\n const cause = (error instanceof QueryError ? error.cause : error) as { code?: unknown; errno?: unknown; message?: unknown } | undefined\n return cause?.code === '23505' || cause?.errno === 1062 || cause?.code === 'ER_DUP_ENTRY' ||\n /UNIQUE constraint failed/.test(String(cause?.message ?? ''))\n}\n\n/**\n * Eloquent's builder: the query builder of one model class. Rows come back as hydrated models, global scopes are\n * applied when the query runs (grouped so an orWhere can't escape them), and unknown methods call the model's local\n * scopes. Everything the query builder does (pagination, chunk, lazy, …) returns models here.\n */\nexport class Builder<M extends Model = Model> extends QueryBuilder<M> {\n readonly model: M\n protected scopes = new Map<string, GlobalScope>()\n protected removedScopes: string[] = []\n protected eagerLoad = new Map<string, RelationConstraint | undefined>()\n\n constructor(model: M) {\n super(model.getConnection(), model.getTable())\n this.model = model\n return new Proxy(this, handler as ProxyHandler<this>)\n }\n\n getModel(): M {\n return this.model\n }\n\n // ---------------------------------------------------------------- scopes\n\n /** The model class's static scope<Name> method for a builder method name, if any. */\n localScope(name: string): AnyFunction | undefined {\n const scope: unknown = Reflect.get(this.model.constructor, `scope${Str.studly(name)}`)\n return typeof scope === 'function' ? (scope as AnyFunction) : undefined\n }\n\n /** Runs a scope; the wheres it adds are grouped when they contain an \"or\" (Laravel's callScope). */\n callScope(scope: (query: this) => unknown): this {\n const before = this.wheres.length\n const result = scope(this)\n if (this.wheres.length > before) this.addNewWheresWithinGroup(before)\n return result === undefined || result === null ? this : (result as this)\n }\n\n withGlobalScope(name: string, scope: GlobalScope): this {\n this.scopes.set(name, scope)\n return this\n }\n\n /** Removes a global scope by name or Scope class. */\n withoutGlobalScope(scope: string | (abstract new (...args: never[]) => unknown)): this {\n const name = typeof scope === 'string' ? scope : scope.name\n this.removedScopes.push(name)\n this.scopes.delete(name)\n return this\n }\n\n /** Removes every global scope, or the given ones. */\n withoutGlobalScopes(scopes?: Array<string | (abstract new (...args: never[]) => unknown)>): this {\n if (!scopes) {\n this.removedScopes.push(...this.scopes.keys())\n this.scopes.clear()\n } else {\n for (const scope of scopes) this.withoutGlobalScope(scope)\n }\n return this\n }\n\n removedScopeNames(): string[] {\n return [...this.removedScopes]\n }\n\n /** A copy of this query with every global scope applied (Laravel's applyScopes()). */\n applyScopes(): this {\n if (!this.scopes.size) return this\n const query = this.clone() as this\n for (const scope of this.scopes.values()) {\n query.callScope((builder) => (typeof scope === 'function' ? scope(builder) : scope.apply(builder, this.model)))\n }\n query.scopes = new Map()\n return query\n }\n\n /** Groups [0, count) and [count, …) separately when either contains an \"or\", so scopes combine with \"and\". */\n protected addNewWheresWithinGroup(count: number): void {\n const all = this.wheres\n this.wheres = []\n this.groupWhereSlice(all.slice(0, count))\n this.groupWhereSlice(all.slice(count))\n }\n\n private groupWhereSlice(slice: Where[]): void {\n if (!slice.length) return\n if (slice.some((where) => where.boolean === 'or')) {\n const nested = new QueryBuilder<Row>(this.connection)\n nested.wheres = slice\n this.wheres.push({ type: 'nested', query: nested, not: false, boolean: slice[0]!.boolean })\n } else {\n this.wheres.push(...slice)\n }\n }\n\n // ---------------------------------------------------------------- typed constraints (Column<M> names)\n\n override where(column: Column<M> | Expression, value: unknown): this\n override where(column: Column<M> | Expression, operator: Operator | string, value: unknown): this\n override where(conditions: Row): this\n override where(callback: (query: this) => unknown): this\n override where(...args: unknown[]): this {\n return Reflect.apply(QueryBuilder.prototype.where, this, args) as this\n }\n\n override orWhere(column: Column<M> | Expression, value: unknown): this\n override orWhere(column: Column<M> | Expression, operator: Operator | string, value: unknown): this\n override orWhere(conditions: Row): this\n override orWhere(callback: (query: this) => unknown): this\n override orWhere(...args: unknown[]): this {\n return Reflect.apply(QueryBuilder.prototype.orWhere, this, args) as this\n }\n\n override whereIn(column: Column<M> | Expression, values: readonly unknown[] | QueryBuilder<unknown>): this {\n return super.whereIn(column, values)\n }\n\n override whereNotIn(column: Column<M> | Expression, values: readonly unknown[] | QueryBuilder<unknown>): this {\n return super.whereNotIn(column, values)\n }\n\n override whereNull(columns: Column<M> | Expression | Array<Column<M> | Expression>): this {\n return super.whereNull(columns)\n }\n\n override whereNotNull(columns: Column<M> | Expression | Array<Column<M> | Expression>): this {\n return super.whereNotNull(columns)\n }\n\n override whereBetween(column: Column<M> | Expression, values: readonly [unknown, unknown]): this {\n return super.whereBetween(column, values)\n }\n\n override orderBy(column: Column<M> | Expression, direction: Direction | Uppercase<Direction> = 'asc'): this {\n return super.orderBy(column, direction)\n }\n\n /** Newest first by the model's created_at column (or the given one). */\n override latest(column?: Column<M> | Expression): this {\n return super.latest(column ?? this.model.getCreatedAtColumn() ?? 'created_at')\n }\n\n override oldest(column?: Column<M> | Expression): this {\n return super.oldest(column ?? this.model.getCreatedAtColumn() ?? 'created_at')\n }\n\n override select(...columns: Array<Column<M> | Expression | Array<Column<M> | Expression>>): this {\n return super.select(...columns)\n }\n\n /** where key = id (or key in ids). */\n whereKey(id: unknown): this {\n if (Array.isArray(id)) return super.whereIn(this.model.getQualifiedKeyName(), id)\n return super.where(this.model.getQualifiedKeyName(), '=', id)\n }\n\n whereKeyNot(id: unknown): this {\n if (Array.isArray(id)) return super.whereNotIn(this.model.getQualifiedKeyName(), id)\n return super.where(this.model.getQualifiedKeyName(), '!=', id)\n }\n\n // ---------------------------------------------------------------- reading\n\n /** Runs the query, hydrates models, fires their retrieved events and eager loads the with() relations. */\n override async runSelect(): Promise<M[]> {\n const query = this.applyScopes()\n const rows = (await QueryBuilder.prototype.runSelect.call(query)) as unknown as Row[]\n const models = this.hydrate(rows)\n if (models.length && this.model.hasModelListeners('retrieved')) {\n for (const model of models) await model.fireModelEvent('retrieved', false)\n }\n if (models.length && this.eagerLoad.size) await this.eagerLoadRelations(models)\n return models\n }\n\n // ---------------------------------------------------------------- eager loading\n\n /**\n * Relations to load with the results, one query per relation (and per nesting level):\n * with('author'), with('comments.author'), with({ comments: (q) => q.where('approved', true) }), with('author:id,name').\n */\n with(...relations: EagerLoadSpec[]): this {\n for (const spec of relations) {\n if (typeof spec === 'string') this.addEagerLoad(spec, undefined)\n else if (Array.isArray(spec)) for (const name of spec) this.addEagerLoad(name, undefined)\n else for (const [name, constraint] of Object.entries(spec)) this.addEagerLoad(name, constraint)\n }\n return this\n }\n\n /** Removes eager loads (including the model's default `with`). */\n without(...relations: string[]): this {\n for (const name of relations) {\n for (const key of [...this.eagerLoad.keys()]) if (key === name || key.startsWith(`${name}.`)) this.eagerLoad.delete(key)\n }\n return this\n }\n\n getEagerLoads(): Map<string, RelationConstraint | undefined> {\n return new Map(this.eagerLoad)\n }\n\n /** Loads every top-level with() relation onto the models (nested ones are passed down to each relation query). */\n async eagerLoadRelations(models: M[]): Promise<M[]> {\n for (const [name, constraint] of this.eagerLoad) {\n if (!name.includes('.')) await this.eagerLoadRelation(models, name, constraint)\n }\n return models\n }\n\n /** The relation instance for a name, without its per-parent constraints. */\n getRelation(name: string): AnyRelation {\n return withoutRelationConstraints(() => this.model.newInstance().getRelationInstance(name))\n }\n\n protected async eagerLoadRelation(models: M[], name: string, constraint: RelationConstraint | undefined): Promise<void> {\n const relation = this.getRelation(name)\n relation.addEagerConstraints(models)\n constraint?.(relation)\n const nested = this.relationsNestedUnder(name)\n if (Object.keys(nested).length) relation.with(nested)\n relation.initRelation(models, name)\n relation.match(models, (await relation.getEager()).all(), name)\n }\n\n private addEagerLoad(spec: string, constraint: RelationConstraint | undefined): void {\n const [path = '', columns] = spec.split(':')\n const name = path.trim()\n let callback = constraint\n if (columns) {\n const selected = columns.split(',').map((column) => column.trim())\n callback = (query) => {\n query.select(...selected)\n constraint?.(query)\n }\n }\n const segments = name.split('.')\n for (let i = 1; i < segments.length; i++) {\n const parent = segments.slice(0, i).join('.')\n if (!this.eagerLoad.has(parent)) this.eagerLoad.set(parent, undefined)\n }\n this.eagerLoad.set(name, callback)\n }\n\n private relationsNestedUnder(name: string): Record<string, RelationConstraint> {\n const nested: Record<string, RelationConstraint> = {}\n for (const [key, constraint] of this.eagerLoad) {\n if (key.startsWith(`${name}.`)) nested[key.slice(name.length + 1)] = constraint ?? (() => undefined)\n }\n return nested\n }\n\n // ---------------------------------------------------------------- relation counts and existence\n\n /**\n * Adds `<relation>_count` columns: withCount('comments'), withCount({ comments: (q) => q.where('approved', true) }),\n * withCount('comments as approved_count'). Global scopes of the related model (soft deletes) apply.\n */\n withCount(...relations: EagerLoadSpec[]): this {\n if (!this.columns.length) this.columns = [`${this.model.getTable()}.*`]\n for (const [spec, constraint] of this.normalizeRelationSpecs(relations)) {\n const [name = '', alias] = spec.split(/\\s+as\\s+/i)\n const relation = this.getRelation(name.trim())\n const query = relation.getRelationExistenceCountQuery(relation.getRelated().newQueryWithoutRelationships(), this)\n query.wheres.push(...relation.wheres)\n if (constraint) query.callScope((q) => constraint(q as unknown as AnyRelation))\n this.selectSub(query.applyScopes(), alias?.trim() ?? `${Str.snake(name.trim())}_count`)\n }\n return this\n }\n\n /**\n * Rows that have related rows: has('comments'), has('comments', '>=', 3), has('comments.author').\n * Uses `exists (…)` for the common \"at least one\"/\"none\" cases and a count subquery otherwise.\n */\n has(relation: string, operator = '>=', count = 1, boolean: 'and' | 'or' = 'and', callback?: RelationConstraint): this {\n if (relation.includes('.')) return this.hasNested(relation, operator, count, boolean, callback)\n const instance = this.getRelation(relation)\n const useExists = (operator === '>=' || operator === '<') && count === 1\n const query = useExists\n ? instance.getRelationExistenceQuery(instance.getRelated().newQueryWithoutRelationships(), this)\n : instance.getRelationExistenceCountQuery(instance.getRelated().newQueryWithoutRelationships(), this)\n query.wheres.push(...instance.wheres)\n if (callback) query.callScope((q) => callback(q as unknown as AnyRelation))\n const scoped = query.applyScopes()\n if (useExists) return this.whereExists(scoped, boolean, operator === '<')\n return this.whereSub(scoped, operator, count, boolean)\n }\n\n orHas(relation: string, operator = '>=', count = 1): this {\n return this.has(relation, operator, count, 'or')\n }\n\n doesntHave(relation: string, boolean: 'and' | 'or' = 'and', callback?: RelationConstraint): this {\n return this.has(relation, '<', 1, boolean, callback)\n }\n\n orDoesntHave(relation: string): this {\n return this.doesntHave(relation, 'or')\n }\n\n /** Rows with related rows matching the callback: whereHas('comments', (q) => q.where('approved', true)). */\n whereHas(relation: string, callback?: RelationConstraint, operator = '>=', count = 1): this {\n return this.has(relation, operator, count, 'and', callback)\n }\n\n orWhereHas(relation: string, callback?: RelationConstraint, operator = '>=', count = 1): this {\n return this.has(relation, operator, count, 'or', callback)\n }\n\n whereDoesntHave(relation: string, callback?: RelationConstraint): this {\n return this.doesntHave(relation, 'and', callback)\n }\n\n orWhereDoesntHave(relation: string, callback?: RelationConstraint): this {\n return this.doesntHave(relation, 'or', callback)\n }\n\n /** has('comments.author'): whereHas('comments', q => q.has('author')) */\n private hasNested(relation: string, operator: string, count: number, boolean: 'and' | 'or', callback?: RelationConstraint): this {\n const [first = '', ...rest] = relation.split('.')\n return this.has(first, '>=', 1, boolean, (query) => {\n query.has(rest.join('.'), operator, count, 'and', callback)\n })\n }\n\n private normalizeRelationSpecs(relations: EagerLoadSpec[]): Array<[string, RelationConstraint | undefined]> {\n const specs: Array<[string, RelationConstraint | undefined]> = []\n for (const spec of relations) {\n if (typeof spec === 'string') specs.push([spec, undefined])\n else if (Array.isArray(spec)) for (const name of spec) specs.push([name, undefined])\n else specs.push(...Object.entries(spec))\n }\n return specs\n }\n\n /** Models from raw rows, marked as existing. */\n hydrate(rows: readonly Row[]): M[] {\n return rows.map((row) => this.model.newFromBuilder(row) as M)\n }\n\n override async aggregate(fn: 'count' | 'min' | 'max' | 'sum' | 'avg', column: ColumnRef): Promise<unknown> {\n return QueryBuilder.prototype.aggregate.call(this.applyScopes(), fn, column)\n }\n\n override async exists(): Promise<boolean> {\n return QueryBuilder.prototype.exists.call(this.applyScopes())\n }\n\n /** The column's values, through the model's casts and accessors. */\n override async pluck<V = unknown>(column: Column<M>): Promise<Collection<V>> {\n const query = this.applyScopes().clone()\n const rows = (await QueryBuilder.prototype.runSelect.call(query.select(column))) as unknown as Row[]\n const key = column.includes('.') ? column.slice(column.lastIndexOf('.') + 1) : column\n return new Collection(rows.map((row) => this.model.newInstance().setRawAttributes({ [key]: row[key] }).getAttribute<V>(key)))\n }\n\n override async find(id: unknown): Promise<M | undefined> {\n return this.clone().whereKey(id).first()\n }\n\n async findMany(ids: readonly unknown[]): Promise<Collection<M>> {\n if (!ids.length) return new Collection<M>()\n return this.clone().whereKey([...ids]).get()\n }\n\n /** find(), or ModelNotFoundError (a 404). With an array, every id must exist. */\n async findOrFail(ids: readonly unknown[]): Promise<Collection<M>>\n async findOrFail(id: unknown): Promise<M>\n async findOrFail(id: unknown): Promise<M | Collection<M>> {\n if (Array.isArray(id)) {\n const models = await this.findMany(id)\n if (models.count() !== new Set(id.map(String)).size) throw new ModelNotFoundError(this.model.constructor.name, id)\n return models\n }\n const model = await this.find(id)\n if (!model) throw new ModelNotFoundError(this.model.constructor.name, [id])\n return model\n }\n\n async findOr<R>(id: unknown, callback: () => R | Promise<R>): Promise<M | R> {\n return (await this.find(id)) ?? callback()\n }\n\n async firstOrFail(): Promise<M> {\n const model = await this.first()\n if (!model) throw new ModelNotFoundError(this.model.constructor.name)\n return model\n }\n\n async firstOr<R>(callback: () => R | Promise<R>): Promise<M | R> {\n return (await this.first()) ?? callback()\n }\n\n async firstWhere(column: Column<M> | Expression, operatorOrValue: unknown, value?: unknown): Promise<M | undefined> {\n const query = this.clone()\n return (value === undefined ? query.where(column, operatorOrValue) : query.where(column, String(operatorOrValue), value)).first()\n }\n\n // ---------------------------------------------------------------- creating and updating\n\n /** A new, unsaved model of this query's class (mass assignment rules apply). */\n newModelInstance(attributes: Row = {}): M {\n return this.model.newInstance(attributes) as M\n }\n\n make(attributes: Row = {}): M {\n return this.newModelInstance(attributes)\n }\n\n async create(attributes: Row = {}): Promise<M> {\n const model = this.newModelInstance(attributes)\n await model.save()\n return model\n }\n\n /** Creates without mass assignment protection. Never pass it request input. */\n async forceCreate(attributes: Row): Promise<M> {\n const model = this.newModelInstance().forceFill(attributes)\n await model.save()\n return model\n }\n\n /** The first match, or a new unsaved model with attributes + values. */\n async firstOrNew(attributes: Row, values: Row = {}): Promise<M> {\n return (await this.clone().where(attributes).first()) ?? this.newModelInstance({ ...attributes, ...values })\n }\n\n /** The first match, or a new saved model. A concurrent insert of the same unique key returns that row instead. */\n async firstOrCreate(attributes: Row, values: Row = {}): Promise<M> {\n return (await this.clone().where(attributes).first()) ?? this.createOrFirst(attributes, values)\n }\n\n /** Tries to create; on a unique constraint violation, returns the existing row (Laravel's createOrFirst()). */\n async createOrFirst(attributes: Row, values: Row = {}): Promise<M> {\n try {\n const connection = this.connection\n const create = () => this.create({ ...attributes, ...values })\n // A failed insert aborts a Postgres transaction, so run it in a savepoint when one is open.\n return connection.transactionLevel() > 0 ? await connection.transaction(create) : await create()\n } catch (error) {\n if (!isUniqueViolation(error)) throw error\n const existing = await this.clone().where(attributes).first()\n if (!existing) throw error\n return existing\n }\n }\n\n /** Updates the first match with values, or creates it. */\n async updateOrCreate(attributes: Row, values: Row = {}): Promise<M> {\n const model = await this.firstOrCreate(attributes, values)\n if (!model.wasRecentlyCreated) await model.fill(values).save()\n return model\n }\n\n /** Mass update (no model events); sets updated_at when the model uses timestamps. */\n override async update(values: Row): Promise<number> {\n return QueryBuilder.prototype.update.call(this.applyScopes(), this.addUpdatedAtColumn(values))\n }\n\n /** Mass delete (no model events). With soft deletes this sets deleted_at on the matching rows instead. */\n override async delete(): Promise<number> {\n if (this.model.usesSoftDeletes()) {\n return this.update({ [this.model.getDeletedAtColumn()]: formatDateTime(this.model.freshTimestamp()) })\n }\n return this.forceDelete()\n }\n\n /** Deletes the matching rows for real, even with soft deletes. */\n async forceDelete(): Promise<number> {\n return QueryBuilder.prototype.delete.call(this.applyScopes())\n }\n\n // ---------------------------------------------------------------- soft deletes\n\n /** Includes soft-deleted rows (withTrashed(false) is withoutTrashed()). */\n withTrashed(withTrashed = true): this {\n return withTrashed ? this.withoutGlobalScope(SoftDeletingScope) : this.withoutTrashed()\n }\n\n /** Excludes soft-deleted rows explicitly. */\n withoutTrashed(): this {\n return super.whereNull(this.model.getQualifiedDeletedAtColumn()).withoutGlobalScope(SoftDeletingScope)\n }\n\n /** Only soft-deleted rows. */\n onlyTrashed(): this {\n return super.whereNotNull(this.model.getQualifiedDeletedAtColumn()).withoutGlobalScope(SoftDeletingScope)\n }\n\n /** Restores every matching row (deleted_at = null), trashed or not. */\n async restore(): Promise<number> {\n return this.withTrashed().update({ [this.model.getDeletedAtColumn()]: null })\n }\n\n protected addUpdatedAtColumn(values: Row): Row {\n const column = this.model.getUpdatedAtColumn()\n if (!this.model.usesTimestamps() || !column || Object.hasOwn(values, column)) return values\n return { ...values, [column]: formatDateTime(this.model.freshTimestamp()) }\n }\n\n // ---------------------------------------------------------------- plumbing\n\n override toSql(): string {\n return QueryBuilder.prototype.toSql.call(this.applyScopes())\n }\n\n override getBindings(): unknown[] {\n return QueryBuilder.prototype.getBindings.call(this.applyScopes())\n }\n\n override clone(): Builder<M> {\n const copy = super.clone() as Builder<M>\n copy.scopes = new Map(this.scopes)\n copy.removedScopes = [...this.removedScopes]\n copy.eagerLoad = new Map(this.eagerLoad)\n return new Proxy(copy, handler as ProxyHandler<Builder<M>>)\n }\n\n /** Nested where groups get a builder of the same model (without global scopes), so local scopes work inside them. */\n override newQuery(): QueryBuilder<Row> {\n return this.model.newModelQuery() as unknown as QueryBuilder<Row>\n }\n\n /** chunk() and lazy() order by the primary key when the query has no order. */\n protected override enforceOrderBy(): void {\n if (!this.orders.length) this.orderBy(this.model.getQualifiedKeyName() as Column<M>, 'asc')\n }\n\n protected override defaultKeyName(): string {\n return this.model.getKeyName()\n }\n\n protected override defaultPerPage(): number {\n return this.model.getPerPage()\n }\n}\n","/**\n * While eager loading, relation methods are called only to learn the relation's shape, so their per-parent\n * constraints (where post_id = ?) must be skipped (Laravel's Relation::noConstraints()). Relation methods are\n * synchronous, so a counter is enough.\n */\nlet disabled = 0\n\nexport function withoutRelationConstraints<T>(fn: () => T): T {\n disabled++\n try {\n return fn()\n } finally {\n disabled--\n }\n}\n\nexport const relationConstraintsEnabled = (): boolean => disabled === 0\n","import type { Builder } from './Builder'\nimport type { Model } from './Model'\nimport type { Scope } from './Scope'\n\n/**\n * Hides soft-deleted rows: where deleted_at is null. Registered for every model with `softDeletes = true`.\n * Builder.withTrashed()/onlyTrashed()/withoutTrashed() remove or replace it.\n */\nexport class SoftDeletingScope implements Scope {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n apply(builder: Builder<any>, model: Model): void {\n builder.whereNull(model.getQualifiedDeletedAtColumn())\n }\n}\n","import { isDeepStrictEqual } from 'node:util'\nimport type { Row } from '@orieljs/contracts'\nimport { Collection } from '@orieljs/collections'\nimport { InvalidCastError, LogicError } from '../errors'\nimport { formatDate, formatDateTime, parseDateTime } from '../Query/values'\n\n/**\n * A custom cast (Laravel's CastsAttributes): get() turns the stored value into what the model exposes, set() turns\n * an assigned value back into what is stored.\n */\nexport interface CastsAttributes<TGet = unknown, TSet = TGet> {\n get(model: object, key: string, value: unknown, attributes: Row): TGet\n set(model: object, key: string, value: TSet, attributes: Row): unknown\n}\n\n/** A TypeScript enum object (string or numeric) used as a cast: casts = { status: PostStatus }. */\nexport type EnumLike = Record<string, string | number>\n\nexport type BuiltInCast =\n | 'int' | 'integer' | 'float' | 'double' | 'real' | 'string' | 'bool' | 'boolean'\n | 'array' | 'json' | 'object' | 'collection'\n | 'date' | 'datetime' | 'immutable_date' | 'immutable_datetime' | 'timestamp'\n | `decimal:${number}`\n\nexport type CastDefinition = BuiltInCast | EnumLike | CastsAttributes | (new () => CastsAttributes)\n\nconst JSON_CASTS = new Set(['array', 'json', 'object', 'collection'])\nconst DATE_CASTS = new Set(['date', 'datetime', 'immutable_date', 'immutable_datetime'])\nconst PRIMITIVE_CASTS = new Set(['int', 'integer', 'float', 'double', 'real', 'string', 'bool', 'boolean', 'timestamp'])\n\nconst isCustom = (cast: CastDefinition): cast is CastsAttributes =>\n typeof cast === 'object' && typeof (cast as Partial<CastsAttributes>).get === 'function' && typeof (cast as Partial<CastsAttributes>).set === 'function'\n\nconst isCustomClass = (cast: CastDefinition): cast is new () => CastsAttributes => typeof cast === 'function'\n\nconst isEnum = (cast: CastDefinition): cast is EnumLike => typeof cast === 'object' && !isCustom(cast)\n\n/** Builds the custom cast instance for a class-valued cast (cached per class). */\nconst instances = new WeakMap<new () => CastsAttributes, CastsAttributes>()\nfunction customCaster(cast: CastsAttributes | (new () => CastsAttributes)): CastsAttributes {\n if (!isCustomClass(cast)) return cast\n let instance = instances.get(cast)\n if (!instance) instances.set(cast, (instance = new cast()))\n return instance\n}\n\n/** The values of a TypeScript enum. Numeric enums also map values back to names; those reverse entries are skipped. */\nexport function enumValues(cast: EnumLike): Array<string | number> {\n return Object.entries(cast)\n .filter(([key]) => !/^\\d+$/.test(key))\n .map(([, value]) => value)\n}\n\nexport const isJsonCast = (cast: CastDefinition | undefined): boolean => typeof cast === 'string' && JSON_CASTS.has(cast)\nexport const isDateCast = (cast: CastDefinition | undefined): boolean => typeof cast === 'string' && DATE_CASTS.has(cast)\n/** A cast whose value is a class instance, so dirty checks and serialization go through custom logic. */\nexport const isCustomCast = (cast: CastDefinition | undefined): boolean => cast !== undefined && (isCustom(cast) || isCustomClass(cast))\n\nconst decimalPlaces = (cast: string): number | undefined => (cast.startsWith('decimal:') ? Number(cast.slice(8)) : undefined)\n\nconst isBuiltInCast = (cast: string): boolean =>\n JSON_CASTS.has(cast) || DATE_CASTS.has(cast) || PRIMITIVE_CASTS.has(cast) || /^decimal:\\d+$/.test(cast)\n\n/** Throws InvalidCastError for a cast string that isn't one of the built-in casts. */\nfunction assertBuiltInCast(cast: string, key: string, className: string): void {\n if (!isBuiltInCast(cast)) throw new InvalidCastError(className, key, cast)\n}\n\nconst toBoolean = (value: unknown): boolean => {\n if (typeof value === 'boolean') return value\n if (typeof value === 'number' || typeof value === 'bigint') return Number(value) !== 0\n const text = String(value).toLowerCase()\n return !(text === '' || text === '0' || text === 'f' || text === 'false')\n}\n\n/** Laravel's castAttribute(): the stored value → the value the model exposes. null stays null (except custom casts). */\nexport function castGet(model: object, key: string, cast: CastDefinition, value: unknown, attributes: Row, className: string): unknown {\n if (isCustom(cast) || isCustomClass(cast)) return customCaster(cast).get(model, key, value, attributes)\n if (typeof cast === 'string') assertBuiltInCast(cast, key, className)\n if (value === null || value === undefined) return value\n if (isEnum(cast)) {\n const allowed = enumValues(cast)\n const match = allowed.find((candidate) => candidate === value || String(candidate) === String(value))\n if (match === undefined) throw new LogicError(`\"${String(value)}\" is not a valid backing value for the cast of [${key}] on [${className}].`)\n return match\n }\n const places = decimalPlaces(cast)\n if (places !== undefined) return Number(value).toFixed(places)\n switch (cast) {\n case 'int': case 'integer':\n return Math.trunc(Number(value))\n case 'float': case 'double': case 'real':\n return Number(value)\n case 'string':\n return String(value)\n case 'bool': case 'boolean':\n return toBoolean(value)\n case 'array': case 'json': case 'object':\n // Postgres and MySQL drivers hand back json columns already parsed; copy them so the original stays intact.\n return typeof value === 'string' ? JSON.parse(value) : structuredClone(value)\n case 'collection':\n return new Collection((typeof value === 'string' ? JSON.parse(value) : structuredClone(value)) as unknown[])\n case 'date': case 'immutable_date': {\n const date = parseDateTime(value)\n date.setUTCHours(0, 0, 0, 0)\n return date\n }\n case 'datetime': case 'immutable_datetime':\n return parseDateTime(value)\n case 'timestamp':\n return Math.floor(parseDateTime(value).getTime() / 1000)\n }\n return value\n}\n\n/** The value assigned to a cast attribute → the value stored in the model's attributes (and later bound). */\nexport function castSet(model: object, key: string, cast: CastDefinition, value: unknown, attributes: Row, className: string): unknown {\n if (isCustom(cast) || isCustomClass(cast)) return customCaster(cast).set(model, key, value, attributes)\n if (typeof cast === 'string') assertBuiltInCast(cast, key, className)\n if (value === null || value === undefined) return null\n if (isEnum(cast)) return castGet(model, key, cast, value, attributes, className)\n if (typeof cast !== 'string') return value\n if (JSON_CASTS.has(cast)) return JSON.stringify(value instanceof Collection ? value.all() : value)\n if (cast === 'date' || cast === 'immutable_date') return formatDate(parseDateTime(value))\n if (cast === 'datetime' || cast === 'immutable_datetime') return formatDateTime(parseDateTime(value))\n if (cast === 'timestamp') return formatDateTime(typeof value === 'number' ? new Date(value * 1000) : parseDateTime(value))\n return value\n}\n\n/**\n * Laravel's originalIsEquivalent(): does the stored value still mean the same thing as the original?\n * Keeps save() from writing columns whose value only changed representation (1 vs true, '5' vs 5, same instant).\n */\nexport function isEquivalent(cast: CastDefinition | undefined, current: unknown, original: unknown, model: object, key: string, className: string): boolean {\n if (current === original) return true\n if (current === null || current === undefined || original === null || original === undefined) return false\n if (cast !== undefined) {\n if (isDateCast(cast) || cast === 'timestamp') {\n return parseDateTime(current).getTime() === parseDateTime(original).getTime()\n }\n if (typeof cast === 'string' && ['float', 'double', 'real'].includes(cast)) {\n return Math.abs(Number(current) - Number(original)) < Number.EPSILON * 4\n }\n const read = (value: unknown) => castGet(model, key, cast, value, {}, className)\n if (typeof cast === 'string' && (JSON_CASTS.has(cast) || PRIMITIVE_CASTS.has(cast) || cast.startsWith('decimal:'))) {\n const a = read(current)\n const b = read(original)\n return isDeepStrictEqual(a instanceof Collection ? a.all() : a, b instanceof Collection ? b.all() : b)\n }\n if (isEnum(cast)) return String(current) === String(original)\n }\n const numeric = (value: unknown) => (typeof value === 'number' || (typeof value === 'string' && value.trim() !== '' && !Number.isNaN(Number(value))))\n return numeric(current) && numeric(original) && Number(current) === Number(original)\n}\n","import { existsSync, readdirSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport type { Row } from '@orieljs/contracts'\nimport { Collection } from '@orieljs/collections'\nimport { Str } from '@orieljs/support'\nimport { LogicError } from '../../errors'\nimport { formatDateTime } from '../../Query/values'\nimport { Model } from '../Model'\nimport { BelongsTo } from '../Relations/BelongsTo'\nimport { BelongsToMany } from '../Relations/BelongsToMany'\nimport { HasOneOrMany } from '../Relations/HasOneOrMany'\nimport { MorphTo } from '../Relations/MorphTo'\n\ndeclare const MANY: unique symbol\n/** Type-level marker set by count(): make()/create() then return a Collection. */\nexport interface Many {\n readonly [MANY]: true\n}\n/** What make()/create() return: a model, or a Collection after count(). */\nexport type FactoryResult<F, M> = F extends Many ? Collection<M> : M\n/** What raw() returns: the attributes, or a list of them after count(). */\nexport type RawResult<F> = F extends Many ? Row[] : Row\n\n/** Which model a state is being made for: its index in count() and the total. */\nexport interface StateContext {\n index: number\n count: number\n}\nexport type State = Row | ((attributes: Row, context: StateContext) => Row)\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyFactory = Factory<any>\n\ninterface HasRelationship {\n factory: AnyFactory\n relationship: string\n pivot: Row\n}\n\ninterface ForRelationship {\n parent: AnyFactory | Model\n relationship: string\n resolved?: Model\n}\n\n/** The builder state newInstance() copies and changes. */\ninterface FactoryState<M extends Model> {\n countValue: number | undefined\n states: State[]\n hasRelations: HasRelationship[]\n forRelations: ForRelationship[]\n afterMakingCallbacks: Array<(model: M) => unknown>\n afterCreatingCallbacks: Array<(model: M) => unknown>\n}\n\nconst registry = new Map<typeof Model, new () => AnyFactory>()\n\n/**\n * Laravel's model factories: `class UserFactory extends Factory<User> { model = User; definition() { … } }`,\n * then `await User.factory().count(3).create()`, `UserFactory.new().unverified().make()`.\n * Every builder method returns a new factory, so a base factory can be reused.\n */\nexport abstract class Factory<M extends Model = Model> {\n /** The model class this factory makes. */\n abstract model: new () => M\n\n /** The default attributes. Values may be factories (created for their key) or (attributes) => value functions. */\n abstract definition(): Row\n\n protected countValue: number | undefined\n protected states: State[] = []\n protected hasRelations: HasRelationship[] = []\n protected forRelations: ForRelationship[] = []\n protected afterMakingCallbacks: Array<(model: M) => unknown> = []\n protected afterCreatingCallbacks: Array<(model: M) => unknown> = []\n\n /** A new factory with the given state (Laravel's Factory::new()). */\n static new<F extends AnyFactory>(this: new () => F, state?: State): F {\n const factory = new this().configure() as F\n return state ? factory.state(state) : factory\n }\n\n /** Registers factory classes for Model.factory() (discoverFactories() does this for database/factories). */\n static register(...factories: Array<new () => AnyFactory>): void {\n for (const factory of factories) registry.set(new factory().model as unknown as typeof Model, factory)\n }\n\n /** The registered factory for a model class. */\n static forModel<M extends Model>(model: new () => M): Factory<M> {\n const factory = registry.get(model as unknown as typeof Model)\n if (!factory) {\n throw new LogicError(`No factory registered for [${model.name}]. Add database/factories/${model.name}Factory.ts (default export) or call Factory.register().`)\n }\n return new factory().configure() as unknown as Factory<M>\n }\n\n /** Hook for afterMaking()/afterCreating() registrations; runs in new(). */\n configure(): this {\n return this\n }\n\n /** How many models make()/create() produce; they then return a Collection. */\n count(count: number): this & Many {\n return this.newInstance({ countValue: count }) as this & Many\n }\n\n /** Overrides attributes: state({ admin: true }) or state((attributes) => ({ … })). */\n state(state: State): this {\n return this.newInstance({ states: [...this.states, state] })\n }\n\n /** Cycles through states per model: sequence({ role: 'admin' }, { role: 'user' }). */\n sequence(...states: State[]): this {\n return this.state((attributes, context) => {\n const state = states[context.index % states.length]!\n return typeof state === 'function' ? state(attributes, context) : state\n })\n }\n\n /** deleted_at = now, for soft-deleting models. */\n trashed(): this {\n return this.state((_attributes) => ({ [new this.model().getDeletedAtColumn()]: formatDateTime(new Date()) }))\n }\n\n /** Creates related models for each created model: has(Post.factory().count(3)) (relationship default: 'posts'). */\n has(factory: AnyFactory, relationship?: string, pivot: Row = {}): this {\n const name = relationship ?? Str.camel(Str.plural(new factory.model().constructor.name))\n return this.newInstance({ hasRelations: [...this.hasRelations, { factory, relationship: name, pivot }] })\n }\n\n /** Sets a belongsTo parent: for(User.factory()) or for(user) (relationship default: 'user'). Created once. */\n for(parent: AnyFactory | Model, relationship?: string): this {\n const cls = parent instanceof Model ? parent.constructor : new parent.model().constructor\n return this.newInstance({ forRelations: [...this.forRelations, { parent, relationship: relationship ?? Str.camel(cls.name) }] })\n }\n\n afterMaking(callback: (model: M) => unknown): this {\n return this.newInstance({ afterMakingCallbacks: [...this.afterMakingCallbacks, callback] })\n }\n\n afterCreating(callback: (model: M) => unknown): this {\n return this.newInstance({ afterCreatingCallbacks: [...this.afterCreatingCallbacks, callback] })\n }\n\n /** The attributes only, without a model (a Row, or a Row[] after count()). */\n async raw(attributes: Row = {}): Promise<RawResult<this>> {\n const rows: Row[] = []\n for (let index = 0; index < (this.countValue ?? 1); index++) rows.push(await this.attributesFor(attributes, index))\n return (this.countValue === undefined ? rows[0]! : rows) as RawResult<this>\n }\n\n /** Unsaved models (afterMaking callbacks run). */\n async make(attributes: Row = {}): Promise<FactoryResult<this, M>> {\n const models = await this.makeModels(attributes)\n return this.result(models)\n }\n\n /** Saved models, with their has() relations (afterCreating callbacks run). */\n async create(attributes: Row = {}): Promise<FactoryResult<this, M>> {\n const models = await this.makeModels(attributes)\n for (const model of models) {\n await model.save()\n await this.createChildren(model)\n for (const callback of this.afterCreatingCallbacks) await callback(model)\n }\n return this.result(models)\n }\n\n async makeOne(attributes: Row = {}): Promise<M> {\n return (await this.newInstance({ countValue: undefined }).makeModels(attributes))[0]!\n }\n\n async createOne(attributes: Row = {}): Promise<M> {\n return (await this.newInstance({ countValue: undefined }).create(attributes)) as M\n }\n\n /** One model per record (or `count` models). */\n async createMany(records: number | Row[]): Promise<Collection<M>> {\n const list = typeof records === 'number' ? Array.from({ length: records }, () => ({})) : records\n const created: M[] = []\n for (const record of list) created.push(await this.createOne(record))\n return new Collection(created)\n }\n\n protected newInstance(changes: Partial<FactoryState<M>>): this {\n const copy = Object.create(Object.getPrototypeOf(this) as object) as this\n Object.assign(copy, this, changes)\n return copy\n }\n\n protected async makeModels(attributes: Row): Promise<M[]> {\n const models: M[] = []\n for (let index = 0; index < (this.countValue ?? 1); index++) {\n const model = new this.model().forceFill(await this.attributesFor(attributes, index))\n for (const callback of this.afterMakingCallbacks) await callback(model)\n models.push(model)\n }\n return models\n }\n\n /** definition() + states + overrides + for() parents, with factory and function values expanded. */\n protected async attributesFor(overrides: Row, index: number): Promise<Row> {\n const context: StateContext = { index, count: this.countValue ?? 1 }\n let attributes: Row = this.definition()\n for (const state of this.states) attributes = { ...attributes, ...(typeof state === 'function' ? state(attributes, context) : state) }\n attributes = { ...attributes, ...overrides }\n for (const parent of this.forRelations) Object.assign(attributes, await this.parentAttributes(parent))\n const expanded: Row = {}\n for (const [key, value] of Object.entries(attributes)) {\n if (value instanceof Factory) expanded[key] = (await value.createOne()).getKey()\n else if (value instanceof Model) expanded[key] = value.getKey()\n else if (typeof value === 'function') expanded[key] = (value as (attributes: Row) => unknown)(attributes)\n else expanded[key] = value\n }\n return expanded\n }\n\n private async parentAttributes(parent: ForRelationship): Promise<Row> {\n const resolved = (parent.resolved ??= parent.parent instanceof Model ? parent.parent : ((await parent.parent.createOne()) as Model))\n const relation = this.relationOn(new this.model(), parent.relationship)\n if (relation instanceof MorphTo) {\n return { [relation.getForeignKeyName()]: resolved.getKey(), [relation.getMorphType()]: resolved.getMorphClass() }\n }\n if (relation instanceof BelongsTo) return { [relation.getForeignKeyName()]: resolved.getAttribute(relation.getOwnerKeyName()) }\n throw new LogicError(`for() needs a belongsTo or morphTo relation; [${parent.relationship}] is neither.`)\n }\n\n private async createChildren(model: M): Promise<void> {\n for (const { factory, relationship, pivot } of this.hasRelations) {\n const relation = this.relationOn(model, relationship)\n if (relation instanceof BelongsToMany) {\n const related = await factory.create()\n await relation.attach(related instanceof Collection ? related.all() : related, pivot)\n } else if (relation instanceof HasOneOrMany) {\n const foreign: Row = { [relation.getForeignKeyName()]: relation.getParentKey() }\n if (relation.morph) foreign[relation.getMorphType()!] = relation.getMorphClass()\n await factory.state(foreign).create()\n } else {\n throw new LogicError(`has() needs a hasOne, hasMany, morphMany or belongsToMany relation; [${relationship}] is none of them.`)\n }\n }\n }\n\n private relationOn(model: Model, relationship: string) {\n return model.getRelationInstance(relationship)\n }\n\n private result(models: M[]): FactoryResult<this, M> {\n return (this.countValue === undefined ? models[0] : new Collection(models)) as FactoryResult<this, M>\n }\n}\n\n/** Imports every factory file in a directory and registers its exported Factory classes. */\nexport async function discoverFactories(path: string): Promise<void> {\n if (!existsSync(path)) return\n for (const file of readdirSync(path).sort()) {\n if (!/\\.(ts|js|mts|mjs)$/.test(file) || /\\.d\\.[mc]?ts$/.test(file)) continue\n const module = (await import(pathToFileURL(join(path, file)).href)) as Record<string, unknown>\n for (const exported of Object.values(module)) {\n if (typeof exported === 'function' && exported.prototype instanceof Factory) {\n Factory.register(exported as unknown as new () => AnyFactory)\n }\n }\n }\n}\n","import { Str } from '@orieljs/support'\nimport type { ColumnRef } from '../../Query/Builder'\nimport type { Builder } from '../Builder'\nimport type { Model } from '../Model'\nimport type { Column } from '../types'\nimport { Relation } from './Relation'\n\n/** post.author(): this model (the child) holds the related model's key. */\nexport class BelongsTo<R extends Model, P extends Model = Model> extends Relation<R, P, R | null> {\n /**\n * @param foreignKey the column on the child ('user_id')\n * @param ownerKey the key on the related model it points at ('id')\n */\n constructor(\n related: R,\n child: P,\n readonly foreignKey: string,\n readonly ownerKey: string,\n relationName?: string,\n ) {\n super(related, child)\n this.relationName = relationName\n this.init()\n }\n\n getChild(): P {\n return this.parent\n }\n\n getForeignKeyName(): string {\n return this.foreignKey\n }\n\n getQualifiedForeignKeyName(): string {\n return this.parent.qualifyColumn(this.foreignKey)\n }\n\n getOwnerKeyName(): string {\n return this.ownerKey\n }\n\n getQualifiedOwnerKeyName(): string {\n return this.model.qualifyColumn(this.ownerKey)\n }\n\n addConstraints(): void {\n this.where(this.getQualifiedOwnerKeyName() as Column<R>, '=', this.parent.getAttribute(this.foreignKey))\n }\n\n addEagerConstraints(models: P[]): void {\n this.whereIn(this.getQualifiedOwnerKeyName() as Column<R>, this.keysOf(models, this.foreignKey))\n }\n\n async getResults(): Promise<R | null> {\n const key = this.parent.getAttribute(this.foreignKey)\n if (key === null || key === undefined) return null\n return (await this.first()) ?? null\n }\n\n initRelation(models: P[], relation: string): P[] {\n for (const model of models) model.setRelation(relation, null)\n return models\n }\n\n match(models: P[], results: R[], relation: string): P[] {\n const owners = new Map(results.map((result) => [String(result.getAttribute(this.ownerKey)), result]))\n for (const model of models) model.setRelation(relation, owners.get(String(model.getAttribute(this.foreignKey))) ?? null)\n return models\n }\n\n /** Points the child at `model` (sets the foreign key and the loaded relation). Save the child afterwards. */\n associate(model: R | null): P {\n this.parent.setAttribute(this.foreignKey, model === null ? null : model.getAttribute(this.ownerKey))\n this.parent.setRelation(this.relationKey(), model)\n return this.parent\n }\n\n /** Clears the foreign key. Save the child afterwards. */\n dissociate(): P {\n return this.associate(null)\n }\n\n getRelationExistenceQuery(query: Builder<R>, _parentQuery: Builder<P>, columns: ColumnRef[] = ['*']): Builder<R> {\n return query.select(...(columns as Array<Column<R>>)).whereColumn(this.getQualifiedForeignKeyName(), '=', this.getQualifiedOwnerKeyName())\n }\n\n /** The loaded-relation name: the resolved name, else the related class in camelCase (author → pass it explicitly). */\n private relationKey(): string {\n return this.relationName ?? Str.camel(this.model.constructor.name)\n }\n}\n","import { ClassRegistry } from '@orieljs/contracts'\nimport { currentContainer } from '@orieljs/container'\nimport { LogicError } from '../../errors'\nimport type { Model } from '../Model'\n\nconst aliases = new Map<string, typeof Model>()\nconst booted = new Map<string, typeof Model>()\n/** The Model base class, handed over by Model.ts once it is defined (importing it here would be a circular import). */\nlet modelBase: typeof Model | undefined\n\nexport function setModelBaseClass(base: typeof Model): void {\n modelBase = base\n}\n\n/**\n * The morph map: the value stored in `*_type` columns for each model class (Laravel's Relation::morphMap()).\n * Without an entry the class name is stored ('Post'). Returns the current map.\n */\nexport function morphMap(map?: Record<string, typeof Model>, merge = true): Record<string, typeof Model> {\n if (map) {\n if (!merge) aliases.clear()\n for (const [alias, model] of Object.entries(map)) aliases.set(alias, model)\n }\n return Object.fromEntries(aliases)\n}\n\n/** The model class for a morph map alias, if mapped. */\nexport function getMorphedModel(alias: string): typeof Model | undefined {\n return aliases.get(alias)\n}\n\n/** The morph map alias of a class, if mapped. */\nexport function getMorphAlias(model: typeof Model): string | undefined {\n for (const [alias, candidate] of aliases) if (candidate === model) return alias\n return undefined\n}\n\n/** Remembers a booted model class by name, so morphTo can find it without a morph map entry. */\nexport function rememberModelClass(model: typeof Model): void {\n booted.set(model.name, model)\n}\n\n/** The class for a stored morph type: the morph map, then the ClassRegistry (discovered models), then booted models. */\nexport function resolveMorphClass(type: string): typeof Model {\n const mapped = aliases.get(type)\n if (mapped) return mapped\n const container = currentContainer()\n if (container?.bound(ClassRegistry)) {\n const registry = container.make(ClassRegistry)\n if (registry.has(type)) {\n const cls = registry.resolve(type)\n if (!modelBase || !(cls.prototype instanceof modelBase)) throw new LogicError(`Class [${type}] is not a model, so it can't be the type of a morphTo relation.`)\n return cls as unknown as typeof Model\n }\n }\n const known = booted.get(type)\n if (known) return known\n throw new LogicError(`Class [${type}] not found for a morphTo relation. Add it to Relation.morphMap().`)\n}\n","import type { Collection } from '@orieljs/collections'\nimport type { ColumnRef } from '../../Query/Builder'\nimport { Expression } from '../../Query/Expression'\nimport { Builder } from '../Builder'\nimport type { Model } from '../Model'\nimport { relationConstraintsEnabled } from './constraints'\nimport { getMorphedModel, morphMap } from './morphMap'\n\n/**\n * A relation is the related model's query builder, constrained to the parent: post.comments() is a\n * Builder<Comment> with `where comments.post_id = ?`, so every builder method (where, orderBy, paginate, a local\n * scope, …) works on it. Subclasses add eager loading (addEagerConstraints/initRelation/match) and the existence\n * queries behind has()/whereHas()/withCount().\n */\nexport abstract class Relation<R extends Model = Model, P extends Model = Model, Result = unknown> extends Builder<R> {\n /** The name the relation is loaded under (set when resolved by name, for eager loading and associate()). */\n relationName: string | undefined\n\n /** Laravel's Relation::morphMap(): { post: Post } stores 'post' instead of 'Post' in *_type columns. */\n static morphMap(map?: Record<string, typeof Model>, merge = true): Record<string, typeof Model> {\n return morphMap(map, merge)\n }\n\n static getMorphedModel(alias: string): typeof Model | undefined {\n return getMorphedModel(alias)\n }\n\n protected constructor(\n related: R,\n readonly parent: P,\n ) {\n super(related)\n related.registerGlobalScopes(this)\n related.registerDefaultEagerLoads(this)\n }\n\n getParent(): P {\n return this.parent\n }\n\n getRelated(): R {\n return this.model\n }\n\n /** Subclasses call this last in their constructor: adds the per-parent constraints unless eager loading. */\n protected init(): void {\n if (relationConstraintsEnabled()) this.addConstraints()\n }\n\n /** The constraints for one parent: where comments.post_id = post.id. */\n abstract addConstraints(): void\n\n /** The constraints for many parents: where comments.post_id in (…). */\n abstract addEagerConstraints(models: P[]): void\n\n /** Sets the empty value (null or an empty collection) on every parent. */\n abstract initRelation(models: P[], relation: string): P[]\n\n /** Distributes the eagerly loaded results to their parents. */\n abstract match(models: P[], results: R[], relation: string): P[]\n\n /** The relation's value for this parent (a model, null or a collection). */\n abstract getResults(): Promise<Result>\n\n /** The query of has()/whereHas(): related rows that belong to the outer query's current row. */\n abstract getRelationExistenceQuery(query: Builder<R>, parentQuery: Builder<P>, columns?: ColumnRef[]): Builder<R>\n\n /** Runs the eager query. */\n getEager(): Promise<Collection<R>> {\n return this.get()\n }\n\n /** select count(*) … for withCount() and has('comments', '>=', 3). */\n getRelationExistenceCountQuery(query: Builder<R>, parentQuery: Builder<P>): Builder<R> {\n return this.getRelationExistenceQuery(query, parentQuery, [new Expression('count(*)')])\n }\n\n /** The distinct non-null values of `key` on the models (the eager whereIn list). */\n protected keysOf(models: Model[], key: string): unknown[] {\n const seen = new Map<string, unknown>()\n for (const model of models) {\n const value = model.getAttribute(key)\n if (value !== null && value !== undefined) seen.set(String(value), value)\n }\n return [...seen.values()]\n }\n}\n","import type { Row } from '@orieljs/contracts'\nimport { Collection } from '@orieljs/collections'\nimport type { Builder as QueryBuilder, ColumnRef } from '../../Query/Builder'\nimport { formatDateTime } from '../../Query/values'\nimport { Builder } from '../Builder'\nimport { Pivot, type Model } from '../Model'\nimport type { Column } from '../types'\nimport { Relation } from './Relation'\n\n/** attach()/sync() accept ids, models, or { id: pivotAttributes }. */\nexport type PivotIds = unknown | readonly unknown[] | Record<string, Row>\n\nexport interface SyncChanges {\n attached: unknown[]\n detached: unknown[]\n updated: unknown[]\n}\n\n/**\n * Many-to-many through a pivot table: post.tags() → belongsToMany(Tag) over post_tag (post_id, tag_id).\n * Each related model carries its pivot row as `tag.pivot` (withPivot() adds columns, withTimestamps() the timestamps).\n */\nexport class BelongsToMany<R extends Model, P extends Model = Model> extends Relation<R, P, Collection<R>> {\n protected pivotColumns: string[] = []\n protected pivotTimestamps: [string, string] | undefined\n\n constructor(\n related: R,\n parent: P,\n readonly table: string,\n readonly foreignPivotKey: string,\n readonly relatedPivotKey: string,\n readonly parentKey: string,\n readonly relatedKey: string,\n ) {\n super(related, parent)\n this.join(this.table, this.model.qualifyColumn(this.relatedKey), '=', this.qualifyPivotColumn(this.relatedPivotKey))\n this.init()\n }\n\n qualifyPivotColumn(column: string): string {\n return column.includes('.') ? column : `${this.table}.${column}`\n }\n\n getTable(): string {\n return this.table\n }\n\n getForeignPivotKeyName(): string {\n return this.foreignPivotKey\n }\n\n getRelatedPivotKeyName(): string {\n return this.relatedPivotKey\n }\n\n getParentKey(): unknown {\n return this.parent.getAttribute(this.parentKey)\n }\n\n addConstraints(): void {\n this.where(this.qualifyPivotColumn(this.foreignPivotKey) as Column<R>, '=', this.getParentKey())\n }\n\n addEagerConstraints(models: P[]): void {\n this.whereIn(this.qualifyPivotColumn(this.foreignPivotKey) as Column<R>, this.keysOf(models, this.parentKey))\n }\n\n /** Extra pivot columns to load onto tag.pivot. */\n withPivot(...columns: Array<string | string[]>): this {\n this.pivotColumns.push(...columns.flat())\n return this\n }\n\n /** The pivot table has created_at/updated_at: they are set on attach() and loaded onto tag.pivot. */\n withTimestamps(createdAt = 'created_at', updatedAt = 'updated_at'): this {\n this.pivotTimestamps = [createdAt, updatedAt]\n return this.withPivot(createdAt, updatedAt)\n }\n\n wherePivot(column: string, operator: unknown, value?: unknown): this {\n const qualified = this.qualifyPivotColumn(column) as Column<R>\n return value === undefined ? this.where(qualified, operator) : this.where(qualified, String(operator), value)\n }\n\n wherePivotIn(column: string, values: readonly unknown[]): this {\n return this.whereIn(this.qualifyPivotColumn(column) as Column<R>, values)\n }\n\n /** Selects the related columns plus the pivot columns (as pivot_*), then moves those onto each model's pivot. */\n override async runSelect(): Promise<R[]> {\n const query = this.clone() as this\n if (!query.columns.length) query.columns = [`${this.model.getTable()}.*`]\n query.columns.push(...this.pivotSelectColumns())\n const models = (await Builder.prototype.runSelect.call(query)) as R[]\n for (const model of models) this.hydratePivot(model)\n return models\n }\n\n async getResults(): Promise<Collection<R>> {\n const key = this.getParentKey()\n return key === null || key === undefined ? new Collection<R>() : this.get()\n }\n\n initRelation(models: P[], relation: string): P[] {\n for (const model of models) model.setRelation(relation, new Collection<R>())\n return models\n }\n\n match(models: P[], results: R[], relation: string): P[] {\n const dictionary = new Map<string, R[]>()\n for (const result of results) {\n const key = String(result.pivot?.getAttribute(this.foreignPivotKey))\n const group = dictionary.get(key)\n if (group) group.push(result)\n else dictionary.set(key, [result])\n }\n for (const model of models) model.setRelation(relation, new Collection(dictionary.get(String(model.getAttribute(this.parentKey))) ?? []))\n return models\n }\n\n getRelationExistenceQuery(query: Builder<R>, _parentQuery: Builder<P>, columns: ColumnRef[] = ['*']): Builder<R> {\n return query\n .select(...(columns as Array<Column<R>>))\n .join(this.table, this.model.qualifyColumn(this.relatedKey), '=', this.qualifyPivotColumn(this.relatedPivotKey))\n .whereColumn(this.parent.qualifyColumn(this.parentKey), '=', this.qualifyPivotColumn(this.foreignPivotKey))\n }\n\n // ---------------------------------------------------------------- the pivot table\n\n /** Inserts pivot rows for ids (or models, or { id: attributes }), with shared extra attributes. */\n async attach(ids: PivotIds, attributes: Row = {}): Promise<void> {\n const rows = [...this.parseIds(ids)].map(([id, extra]) => this.pivotRow(id, { ...attributes, ...extra }, true))\n if (rows.length) await this.newPivotQuery().insert(rows)\n }\n\n /** Deletes pivot rows for ids, or every pivot row of the parent. Returns how many were deleted. */\n async detach(ids?: PivotIds): Promise<number> {\n const query = this.newPivotQuery().where(this.foreignPivotKey, '=', this.getParentKey())\n if (ids !== undefined) {\n const list = [...this.parseIds(ids).keys()]\n if (!list.length) return 0\n query.whereIn(this.relatedPivotKey, list)\n }\n return query.delete()\n }\n\n /** Makes the pivot rows exactly ids: attaches the missing ones, detaches the others, updates given attributes. */\n async sync(ids: PivotIds, detaching = true): Promise<SyncChanges> {\n const changes: SyncChanges = { attached: [], detached: [], updated: [] }\n const wanted = this.parseIds(ids)\n const current = await this.currentPivotIds()\n const wantedKeys = new Set([...wanted.keys()].map(String))\n if (detaching) {\n const detach = current.filter((id) => !wantedKeys.has(String(id)))\n if (detach.length) {\n await this.detach(detach)\n changes.detached.push(...detach)\n }\n }\n const currentKeys = new Set(current.map(String))\n for (const [id, attributes] of wanted) {\n if (!currentKeys.has(String(id))) {\n await this.attach(id, attributes)\n changes.attached.push(id)\n } else if (Object.keys(attributes).length && (await this.updateExistingPivot(id, attributes)) > 0) {\n changes.updated.push(id)\n }\n }\n return changes\n }\n\n syncWithoutDetaching(ids: PivotIds): Promise<SyncChanges> {\n return this.sync(ids, false)\n }\n\n /** Attaches the ids that aren't attached and detaches the ones that are. */\n async toggle(ids: PivotIds): Promise<{ attached: unknown[]; detached: unknown[] }> {\n const current = new Set((await this.currentPivotIds()).map(String))\n const attached: unknown[] = []\n const detached: unknown[] = []\n for (const [id, attributes] of this.parseIds(ids)) {\n if (current.has(String(id))) {\n await this.detach(id)\n detached.push(id)\n } else {\n await this.attach(id, attributes)\n attached.push(id)\n }\n }\n return { attached, detached }\n }\n\n /** Updates the pivot row of one related id. Returns the number of affected rows. */\n async updateExistingPivot(id: unknown, attributes: Row): Promise<number> {\n const values = { ...attributes }\n if (this.pivotTimestamps) values[this.pivotTimestamps[1]] = formatDateTime(this.parent.freshTimestamp())\n return this.newPivotQuery()\n .where(this.foreignPivotKey, '=', this.getParentKey())\n .where(this.relatedPivotKey, '=', this.idOf(id))\n .update(values)\n }\n\n /** Saves a new related model and attaches it. */\n override async create(attributes: Row = {}, pivotAttributes: Row = {}): Promise<R> {\n const model = this.model.newInstance(attributes) as R\n await model.save()\n await this.attach(model, pivotAttributes)\n return model\n }\n\n /** Saves a related model and attaches it. */\n async save(model: R, pivotAttributes: Row = {}): Promise<R> {\n await model.save()\n await this.attach(model, pivotAttributes)\n return model\n }\n\n /** A plain query builder on the pivot table. */\n newPivotQuery(): QueryBuilder<Row> {\n return this.connection.table(this.table)\n }\n\n private async currentPivotIds(): Promise<unknown[]> {\n return (await this.newPivotQuery().where(this.foreignPivotKey, '=', this.getParentKey()).pluck(this.relatedPivotKey)).all()\n }\n\n private pivotSelectColumns(): string[] {\n const columns = [...new Set([this.foreignPivotKey, this.relatedPivotKey, ...this.pivotColumns])]\n return columns.map((column) => `${this.table}.${column} as pivot_${column}`)\n }\n\n private hydratePivot(model: R): void {\n const attributes = model.getAttributes()\n const pivotValues: Row = {}\n const own: Row = {}\n for (const [key, value] of Object.entries(attributes)) {\n if (key.startsWith('pivot_')) pivotValues[key.slice(6)] = value\n else own[key] = value\n }\n model.setRawAttributes(own, true)\n const pivot = new Pivot().setTable(this.table)\n pivot.timestamps = this.pivotTimestamps !== undefined\n pivot.setRawAttributes(pivotValues, true)\n pivot.exists = true\n model.setRelation('pivot', pivot)\n }\n\n private pivotRow(id: unknown, attributes: Row, creating: boolean): Row {\n const row: Row = { ...attributes, [this.foreignPivotKey]: this.getParentKey(), [this.relatedPivotKey]: this.idOf(id) }\n if (this.pivotTimestamps && creating) {\n const now = formatDateTime(this.parent.freshTimestamp())\n row[this.pivotTimestamps[0]] ??= now\n row[this.pivotTimestamps[1]] ??= now\n }\n return row\n }\n\n /** ids → Map(id → extra pivot attributes). Models become their related key. */\n private parseIds(ids: PivotIds): Map<unknown, Row> {\n const parsed = new Map<unknown, Row>()\n if (ids instanceof Collection) ids = ids.all()\n if (Array.isArray(ids)) {\n for (const id of ids) parsed.set(this.idOf(id), {})\n } else if (ids !== null && typeof ids === 'object' && !this.isModel(ids)) {\n for (const [id, attributes] of Object.entries(ids as Record<string, Row>)) parsed.set(this.castKey(id), attributes)\n } else {\n parsed.set(this.idOf(ids), {})\n }\n return parsed\n }\n\n private idOf(id: unknown): unknown {\n return this.isModel(id) ? id.getAttribute(this.relatedKey) : id\n }\n\n private isModel(value: unknown): value is Model {\n return typeof value === 'object' && value !== null && typeof (value as Model).getAttribute === 'function' && typeof (value as Model).getTable === 'function'\n }\n\n /** Object keys are strings; numeric ones go back to numbers for integer keys. */\n private castKey(id: string): unknown {\n return this.model.getKeyType() === 'int' && /^\\d+$/.test(id) ? Number(id) : id\n }\n}\n","import type { Row } from '@orieljs/contracts'\nimport type { ColumnRef } from '../../Query/Builder'\nimport type { Builder } from '../Builder'\nimport type { Model } from '../Model'\nimport type { Column } from '../types'\nimport { Relation } from './Relation'\n\n/** For morphOne/morphMany: the qualified type column and the parent's morph class stored in it. */\nexport interface MorphConstraint {\n type: string\n value: string\n}\n\n/**\n * The shared half of hasOne, hasMany, morphOne and morphMany: the related table holds the foreign key (and, for\n * the morph relations, the parent's type).\n */\nexport abstract class HasOneOrMany<R extends Model, P extends Model, Result> extends Relation<R, P, Result> {\n /**\n * @param foreignKey the qualified foreign key on the related table ('comments.post_id')\n * @param localKey the key on the parent it points at ('id')\n * @param morph the type column and value, for morphOne/morphMany\n */\n constructor(\n related: R,\n parent: P,\n readonly foreignKey: string,\n readonly localKey: string,\n readonly morph?: MorphConstraint,\n ) {\n super(related, parent)\n this.init()\n }\n\n /** 'post_id' */\n getForeignKeyName(): string {\n return this.foreignKey.slice(this.foreignKey.lastIndexOf('.') + 1)\n }\n\n getQualifiedForeignKeyName(): string {\n return this.foreignKey\n }\n\n getParentKey(): unknown {\n return this.parent.getAttribute(this.localKey)\n }\n\n getQualifiedParentKeyName(): string {\n return this.parent.qualifyColumn(this.localKey)\n }\n\n /** 'commentable_type' for a morph relation. */\n getMorphType(): string | undefined {\n return this.morph?.type.slice(this.morph.type.lastIndexOf('.') + 1)\n }\n\n /** The parent's value in the type column, for a morph relation. */\n getMorphClass(): string | undefined {\n return this.morph?.value\n }\n\n addConstraints(): void {\n this.where(this.foreignKey as Column<R>, '=', this.getParentKey())\n this.whereNotNull(this.foreignKey as Column<R>)\n if (this.morph) this.where(this.morph.type as Column<R>, '=', this.morph.value)\n }\n\n addEagerConstraints(models: P[]): void {\n this.whereIn(this.foreignKey as Column<R>, this.keysOf(models, this.localKey))\n if (this.morph) this.where(this.morph.type as Column<R>, '=', this.morph.value)\n }\n\n /** Related models grouped by their foreign key, as strings: bigint and integer keys compare equal. */\n protected buildDictionary(results: R[]): Map<string, R[]> {\n const dictionary = new Map<string, R[]>()\n const key = this.getForeignKeyName()\n for (const result of results) {\n const value = String(result.getAttribute(key))\n const group = dictionary.get(value)\n if (group) group.push(result)\n else dictionary.set(value, [result])\n }\n return dictionary\n }\n\n /** New related models get the parent's key (and type): post.comments().create({ body }) sets post_id. */\n override newModelInstance(attributes: Row = {}): R {\n return this.setForeignAttributes(super.newModelInstance(attributes))\n }\n\n /** Sets the foreign key (and type) on an existing model and saves it. */\n async save(model: R): Promise<R> {\n await this.setForeignAttributes(model).save()\n return model\n }\n\n protected setForeignAttributes(model: R): R {\n model.setAttribute(this.getForeignKeyName(), this.getParentKey())\n if (this.morph) model.setAttribute(this.getMorphType()!, this.morph.value)\n return model\n }\n\n async saveMany(models: Iterable<R>): Promise<R[]> {\n const saved: R[] = []\n for (const model of models) saved.push(await this.save(model))\n return saved\n }\n\n async createMany(records: Row[]): Promise<R[]> {\n const created: R[] = []\n for (const record of records) created.push(await this.create(record))\n return created\n }\n\n getRelationExistenceQuery(query: Builder<R>, _parentQuery: Builder<P>, columns: ColumnRef[] = ['*']): Builder<R> {\n query.select(...(columns as Array<Column<R>>)).whereColumn(this.getQualifiedParentKeyName(), '=', this.foreignKey)\n if (this.morph) query.where(this.morph.type as Column<R>, '=', this.morph.value)\n return query\n }\n}\n","import { Collection } from '@orieljs/collections'\nimport { LogicError } from '../../errors'\nimport type { Builder } from '../Builder'\nimport type { Model } from '../Model'\nimport { BelongsTo } from './BelongsTo'\nimport { resolveMorphClass } from './morphMap'\n\n/**\n * comment.commentable() → morphTo('commentable'): the parent's class comes from commentable_type (a morph map alias\n * or a class name) and its key from commentable_id. Eager loading runs one query per distinct type.\n */\nexport class MorphTo<R extends Model = Model, P extends Model = Model> extends BelongsTo<R, P> {\n /** Parents grouped by type, then by id, while eager loading. */\n private dictionary = new Map<string, Map<string, P[]>>()\n /** The stored type each eager result was loaded for (an alias or a class name), for match(). */\n private resultTypes = new WeakMap<Model, string>()\n\n /**\n * @param related an instance of the current type's class (the child's own class when the type is empty)\n * @param morphType the type column on the child ('commentable_type')\n * @param ownerKey the key on the parent (default: each class's primary key)\n */\n constructor(related: R, child: P, foreignKey: string, readonly morphTypeColumn: string, readonly ownerKeyOverride: string | undefined, relationName: string) {\n super(related, child, foreignKey, ownerKeyOverride ?? related.getKeyName(), relationName)\n // Without a type, `related` is only the child's own class standing in for the real ones: its default with and\n // withCount belong to the child, not to the parents getEager() loads (each type's query adds its own defaults).\n if (!child.getAttribute(morphTypeColumn)) {\n this.eagerLoad.clear()\n this.columns = []\n }\n }\n\n getMorphType(): string {\n return this.morphTypeColumn\n }\n\n override addConstraints(): void {\n if (this.parent.getAttribute(this.morphTypeColumn)) super.addConstraints()\n }\n\n override async getResults(): Promise<R | null> {\n if (!this.parent.getAttribute(this.morphTypeColumn)) return null\n return super.getResults()\n }\n\n /** Groups the children by type and id; the queries run in getEager(). */\n override addEagerConstraints(models: P[]): void {\n this.dictionary = new Map()\n for (const model of models) {\n const type = model.getAttribute(this.morphTypeColumn)\n const id = model.getAttribute(this.foreignKey)\n if (!type || id === null || id === undefined) continue\n const byId = this.dictionary.get(String(type)) ?? new Map<string, P[]>()\n const group = byId.get(String(id))\n if (group) group.push(model)\n else byId.set(String(id), [model])\n this.dictionary.set(String(type), byId)\n }\n }\n\n /** One query per type, with this relation's constraints and nested eager loads. */\n override async getEager(): Promise<Collection<R>> {\n const results: R[] = []\n for (const [type, byId] of this.dictionary) {\n const cls = resolveMorphClass(type)\n const instance = cls.prototypeInstance()\n const ownerKey = this.ownerKeyOverride ?? instance.getKeyName()\n const query = cls.query()\n for (const [name, constraint] of this.getEagerLoads()) query.with(constraint ? { [name]: constraint } : name)\n query.wheres.push(...this.wheres)\n const ids = [...byId.values()].map((models) => models[0]!.getAttribute(this.foreignKey))\n for (const result of (await query.whereIn(instance.qualifyColumn(ownerKey), ids).get()).all() as unknown as R[]) {\n this.resultTypes.set(result, type)\n results.push(result)\n }\n }\n return new Collection(results)\n }\n\n override match(models: P[], results: R[], relation: string): P[] {\n for (const result of results) {\n const byId = this.dictionary.get(this.resultTypes.get(result) ?? result.getMorphClass())\n const ownerKey = this.ownerKeyOverride ?? result.getKeyName()\n for (const model of byId?.get(String(result.getAttribute(ownerKey))) ?? []) model.setRelation(relation, result)\n }\n return models\n }\n\n /** Points the child at `model`: sets the id and the type columns and the loaded relation. */\n override associate(model: R | null): P {\n this.parent.setAttribute(this.foreignKey, model === null ? null : model.getAttribute(this.ownerKeyOverride ?? model.getKeyName()))\n this.parent.setAttribute(this.morphTypeColumn, model === null ? null : model.getMorphClass())\n this.parent.setRelation(this.relationName ?? this.morphTypeColumn.replace(/_type$/, ''), model)\n return this.parent\n }\n\n override getRelationExistenceQuery(): Builder<R> {\n throw new LogicError('has()/whereHas() on a morphTo relation needs the possible types, which Oriel v1 does not support.')\n }\n}\n","import { AsyncLocalStorage } from 'node:async_hooks'\nimport { EventDispatcher } from '@orieljs/contracts'\nimport { currentContainer } from '@orieljs/container'\nimport { LogicError } from '../errors'\n\n/** Laravel's model events. The -ing events of save, delete and restore can cancel by returning false. */\nexport const MODEL_EVENTS = [\n 'retrieved', 'creating', 'created', 'updating', 'updated', 'saving', 'saved',\n 'deleting', 'deleted', 'restoring', 'restored', 'forceDeleting', 'forceDeleted',\n] as const\nexport type ModelEvent = (typeof MODEL_EVENTS)[number]\n\n/** A listener receives the model. Returning false from a halting event cancels the operation. */\nexport type ModelListener<M> = (model: M) => unknown\n\nconst muted = new AsyncLocalStorage<boolean>()\n\n/** 'eloquent.created: Post' (Laravel uses the fully qualified class name; Oriel uses the class name). */\nexport function modelEventName(event: string, className: string): string {\n return `eloquent.${event}: ${className}`\n}\n\n/** The EventDispatcher of the current container, when one is bound. Firing without one is a no-op. */\nexport function eventDispatcher(): EventDispatcher | undefined {\n const container = currentContainer()\n return container?.bound(EventDispatcher) ? container.make(EventDispatcher) : undefined\n}\n\n/** The dispatcher for registering listeners: required, because silently dropping an observer would hide a bug. */\nexport function requireEventDispatcher(className: string): EventDispatcher {\n const dispatcher = eventDispatcher()\n if (!dispatcher) {\n throw new LogicError(`Registering model events on [${className}] needs an EventDispatcher. Is EventServiceProvider registered?`)\n }\n return dispatcher\n}\n\n/** Runs fn with model events off, for this async context only (Model.withoutEvents, saveQuietly). */\nexport function withoutModelEvents<R>(fn: () => R): R {\n return muted.run(true, fn)\n}\n\nexport function modelEventsMuted(): boolean {\n return muted.getStore() === true\n}\n","import { Collection } from '@orieljs/collections'\nimport type { Model } from '../Model'\nimport { HasOneOrMany } from './HasOneOrMany'\n\n/** post.comments(): many related rows hold the parent's key. */\nexport class HasMany<R extends Model, P extends Model = Model> extends HasOneOrMany<R, P, Collection<R>> {\n async getResults(): Promise<Collection<R>> {\n const key = this.getParentKey()\n return key === null || key === undefined ? new Collection<R>() : this.get()\n }\n\n initRelation(models: P[], relation: string): P[] {\n for (const model of models) model.setRelation(relation, new Collection<R>())\n return models\n }\n\n match(models: P[], results: R[], relation: string): P[] {\n const dictionary = this.buildDictionary(results)\n for (const model of models) {\n model.setRelation(relation, new Collection(dictionary.get(String(model.getAttribute(this.localKey))) ?? []))\n }\n return models\n }\n}\n","import { Collection } from '@orieljs/collections'\nimport type { Row } from '@orieljs/contracts'\nimport type { ColumnRef } from '../../Query/Builder'\nimport { Builder } from '../Builder'\nimport type { Model } from '../Model'\nimport type { Column } from '../types'\nimport { Relation } from './Relation'\n\nconst THROUGH_KEY = 'laravel_through_key'\n\n/**\n * Related rows reached through an intermediate model: country.posts() → hasManyThrough(Post, User):\n * posts join users on users.id = posts.user_id where users.country_id = countries.id.\n */\nexport class HasManyThrough<R extends Model, P extends Model = Model, T extends Model = Model> extends Relation<R, P, Collection<R>> {\n /** The through key of each loaded model (kept off its attributes, so it never reaches toJSON()). */\n private readonly throughKeys = new WeakMap<Model, unknown>()\n\n /**\n * @param firstKey on the through table, pointing at the far parent ('users.country_id')\n * @param secondKey on the related table, pointing at the through model ('posts.user_id')\n * @param localKey on the far parent ('countries.id')\n * @param secondLocalKey on the through model ('users.id')\n */\n constructor(\n related: R,\n farParent: P,\n readonly throughParent: T,\n readonly firstKey: string,\n readonly secondKey: string,\n readonly localKey: string,\n readonly secondLocalKey: string,\n ) {\n super(related, farParent)\n this.join(this.throughParent.getTable(), this.getQualifiedParentKeyName(), '=', this.getQualifiedForeignKeyName())\n if (this.throughParent.usesSoftDeletes()) {\n this.withGlobalScope('SoftDeletableHasManyThrough', (query) => query.whereNull(this.throughParent.getQualifiedDeletedAtColumn()))\n }\n this.init()\n }\n\n /** users.country_id */\n getQualifiedFirstKeyName(): string {\n return this.throughParent.qualifyColumn(this.firstKey)\n }\n\n /** posts.user_id */\n getQualifiedForeignKeyName(): string {\n return this.model.qualifyColumn(this.secondKey)\n }\n\n /** users.id */\n getQualifiedParentKeyName(): string {\n return this.throughParent.qualifyColumn(this.secondLocalKey)\n }\n\n /** countries.id */\n getQualifiedLocalKeyName(): string {\n return this.parent.qualifyColumn(this.localKey)\n }\n\n addConstraints(): void {\n this.where(this.getQualifiedFirstKeyName() as Column<R>, '=', this.parent.getAttribute(this.localKey))\n }\n\n addEagerConstraints(models: P[]): void {\n this.whereIn(this.getQualifiedFirstKeyName() as Column<R>, this.keysOf(models, this.localKey))\n }\n\n /** Selects the related columns plus the through key, then moves the key off the attributes. */\n override async runSelect(): Promise<R[]> {\n const query = this.clone() as this\n if (!query.columns.length) query.columns = [`${this.model.getTable()}.*`]\n query.columns.push(`${this.getQualifiedFirstKeyName()} as ${THROUGH_KEY}`)\n const models = (await Builder.prototype.runSelect.call(query)) as R[]\n for (const model of models) {\n const { [THROUGH_KEY]: key, ...attributes } = model.getAttributes() as Row\n this.throughKeys.set(model, key)\n model.setRawAttributes(attributes, true)\n }\n return models\n }\n\n async getResults(): Promise<Collection<R>> {\n const key = this.parent.getAttribute(this.localKey)\n return key === null || key === undefined ? new Collection<R>() : this.get()\n }\n\n override async getEager(): Promise<Collection<R>> {\n return this.get()\n }\n\n initRelation(models: P[], relation: string): P[] {\n for (const model of models) model.setRelation(relation, new Collection<R>())\n return models\n }\n\n match(models: P[], results: R[], relation: string): P[] {\n const dictionary = new Map<string, R[]>()\n for (const result of results) {\n const key = String(this.throughKeys.get(result))\n const group = dictionary.get(key)\n if (group) group.push(result)\n else dictionary.set(key, [result])\n }\n for (const model of models) model.setRelation(relation, new Collection(dictionary.get(String(model.getAttribute(this.localKey))) ?? []))\n return models\n }\n\n getRelationExistenceQuery(query: Builder<R>, _parentQuery: Builder<P>, columns: ColumnRef[] = ['*']): Builder<R> {\n query\n .select(...(columns as Array<Column<R>>))\n .join(this.throughParent.getTable(), this.getQualifiedParentKeyName(), '=', this.getQualifiedForeignKeyName())\n .whereColumn(this.getQualifiedLocalKeyName(), '=', this.getQualifiedFirstKeyName())\n if (this.throughParent.usesSoftDeletes()) query.whereNull(this.throughParent.getQualifiedDeletedAtColumn() as Column<R>)\n return query\n }\n}\n","import type { Model } from '../Model'\nimport { HasOneOrMany } from './HasOneOrMany'\n\n/** user.profile(): one related row holds the parent's key. */\nexport class HasOne<R extends Model, P extends Model = Model> extends HasOneOrMany<R, P, R | null> {\n async getResults(): Promise<R | null> {\n const key = this.getParentKey()\n if (key === null || key === undefined) return null\n return (await this.first()) ?? null\n }\n\n initRelation(models: P[], relation: string): P[] {\n for (const model of models) model.setRelation(relation, null)\n return models\n }\n\n match(models: P[], results: R[], relation: string): P[] {\n const dictionary = this.buildDictionary(results)\n for (const model of models) {\n model.setRelation(relation, dictionary.get(String(model.getAttribute(this.localKey)))?.[0] ?? null)\n }\n return models\n }\n}\n","import type { Model } from '../Model'\nimport { HasMany } from './HasMany'\n\n/** post.comments() → morphMany(Comment, 'commentable'): comments.commentable_id + commentable_type = 'Post'. */\nexport class MorphMany<R extends Model, P extends Model = Model> extends HasMany<R, P> {\n /**\n * @param morphType the qualified type column ('comments.commentable_type')\n * @param foreignKey the qualified id column ('comments.commentable_id')\n */\n constructor(related: R, parent: P, morphType: string, foreignKey: string, localKey: string) {\n super(related, parent, foreignKey, localKey, { type: morphType, value: parent.getMorphClass() })\n }\n}\n","import type { Model } from '../Model'\nimport { HasOne } from './HasOne'\n\n/** user.image() → morphOne(Image, 'imageable'): images.imageable_id + imageable_type = 'User'. */\nexport class MorphOne<R extends Model, P extends Model = Model> extends HasOne<R, P> {\n constructor(related: R, parent: P, morphType: string, foreignKey: string, localKey: string) {\n super(related, parent, foreignKey, localKey, { type: morphType, value: parent.getMorphClass() })\n }\n}\n","/**\n * A migration: `export default class extends Migration { async up() { await Schema.create(…) } async down() { … } }`.\n * Files live in database/migrations and run in file-name order. up() and down() are abstract (as in Laravel's\n * stub), so implementing them needs no `override` under noImplicitOverride.\n */\nexport abstract class Migration {\n /** The connection to run on (default: the default connection). */\n connection: string | undefined = undefined\n\n /** Wrap up()/down() in a transaction where DDL is transactional (Postgres, SQLite; not MySQL), like Laravel. */\n withinTransaction = true\n\n abstract up(): Promise<void> | void\n\n abstract down(): Promise<void> | void\n}\n","import { existsSync, mkdirSync, writeFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { Str } from '@orieljs/support'\nimport { LogicError } from '../errors'\n\n/** Laravel 11's migration.create stub: an anonymous class, the form the Migrator loads. */\nexport const MIGRATION_CREATE_STUB = `import { Migration, Schema } from '{{ importSource }}'\n\nexport default class extends Migration {\n async up() {\n await Schema.create('{{ table }}', (table) => {\n table.id()\n table.timestamps()\n })\n }\n\n async down() {\n await Schema.dropIfExists('{{ table }}')\n }\n}\n`\n\n/** Laravel 11's migration.update stub. */\nexport const MIGRATION_UPDATE_STUB = `import { Migration, Schema } from '{{ importSource }}'\n\nexport default class extends Migration {\n async up() {\n await Schema.table('{{ table }}', (table) => {\n //\n })\n }\n\n async down() {\n await Schema.table('{{ table }}', (table) => {\n //\n })\n }\n}\n`\n\n/** Laravel 11's blank migration stub. */\nexport const MIGRATION_STUB = `import { Migration } from '{{ importSource }}'\n\nexport default class extends Migration {\n async up() {\n //\n }\n\n async down() {\n //\n }\n}\n`\n\n/**\n * Laravel's TableGuesser: create_posts_table → ['posts', true], add_votes_to_users_table → ['users', false].\n * Returns undefined when the name says nothing about a table.\n */\nexport function guessTable(migration: string): { table: string; create: boolean } | undefined {\n const create = /^create_(\\w+?)(?:_table)?$/.exec(migration)\n if (create) return { table: create[1]!, create: true }\n const change = /_(?:to|from|in)_(\\w+?)(?:_table)?$/.exec(migration)\n if (change) return { table: change[1]!, create: false }\n return undefined\n}\n\n/** Laravel's date prefix, Y_m_d_His (UTC). */\nexport function migrationDatePrefix(date: Date = new Date()): string {\n const pad = (value: number) => String(value).padStart(2, '0')\n return (\n `${date.getUTCFullYear()}_${pad(date.getUTCMonth() + 1)}_${pad(date.getUTCDate())}_` +\n `${pad(date.getUTCHours())}${pad(date.getUTCMinutes())}${pad(date.getUTCSeconds())}`\n )\n}\n\nexport interface CreateMigrationOptions {\n /** The table to create (--create). */\n create?: string\n /** The table to change (--table). */\n table?: string\n /** The package the migration imports Migration and Schema from (default '@orieljs/framework'). */\n importSource?: string\n /** For tests: the timestamp of the file name. */\n date?: Date\n}\n\n/** Laravel's MigrationCreator: writes <path>/<Y_m_d_His>_<name>.ts from the create, update or blank stub. */\nexport class MigrationCreator {\n /** Returns the path of the new file. */\n create(name: string, path: string, options: CreateMigrationOptions = {}): string {\n const snake = Str.snake(name.trim())\n let table = options.table ?? options.create\n let create = options.create !== undefined\n if (table === undefined) {\n const guessed = guessTable(snake)\n if (guessed) ({ table, create } = guessed)\n }\n const stub = table === undefined ? MIGRATION_STUB : create ? MIGRATION_CREATE_STUB : MIGRATION_UPDATE_STUB\n const file = join(path, `${migrationDatePrefix(options.date)}_${snake}.ts`)\n if (existsSync(file)) throw new LogicError(`Migration [${file}] already exists.`)\n mkdirSync(path, { recursive: true })\n writeFileSync(\n file,\n stub.replaceAll('{{ importSource }}', options.importSource ?? '@orieljs/framework').replaceAll('{{ table }}', table ?? ''),\n )\n return file\n }\n}\n","import type { Connection } from '../Connection'\n\nexport interface MigrationRecord {\n migration: string\n batch: number\n}\n\n/** The migrations table (id, migration, batch): which migration ran in which batch (Laravel's DatabaseMigrationRepository). */\nexport class MigrationRepository {\n constructor(\n protected readonly connection: Connection,\n readonly table = 'migrations',\n ) {}\n\n async repositoryExists(): Promise<boolean> {\n return this.connection.getSchemaBuilder().hasTable(this.table)\n }\n\n async createRepository(): Promise<void> {\n await this.connection.getSchemaBuilder().create(this.table, (table) => {\n table.increments('id')\n table.string('migration')\n table.integer('batch')\n })\n }\n\n async deleteRepository(): Promise<void> {\n await this.connection.getSchemaBuilder().dropIfExists(this.table)\n }\n\n /** Every migration that ran, oldest first. */\n async getRan(): Promise<string[]> {\n return (await this.query().orderBy('batch').orderBy('migration').pluck<string>('migration')).all()\n }\n\n /** The last `steps` migrations, newest first. */\n async getMigrations(steps: number): Promise<MigrationRecord[]> {\n return this.records(this.query().where('batch', '>=', 1).orderBy('batch', 'desc').orderBy('migration', 'desc').limit(steps))\n }\n\n /** The migrations of one batch, newest first. */\n async getMigrationsByBatch(batch: number): Promise<MigrationRecord[]> {\n return this.records(this.query().where('batch', batch).orderBy('migration', 'desc'))\n }\n\n /** The migrations of the last batch, newest first. */\n async getLast(): Promise<MigrationRecord[]> {\n return this.getMigrationsByBatch(await this.getLastBatchNumber())\n }\n\n /** migration name → batch. */\n async getMigrationBatches(): Promise<Record<string, number>> {\n const rows = await this.records(this.query().orderBy('batch').orderBy('migration'))\n return Object.fromEntries(rows.map((row) => [row.migration, row.batch]))\n }\n\n async log(migration: string, batch: number): Promise<void> {\n await this.query().insert({ migration, batch })\n }\n\n async delete(migration: string): Promise<void> {\n await this.query().where('migration', migration).delete()\n }\n\n async getNextBatchNumber(): Promise<number> {\n return (await this.getLastBatchNumber()) + 1\n }\n\n async getLastBatchNumber(): Promise<number> {\n return Number((await this.query().max('batch')) ?? 0)\n }\n\n private query() {\n return this.connection.table<MigrationRecord>(this.table)\n }\n\n private async records(query: ReturnType<MigrationRepository['query']>): Promise<MigrationRecord[]> {\n return (await query.get()).all().map((row) => ({ migration: String(row.migration), batch: Number(row.batch) }))\n }\n}\n","import { existsSync, readdirSync } from 'node:fs'\nimport { basename, extname, join } from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport type { Connection } from '../Connection'\nimport type { DatabaseManagerImpl } from '../DatabaseManager'\nimport { LogicError } from '../errors'\nimport { Migration } from './Migration'\nimport { MigrationRepository } from './MigrationRepository'\n\nconst MIGRATION_FILE = /^(?!.*\\.d\\.[mc]?ts$).+\\.(ts|js|mts|mjs)$/\n\nexport interface MigrationStatus {\n name: string\n ran: boolean\n batch: number | undefined\n}\n\nexport interface MigratorOptions {\n /** Run each migration in its own batch (migrate --step). */\n step?: boolean\n}\n\nexport interface RollbackOptions {\n /** Roll back this many migrations instead of the last batch. */\n step?: number\n /** Roll back one batch by number. */\n batch?: number\n}\n\n/**\n * Runs database/migrations/*.ts in file-name order and records them in the migrations table\n * (Laravel's Migrator). Output lines go to `output`.\n */\nexport class Migrator {\n private connectionName: string | undefined\n\n constructor(\n protected readonly manager: DatabaseManagerImpl,\n protected readonly output: (line: string) => void = () => undefined,\n ) {}\n\n /** Use another connection for the repository and for migrations that don't name one (--database). */\n setConnection(name: string | undefined): this {\n this.connectionName = name\n return this\n }\n\n getConnection(): Connection {\n return this.manager.connection(this.connectionName)\n }\n\n getRepository(): MigrationRepository {\n return new MigrationRepository(this.getConnection(), this.manager.migrationsTable())\n }\n\n /** migration name (file name without extension) → absolute path, sorted by name across all paths. */\n getMigrationFiles(paths: readonly string[]): Map<string, string> {\n const files: Array<[string, string]> = []\n for (const path of paths) {\n if (!existsSync(path)) continue\n for (const file of readdirSync(path)) {\n if (MIGRATION_FILE.test(file)) files.push([basename(file, extname(file)), join(path, file)])\n }\n }\n return new Map(files.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)))\n }\n\n /** Creates the migrations table when it doesn't exist yet. */\n async ensureRepository(): Promise<MigrationRepository> {\n const repository = this.getRepository()\n if (!(await repository.repositoryExists())) await repository.createRepository()\n return repository\n }\n\n /** Runs every pending migration in one new batch (or one batch each with step). Returns their names. */\n async run(paths: readonly string[], options: MigratorOptions = {}): Promise<string[]> {\n const repository = await this.ensureRepository()\n const ran = new Set(await repository.getRan())\n const pending = [...this.getMigrationFiles(paths)].filter(([name]) => !ran.has(name))\n if (!pending.length) {\n this.output('Nothing to migrate.')\n return []\n }\n let batch = await repository.getNextBatchNumber()\n this.output('Running migrations.')\n for (const [name, file] of pending) {\n await this.runMigration(await this.resolve(file), 'up')\n await repository.log(name, batch)\n this.output(` ${name} DONE`)\n if (options.step) batch++\n }\n return pending.map(([name]) => name)\n }\n\n /** Rolls back the last batch (or the last `step` migrations, or one batch). Returns the names rolled back. */\n async rollback(paths: readonly string[], options: RollbackOptions = {}): Promise<string[]> {\n const repository = await this.ensureRepository()\n const records = options.step\n ? await repository.getMigrations(options.step)\n : options.batch\n ? await repository.getMigrationsByBatch(options.batch)\n : await repository.getLast()\n if (!records.length) {\n this.output('Nothing to rollback.')\n return []\n }\n this.output('Rolling back migrations.')\n return this.rollDown(paths, records.map((record) => record.migration), repository)\n }\n\n /** Rolls back every migration, newest first. */\n async reset(paths: readonly string[]): Promise<string[]> {\n const repository = await this.ensureRepository()\n const ran = (await repository.getRan()).reverse()\n if (!ran.length) {\n this.output('Nothing to rollback.')\n return []\n }\n this.output('Rolling back migrations.')\n return this.rollDown(paths, ran, repository)\n }\n\n /** Drops every table, then runs every migration (migrate:fresh). */\n async fresh(paths: readonly string[]): Promise<string[]> {\n await this.getConnection().getSchemaBuilder().dropAllTables()\n this.output('Dropping all tables DONE')\n return this.run(paths)\n }\n\n /** Every migration file and every recorded migration, with its batch (all pending without a migrations table). */\n async status(paths: readonly string[]): Promise<MigrationStatus[]> {\n const repository = this.getRepository()\n const batches = (await repository.repositoryExists()) ? await repository.getMigrationBatches() : {}\n const names = new Set([...this.getMigrationFiles(paths).keys(), ...Object.keys(batches)])\n return [...names].sort().map((name) => ({ name, ran: name in batches, batch: batches[name] }))\n }\n\n /** Imports a migration file; its default export is a Migration class (or instance). */\n async resolve(file: string): Promise<Migration> {\n const module = (await import(pathToFileURL(file).href)) as { default?: unknown }\n const exported = module.default\n const migration = typeof exported === 'function' ? new (exported as new () => unknown)() : exported\n if (!(migration instanceof Migration)) {\n throw new LogicError(`Migration [${basename(file)}] must default-export a class extending Migration.`)\n }\n return migration\n }\n\n private async rollDown(paths: readonly string[], names: string[], repository: MigrationRepository): Promise<string[]> {\n const files = this.getMigrationFiles(paths)\n const rolledBack: string[] = []\n for (const name of names) {\n const file = files.get(name)\n if (!file) {\n this.output(` ${name} Migration not found`)\n continue\n }\n await this.runMigration(await this.resolve(file), 'down')\n await repository.delete(name)\n this.output(` ${name} DONE`)\n rolledBack.push(name)\n }\n return rolledBack\n }\n\n /** Runs up/down on the migration's connection (made the default meanwhile), in a transaction where DDL allows it. */\n private async runMigration(migration: Migration, method: 'up' | 'down'): Promise<void> {\n const name = migration.connection ?? this.connectionName\n await this.manager.usingConnection(name, async () => {\n const connection = this.manager.connection(name)\n const run = async () => {\n await migration[method]()\n }\n if (migration.withinTransaction && connection.getDriverName() !== 'mysql') await connection.transaction(run)\n else await run()\n })\n }\n}\n","import { Model } from './Eloquent/Model'\n\nexport type SeederClass = new () => Seeder\n\n/**\n * A database seeder (database/seeders/*.ts): run() inserts data, call() runs other seeders. Seeders run with mass\n * assignment protection off, as with Laravel's db:seed.\n */\nexport abstract class Seeder {\n protected output: (line: string) => void = () => undefined\n\n abstract run(): Promise<void> | void\n\n setOutput(output: (line: string) => void): this {\n this.output = output\n return this\n }\n\n /** Runs other seeders in order, printing their names. */\n async call(...seeders: Array<SeederClass | SeederClass[]>): Promise<void> {\n for (const seeder of seeders.flat()) {\n this.output(` ${seeder.name} RUNNING`)\n await new seeder().setOutput(this.output).invoke()\n this.output(` ${seeder.name} DONE`)\n }\n }\n\n /** Runs other seeders without output. */\n async callSilent(...seeders: Array<SeederClass | SeederClass[]>): Promise<void> {\n for (const seeder of seeders.flat()) await new seeder().invoke()\n }\n\n /** Runs run() unguarded. */\n async invoke(): Promise<void> {\n await Model.unguarded(() => this.run())\n }\n}\n","import { existsSync } from 'node:fs'\nimport { isAbsolute, join, relative } from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport type { Application, CommandContext, ConsoleKernel } from '@orieljs/contracts'\nimport type { DatabaseManagerImpl } from '../DatabaseManager'\nimport { LogicError } from '../errors'\nimport { MigrationCreator } from '../Migrations/MigrationCreator'\nimport { Migrator } from '../Migrations/Migrator'\nimport type { ModelRegistry } from '../ModelRegistry'\nimport { Seeder } from '../Seeder'\nimport { TypeGenerator } from '../Types/TypeGenerator'\n\n/** The parts of the application and database the commands need (resolved lazily, when a command runs). */\nexport interface DatabaseCommandContext {\n app: Pick<Application, 'basePath' | 'databasePath' | 'isProduction'>\n manager(): DatabaseManagerImpl\n /** The discovered models. When given, model:types works and migrate regenerates the types outside production. */\n models?(): Promise<ModelRegistry>\n /** The package generated types import from (default '@orieljs/framework'). */\n typesImportSource?: string\n /** The package make:migration's stubs import from (default '@orieljs/framework'). */\n stubsImportSource?: string\n}\n\ntype Handler = (command: CommandContext) => Promise<number>\n\nconst text = (value: unknown): string | undefined => (typeof value === 'string' && value !== '' ? value : undefined)\nconst list = (value: unknown): string[] => (Array.isArray(value) ? value.map(String) : text(value) ? [String(value)] : [])\nconst integer = (value: unknown): number => {\n const number = Number(value ?? 0)\n return Number.isInteger(number) && number > 0 ? number : 0\n}\n\n/** A closure command with Laravel's description (shown by `oriel list`). */\nfunction define(kernel: ConsoleKernel, signature: string, description: string, handler: Handler): void {\n kernel\n .command(signature, async function (this: CommandContext) {\n return handler(this)\n })\n .purpose(description)\n}\n\n/** Laravel's ConfirmableTrait without the prompt: in production the command needs --force. */\nfunction confirmToProceed(context: DatabaseCommandContext, command: CommandContext): boolean {\n if (!context.app.isProduction() || command.option('force') === true) return true\n command.error('Application in production. Use --force to run this command.')\n return false\n}\n\n/** --path values (relative to the base path), or database/migrations. */\nfunction migrationPaths(context: DatabaseCommandContext, command: CommandContext): string[] {\n const paths = list(command.option('path'))\n if (!paths.length) return [context.app.databasePath('migrations')]\n return paths.map((path) => (isAbsolute(path) ? path : context.app.basePath(path)))\n}\n\nfunction migrator(context: DatabaseCommandContext, command: CommandContext): Migrator {\n return new Migrator(context.manager(), (line) => command.line(line)).setConnection(text(command.option('database')))\n}\n\n/** Imports database/seeders/<Class>.ts and runs it (default export or the export named after the class). */\nexport async function runSeeder(context: DatabaseCommandContext, className: string, output: (line: string) => void, database?: string): Promise<void> {\n const name = className.split('\\\\').pop()!\n const file = ['ts', 'js', 'mts', 'mjs'].map((extension) => context.app.databasePath(join('seeders', `${name}.${extension}`))).find(existsSync)\n if (!file) throw new LogicError(`Seeder [${name}] not found in ${context.app.databasePath('seeders')}.`)\n const module = (await import(pathToFileURL(file).href)) as Record<string, unknown>\n const exported = module.default ?? module[name]\n const seeder = typeof exported === 'function' ? new (exported as new () => unknown)() : exported\n if (!(seeder instanceof Seeder)) throw new LogicError(`Seeder [${name}] must export a class extending Seeder.`)\n await context.manager().usingConnection(database, () => seeder.setOutput(output).invoke())\n}\n\n/** Writes types/models.d.ts for the discovered models; returns the path relative to the base path. */\nexport async function generateModelTypes(context: DatabaseCommandContext): Promise<string | undefined> {\n if (!context.models) return undefined\n const outputFile = context.app.basePath(join('types', 'models.d.ts'))\n await new TypeGenerator({ outputFile, importSource: context.typesImportSource }).write((await context.models()).all())\n return relative(context.app.basePath(), outputFile)\n}\n\n/** Laravel's needsSeeding(): --seed, or a --seeder class on its own. */\nasync function seedIfRequested(context: DatabaseCommandContext, command: CommandContext): Promise<void> {\n const seeder = text(command.option('seeder'))\n if (command.option('seed') !== true && seeder === undefined) return\n command.info('Seeding database.')\n await runSeeder(context, seeder ?? 'DatabaseSeeder', (line) => command.line(line), text(command.option('database')))\n}\n\n/** The migrate*, migrate:install, db:seed and make:migration commands (closure commands, PC1). */\nexport function registerMigrationCommands(kernel: ConsoleKernel, context: DatabaseCommandContext): void {\n define(kernel, 'migrate {--database=} {--force} {--path=*} {--seed} {--seeder=} {--step}', 'Run the database migrations', async (command) => {\n if (!confirmToProceed(context, command)) return 1\n await migrator(context, command).run(migrationPaths(context, command), { step: command.option('step') === true })\n await seedIfRequested(context, command)\n // Like the spec's \"after oriel migrate\": only for apps that keep generated types (a types/ directory).\n if (!context.app.isProduction() && existsSync(context.app.basePath('types'))) {\n const written = await generateModelTypes(context)\n if (written) command.line(`Model types written to ${written}.`)\n }\n return 0\n })\n\n define(kernel, 'migrate:install {--database=}', 'Create the migration repository', async (command) => {\n const repository = migrator(context, command).getRepository()\n if (!(await repository.repositoryExists())) await repository.createRepository()\n command.info('Migration table created successfully.')\n return 0\n })\n\n define(kernel, 'migrate:rollback {--database=} {--force} {--path=*} {--step=0} {--batch=0}', 'Rollback the last database migration', async (command) => {\n if (!confirmToProceed(context, command)) return 1\n await migrator(context, command).rollback(migrationPaths(context, command), {\n step: integer(command.option('step')),\n batch: integer(command.option('batch')),\n })\n return 0\n })\n\n define(kernel, 'migrate:reset {--database=} {--force} {--path=*}', 'Rollback all database migrations', async (command) => {\n if (!confirmToProceed(context, command)) return 1\n await migrator(context, command).reset(migrationPaths(context, command))\n return 0\n })\n\n define(kernel, 'migrate:refresh {--database=} {--force} {--path=*} {--seed} {--seeder=} {--step=0}', 'Reset and re-run all migrations', async (command) => {\n if (!confirmToProceed(context, command)) return 1\n const instance = migrator(context, command)\n const paths = migrationPaths(context, command)\n const step = integer(command.option('step'))\n if (step) await instance.rollback(paths, { step })\n else await instance.reset(paths)\n await instance.run(paths)\n await seedIfRequested(context, command)\n return 0\n })\n\n define(kernel, 'migrate:fresh {--database=} {--force} {--path=*} {--seed} {--seeder=}', 'Drop all tables and re-run all migrations', async (command) => {\n if (!confirmToProceed(context, command)) return 1\n await migrator(context, command).fresh(migrationPaths(context, command))\n await seedIfRequested(context, command)\n return 0\n })\n\n define(kernel, 'migrate:status {--database=} {--path=*}', 'Show the status of each migration', async (command) => {\n const instance = migrator(context, command)\n if (!(await instance.getRepository().repositoryExists())) {\n command.error('Migration table not found.')\n return 1\n }\n for (const status of await instance.status(migrationPaths(context, command))) {\n command.line(status.ran ? ` ${status.name} [${status.batch}] Ran` : ` ${status.name} Pending`)\n }\n return 0\n })\n\n define(kernel, 'db:seed {class?} {--class=DatabaseSeeder} {--database=} {--force}', 'Seed the database with records', async (command) => {\n if (!confirmToProceed(context, command)) return 1\n command.info('Seeding database.')\n const className = text(command.argument('class')) ?? text(command.option('class')) ?? 'DatabaseSeeder'\n await runSeeder(context, className, (line) => command.line(line), text(command.option('database')))\n return 0\n })\n\n const makeMigration =\n 'make:migration {name : The name of the migration} {--create= : The table to be created} ' +\n '{--table= : The table to migrate} {--path= : The location where the migration file should be created}'\n define(kernel, makeMigration, 'Create a new migration file', async (command) => {\n const name = text(command.argument('name'))\n if (name === undefined) {\n command.error('Not enough arguments (missing: \"name\").')\n return 1\n }\n const path = text(command.option('path'))\n const directory = path === undefined ? context.app.databasePath('migrations') : isAbsolute(path) ? path : context.app.basePath(path)\n const file = new MigrationCreator().create(name, directory, {\n create: text(command.option('create')),\n table: text(command.option('table')),\n importSource: context.stubsImportSource,\n })\n command.info(`Migration [${relative(context.app.basePath(), file)}] created successfully.`)\n return 0\n })\n}\n\n/** model:types: regenerates types/models.d.ts from the database schema and the discovered models. */\nexport function registerModelTypesCommand(kernel: ConsoleKernel, context: DatabaseCommandContext): void {\n define(kernel, 'model:types', \"Generate TypeScript types for the application's models\", async (command) => {\n const written = await generateModelTypes(context)\n if (!written) {\n command.error('No models registry is available: is DatabaseServiceProvider registered?')\n return 1\n }\n command.info(`Model types written to ${written}.`)\n return 0\n })\n}\n","import { mkdir, writeFile } from 'node:fs/promises'\nimport { dirname, relative, sep } from 'node:path'\nimport { Str } from '@orieljs/support'\nimport { enumValues, type CastDefinition } from '../Eloquent/casts'\nimport { Model } from '../Eloquent/Model'\nimport type { RegisteredModel } from '../ModelRegistry'\nimport type { ColumnInfo } from '../Schema/Grammar'\n\nexport interface TypeGeneratorOptions {\n /** Where the declarations go (the skeleton: types/models.d.ts). */\n outputFile: string\n /** The package the generated file imports ScopeStatic from. */\n importSource?: string\n}\n\nconst INTEGER = new Set(['int', 'integer', 'int2', 'int4', 'int8', 'bigint', 'smallint', 'mediumint', 'tinyint', 'serial', 'bigserial', 'smallserial', 'year'])\nconst FLOAT = new Set(['float', 'float4', 'float8', 'double', 'double precision', 'real'])\nconst BOOLEAN = new Set(['bool', 'boolean'])\nconst JSON_TYPES = new Set(['json', 'jsonb'])\nconst BINARY = new Set(['blob', 'bytea', 'binary', 'varbinary', 'longblob', 'mediumblob', 'tinyblob'])\n\n/** The TypeScript type for a cast, or undefined when the column type decides. */\nfunction castType(cast: CastDefinition | undefined): string | undefined {\n if (cast === undefined) return undefined\n if (typeof cast === 'string') {\n if (['int', 'integer', 'float', 'double', 'real', 'timestamp'].includes(cast)) return 'number'\n if (cast === 'string' || cast.startsWith('decimal:')) return 'string'\n if (cast === 'bool' || cast === 'boolean') return 'boolean'\n if (['date', 'datetime', 'immutable_date', 'immutable_datetime'].includes(cast)) return 'Date'\n return 'unknown'\n }\n if (typeof cast === 'object' && typeof (cast as { get?: unknown }).get !== 'function') {\n const literal = (value: string | number) => (typeof value === 'number' ? String(value) : `'${value.replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\")}'`)\n return enumValues(cast as Record<string, string | number>).map(literal).join(' | ') || 'never'\n }\n return 'unknown'\n}\n\n/** The TypeScript type for a database column type (what the drivers hand back without a cast). */\nfunction columnType(column: ColumnInfo): string {\n const name = column.type_name.toLowerCase()\n if (INTEGER.has(name)) return 'number'\n if (FLOAT.has(name)) return 'number'\n if (BOOLEAN.has(name)) return 'boolean'\n if (JSON_TYPES.has(name)) return 'unknown'\n if (BINARY.has(name)) return 'Buffer'\n return 'string'\n}\n\n/** The get<Name>Attribute accessors on a model class, as [attribute, method] pairs. */\nfunction accessors(model: typeof Model): Array<[string, string]> {\n const found = new Map<string, string>()\n for (let proto: object | null = model.prototype; proto && proto !== Model.prototype; proto = Object.getPrototypeOf(proto) as object | null) {\n for (const key of Object.getOwnPropertyNames(proto)) {\n const match = /^get(.+)Attribute$/.exec(key)\n if (match && typeof Reflect.get(proto, key) === 'function' && !found.has(Str.snake(match[1]!))) found.set(Str.snake(match[1]!), key)\n }\n }\n return [...found]\n}\n\n/** The static scope<Name> methods of a model class, as [builder method, static method] pairs. */\nfunction scopes(model: typeof Model): Array<[string, string]> {\n const found = new Map<string, string>()\n for (let current: unknown = model; current && current !== Model; current = Object.getPrototypeOf(current)) {\n for (const key of Object.getOwnPropertyNames(current)) {\n if (key.startsWith('scope') && key.length > 5 && typeof Reflect.get(current as object, key) === 'function') {\n const name = Str.lcfirst(key.slice(5))\n if (!found.has(name)) found.set(name, key)\n }\n }\n }\n return [...found]\n}\n\n/**\n * Writes types/models.d.ts: for every model, the attribute types (from the database columns and the model's casts)\n * merged into the class by declaration merging, the phantom $attributes that Column<M> reads, accessor-only\n * attributes, and the static scope proxies (Post.published()).\n */\nexport class TypeGenerator {\n constructor(private readonly options: TypeGeneratorOptions) {}\n\n async generate(models: readonly RegisteredModel[]): Promise<string> {\n const blocks: string[] = []\n for (const entry of [...models].sort((a, b) => a.name.localeCompare(b.name))) {\n if (!entry.file) continue\n const block = await this.modelBlock(entry)\n if (block) blocks.push(block)\n }\n const importSource = this.options.importSource ?? '@orieljs/framework'\n return [\n '// Generated by `oriel model:types`. Do not edit: run `oriel model:types` (or `oriel migrate`) again.',\n // Built by concatenation so tools that scan source for imports don't mistake this template for one.\n 'import type { ScopeStatic } from ' + `'${importSource}'`,\n '',\n ...blocks,\n ].join('\\n')\n }\n\n /** Generates and writes the file; returns its path. */\n async write(models: readonly RegisteredModel[]): Promise<string> {\n await mkdir(dirname(this.options.outputFile), { recursive: true })\n await writeFile(this.options.outputFile, await this.generate(models))\n return this.options.outputFile\n }\n\n private async modelBlock({ name, model, file }: RegisteredModel): Promise<string | undefined> {\n const instance = model.prototypeInstance()\n const columns = await instance.getConnection().getSchemaBuilder().getColumns(instance.getTable())\n if (!columns.length) return undefined\n const casts = instance.getCasts()\n const attributes = columns.map((column) => {\n const type = castType(casts[column.name]) ?? columnType(column)\n return [column.name, column.nullable && type !== 'unknown' ? `${type} | null` : type] as const\n })\n const members = attributes.filter(([column]) => !(column in instance))\n const extra = accessors(model).filter(([attribute]) => !columns.some((column) => column.name === attribute) && !(attribute in instance))\n const statics = scopes(model).filter(([method]) => !(method in Model))\n const lines = [\n 'declare module ' + `'${this.modulePath(file!)}' {`,\n ` interface ${name} {`,\n ' $attributes?: {',\n ...attributes.map(([column, type]) => ` ${this.key(column)}: ${type}`),\n ' }',\n ...members.map(([column, type]) => ` ${this.key(column)}: ${type}`),\n ...extra.map(([attribute, method]) => ` ${this.key(attribute)}: ReturnType<${name}['${method}']>`),\n ' }',\n ]\n if (statics.length) {\n lines.push(` namespace ${name} {`, ...statics.map(([method, key]) => ` const ${method}: ScopeStatic<typeof ${name}, '${key}'>`), ' }')\n }\n lines.push('}', '')\n return lines.join('\\n')\n }\n\n /** '../app/Models/Post' for app/Models/Post.ts, relative to the output file. */\n private modulePath(file: string): string {\n const path = relative(dirname(this.options.outputFile), file).split(sep).join('/').replace(/\\.(ts|js|mts|mjs)$/, '')\n return path.startsWith('.') ? path : `./${path}`\n }\n\n private key(name: string): string {\n return /^[A-Za-z_$][\\w$]*$/.test(name) ? name : JSON.stringify(name)\n }\n}\n","import { existsSync, readdirSync, statSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport { Str } from '@orieljs/support'\nimport { Model } from './Eloquent/Model'\n\nexport interface RegisteredModel {\n name: string\n model: typeof Model\n /** The file it was discovered in (used by model:types for the module path). */\n file?: string\n}\n\nconst MODEL_FILE = /^(?!.*\\.d\\.[mc]?ts$).+\\.(ts|js|mts|mjs)$/\n\n/**\n * The application's models, auto-discovered from app/Models: route model binding ({post} → Post), model:types,\n * and morphTo (through the ClassRegistry) look models up here by name.\n */\nexport class ModelRegistry {\n private readonly models = new Map<string, RegisteredModel>()\n\n /** Registers a model class (booting it, so static scope proxies such as Post.published() exist). */\n register(model: typeof Model, file?: string): RegisteredModel {\n const entry: RegisteredModel = { name: model.name, model, file }\n this.models.set(model.name, entry)\n model.bootIfNotBooted()\n return entry\n }\n\n /** Imports every file under `directory` and registers each exported Model subclass. */\n async discover(directory: string): Promise<RegisteredModel[]> {\n const found: RegisteredModel[] = []\n for (const file of listFiles(directory)) {\n const module = (await import(pathToFileURL(file).href)) as Record<string, unknown>\n for (const exported of Object.values(module)) {\n if (typeof exported === 'function' && exported.prototype instanceof Model && !this.models.has(exported.name)) {\n found.push(this.register(exported as typeof Model, file))\n }\n }\n }\n return found\n }\n\n /** A model by class name or route parameter name: 'Post', 'post', 'blog_post' and 'blogPost' find BlogPost. */\n get(name: string): RegisteredModel | undefined {\n return this.models.get(name) ?? this.models.get(Str.studly(name))\n }\n\n resolve(name: string): typeof Model | undefined {\n return this.get(name)?.model\n }\n\n has(name: string): boolean {\n return this.get(name) !== undefined\n }\n\n all(): RegisteredModel[] {\n return [...this.models.values()]\n }\n}\n\nfunction listFiles(directory: string): string[] {\n if (!existsSync(directory)) return []\n const files: string[] = []\n for (const entry of readdirSync(directory).sort()) {\n const path = join(directory, entry)\n if (statSync(path).isDirectory()) files.push(...listFiles(path))\n else if (MODEL_FILE.test(entry)) files.push(path)\n }\n return files\n}\n","import { randomUUID } from 'node:crypto'\nimport { DatabaseError, LogicError } from '../../errors'\n\nconst FIRST_NAMES = [\n 'Taylor', 'Abigail', 'Dayle', 'Mohamed', 'Jess', 'Nuno', 'James', 'Tim', 'Joe', 'Dries', 'Ana', 'Maria', 'Sofia',\n 'Liam', 'Noah', 'Emma', 'Olivia', 'Ava', 'Mia', 'Lucas', 'Hugo', 'Lea', 'Ines', 'Yuki', 'Aarav', 'Zara', 'Omar',\n 'Chloe', 'Ethan', 'Grace', 'Isaac', 'Julia', 'Kai', 'Leo', 'Nora', 'Owen', 'Priya', 'Quinn', 'Ruby', 'Sam',\n]\nconst LAST_NAMES = [\n 'Otwell', 'Smith', 'Johnson', 'Brown', 'Garcia', 'Miller', 'Davis', 'Martin', 'Lopez', 'Wilson', 'Anderson',\n 'Thomas', 'Moore', 'Jackson', 'White', 'Harris', 'Clark', 'Lewis', 'Walker', 'Hall', 'Young', 'King', 'Wright',\n 'Scott', 'Green', 'Baker', 'Adams', 'Nelson', 'Hill', 'Campbell', 'Mitchell', 'Roberts', 'Carter', 'Phillips',\n]\nconst WORDS = [\n 'lorem', 'ipsum', 'dolor', 'sit', 'amet', 'consectetur', 'adipiscing', 'elit', 'sed', 'do', 'eiusmod', 'tempor',\n 'incididunt', 'ut', 'labore', 'et', 'dolore', 'magna', 'aliqua', 'enim', 'ad', 'minim', 'veniam', 'quis', 'nostrud',\n 'exercitation', 'ullamco', 'laboris', 'nisi', 'aliquip', 'ex', 'ea', 'commodo', 'consequat', 'duis', 'aute',\n 'irure', 'in', 'reprehenderit', 'voluptate', 'velit', 'esse', 'cillum', 'fugiat', 'nulla', 'pariatur', 'excepteur',\n 'sint', 'occaecat', 'cupidatat', 'non', 'proident', 'sunt', 'culpa', 'qui', 'officia', 'deserunt', 'mollit', 'anim',\n]\nconst DOMAINS = ['example.com', 'example.org', 'example.net']\nconst CITIES = ['Springfield', 'Riverside', 'Fairview', 'Madison', 'Georgetown', 'Clinton', 'Salem', 'Franklin', 'Greenville', 'Bristol']\nconst COUNTRIES = ['France', 'Japan', 'Brazil', 'Canada', 'India', 'Kenya', 'Spain', 'Norway', 'Chile', 'Vietnam']\nconst COMPANY_SUFFIXES = ['Inc', 'LLC', 'Group', 'Ltd', 'and Sons']\n\n/** Thrown by fake().unique() when it can't find a new value (Laravel's OverflowException). */\nexport class FakerOverflowError extends DatabaseError {\n override readonly name = 'FakerOverflowError'\n}\n\nconst DURATION = /^([+-]?\\d+)\\s*(second|minute|hour|day|week|month|year)s?$/i\nconst UNIT_MS: Record<string, number> = {\n second: 1000, minute: 60_000, hour: 3_600_000, day: 86_400_000, week: 604_800_000, month: 2_629_800_000, year: 31_557_600_000,\n}\n\n/**\n * A small built-in fake data generator for factories and tests (the subset of Faker that factories typically use).\n * Seedable for repeatable data: fake().seed(1234). For anything richer, use sequence() or plain JavaScript.\n */\nexport class Faker {\n private state = Math.floor(Math.random() * 2 ** 32)\n private uniqueProxy: Faker | undefined\n private readonly seen = new Map<string, Set<unknown>>()\n\n /** Makes the sequence repeatable. */\n seed(seed: number): this {\n this.state = seed >>> 0\n return this\n }\n\n /** A float in [0, 1) (mulberry32). */\n random(): number {\n this.state = (this.state + 0x6d2b79f5) >>> 0\n let t = this.state\n t = Math.imul(t ^ (t >>> 15), t | 1)\n t ^= t + Math.imul(t ^ (t >>> 7), t | 61)\n return ((t ^ (t >>> 14)) >>> 0) / 4294967296\n }\n\n /**\n * The same generator, but every call returns a value it hasn't returned before (per method). reset clears the\n * memory. Throws FakerOverflowError after 10000 tries.\n */\n unique(reset = false): Faker {\n if (reset) this.seen.clear()\n this.uniqueProxy ??= new Proxy(this, {\n get: (target, key, receiver) => {\n const value: unknown = Reflect.get(target, key, receiver)\n if (typeof value !== 'function' || typeof key === 'symbol' || key === 'unique' || key === 'seed' || key === 'random') return value\n return (...args: unknown[]) => {\n const seen = target.seen.get(key) ?? new Set<unknown>()\n target.seen.set(key, seen)\n for (let i = 0; i < 10_000; i++) {\n const candidate: unknown = (value as (...a: unknown[]) => unknown).apply(target, args)\n const fingerprint = typeof candidate === 'object' ? JSON.stringify(candidate) : candidate\n if (!seen.has(fingerprint)) {\n seen.add(fingerprint)\n return candidate\n }\n }\n throw new FakerOverflowError('Maximum retries of 10000 reached without finding a unique value')\n }\n },\n })\n return this.uniqueProxy\n }\n\n numberBetween(min = 0, max = 2147483647): number {\n return Math.floor(this.random() * (max - min + 1)) + min\n }\n\n /** A random integer with up to `digits` digits (strict: exactly that many). */\n randomNumber(digits = 9, strict = false): number {\n const max = 10 ** digits - 1\n return strict ? this.numberBetween(10 ** (digits - 1), max) : this.numberBetween(0, max)\n }\n\n randomFloat(decimals = 2, min = 0, max = 1000): number {\n return Number((this.random() * (max - min) + min).toFixed(decimals))\n }\n\n randomDigit(): number {\n return this.numberBetween(0, 9)\n }\n\n /** true with `chanceOfGettingTrue` percent. */\n boolean(chanceOfGettingTrue = 50): boolean {\n return this.random() * 100 < chanceOfGettingTrue\n }\n\n randomElement<T>(items: readonly T[]): T {\n if (!items.length) throw new LogicError('randomElement() needs at least one item.')\n return items[this.numberBetween(0, items.length - 1)]!\n }\n\n /** `count` distinct items, in random order. */\n randomElements<T>(items: readonly T[], count = 1): T[] {\n const pool = [...items]\n const picked: T[] = []\n while (picked.length < count && pool.length) picked.push(pool.splice(this.numberBetween(0, pool.length - 1), 1)[0]!)\n return picked\n }\n\n shuffle<T>(items: readonly T[]): T[] {\n return this.randomElements(items, items.length)\n }\n\n firstName(): string {\n return this.randomElement(FIRST_NAMES)\n }\n\n lastName(): string {\n return this.randomElement(LAST_NAMES)\n }\n\n name(): string {\n return `${this.firstName()} ${this.lastName()}`\n }\n\n userName(): string {\n return `${this.firstName().toLowerCase()}.${this.lastName().toLowerCase()}${this.numberBetween(1, 999)}`\n }\n\n /** An address at example.com/org/net, which never delivers mail. */\n safeEmail(): string {\n return `${this.userName()}@${this.randomElement(DOMAINS)}`\n }\n\n email(): string {\n return this.safeEmail()\n }\n\n word(): string {\n return this.randomElement(WORDS)\n }\n\n words(count = 3): string[] {\n return Array.from({ length: count }, () => this.word())\n }\n\n sentence(words = 6): string {\n const text = this.words(Math.max(1, words)).join(' ')\n return `${text.charAt(0).toUpperCase()}${text.slice(1)}.`\n }\n\n sentences(count = 3): string[] {\n return Array.from({ length: count }, () => this.sentence(this.numberBetween(4, 10)))\n }\n\n paragraph(sentences = 3): string {\n return this.sentences(sentences).join(' ')\n }\n\n paragraphs(count = 3): string[] {\n return Array.from({ length: count }, () => this.paragraph())\n }\n\n /** Text of at most `maxChars` characters. */\n text(maxChars = 200): string {\n let text = ''\n while (text.length < maxChars) text = text ? `${text} ${this.sentence()}` : this.sentence()\n return text.slice(0, maxChars).trimEnd()\n }\n\n slug(words = 3): string {\n return this.words(words).join('-')\n }\n\n title(): string {\n return this.sentence(this.numberBetween(2, 5)).slice(0, -1)\n }\n\n url(): string {\n return `https://${this.randomElement(DOMAINS)}/${this.slug()}`\n }\n\n city(): string {\n return this.randomElement(CITIES)\n }\n\n country(): string {\n return this.randomElement(COUNTRIES)\n }\n\n company(): string {\n return `${this.lastName()} ${this.randomElement(COMPANY_SUFFIXES)}`\n }\n\n phoneNumber(): string {\n return this.numerify('+1-###-###-####')\n }\n\n uuid(): string {\n return randomUUID()\n }\n\n /** Replaces every # with a digit. */\n numerify(pattern = '###'): string {\n return pattern.replace(/#/g, () => String(this.randomDigit()))\n }\n\n /** Replaces every ? with a letter. */\n lexify(pattern = '????'): string {\n return pattern.replace(/\\?/g, () => String.fromCharCode(97 + this.numberBetween(0, 25)))\n }\n\n /** numerify() and lexify() together. */\n bothify(pattern = '## ??'): string {\n return this.lexify(this.numerify(pattern))\n }\n\n hexColor(): string {\n return `#${this.numberBetween(0, 0xffffff).toString(16).padStart(6, '0')}`\n }\n\n /** A date between two points ('-30 years', 'now', '+1 week', a Date). */\n dateTimeBetween(start: Date | string = '-30 years', end: Date | string = 'now'): Date {\n const from = this.resolveDate(start).getTime()\n const to = this.resolveDate(end).getTime()\n return new Date(Math.floor(from + this.random() * (to - from)))\n }\n\n /** A date before `max` (default now). */\n dateTime(max: Date | string = 'now'): Date {\n return this.dateTimeBetween(new Date(0), max)\n }\n\n /** A Y-m-d date string before `max`. */\n date(max: Date | string = 'now'): string {\n return this.dateTime(max).toISOString().slice(0, 10)\n }\n\n private resolveDate(value: Date | string): Date {\n if (value instanceof Date) return value\n if (value === 'now') return new Date()\n const match = DURATION.exec(value.trim())\n if (match) return new Date(Date.now() + Number(match[1]) * UNIT_MS[match[2]!.toLowerCase()]!)\n const parsed = new Date(value)\n if (Number.isNaN(parsed.getTime())) throw new LogicError(`Unable to parse [${value}] as a date.`)\n return parsed\n }\n}\n\nlet shared: Faker | undefined\n\n/** The shared fake data generator (Laravel's fake() helper): fake().name(), fake().unique().safeEmail(). */\nexport function fake(): Faker {\n return (shared ??= new Faker())\n}\n","import type { Class, RouteModelResolver } from '@orieljs/contracts'\nimport { Model } from './Eloquent/Model'\nimport { LogicError, ModelNotFoundError } from './errors'\nimport type { ModelRegistry } from './ModelRegistry'\n\n/**\n * Route model binding for the router: {post} → Post (StudlyCase of the parameter, from the app/Models registry),\n * {post:slug} → Post where slug = value, Route.model('author', User) → resolveExplicit(User, …).\n * Named RouteModelResolverImpl so it never shadows the RouteModelResolver token.\n */\nexport class RouteModelResolverImpl implements RouteModelResolver {\n constructor(private readonly registry: ModelRegistry) {}\n\n /** undefined when no model is called `parameter` (the router keeps the string); throws ModelNotFoundError (404) when the row is missing. */\n async resolve(parameter: string, value: string, field?: string): Promise<unknown | undefined> {\n const model = this.registry.resolve(parameter)\n if (!model) return undefined\n return this.resolveExplicit(model, value, field)\n }\n\n /** The model of `model` whose route key (or `field`) equals value; ModelNotFoundError (404) when there is none. */\n async resolveExplicit(model: Class<unknown>, value: string, field?: string): Promise<unknown> {\n if (!(model.prototype instanceof Model)) throw new LogicError(`Route model binding needs a Model class; [${model.name}] isn't one.`)\n const cls = model as unknown as typeof Model\n const found = await cls.prototypeInstance().resolveRouteBinding(value, field)\n if (!found) throw new ModelNotFoundError(cls.name, [value])\n return found\n }\n}\n","import {\n Application,\n ClassRegistry,\n ConfigRepository,\n ConsoleKernel,\n DatabaseManager,\n HttpRequest,\n RouteModelResolver,\n} from '@orieljs/contracts'\nimport { currentContainer } from '@orieljs/container'\nimport { ServiceProvider } from '@orieljs/support'\nimport { registerMigrationCommands, registerModelTypesCommand, type DatabaseCommandContext } from './Console/commands'\nimport { DatabaseManagerImpl, type DatabaseConfig } from './DatabaseManager'\nimport { discoverFactories } from './Eloquent/Factories/Factory'\nimport { Model } from './Eloquent/Model'\nimport { SchemaBuilderToken } from './facades'\nimport { ModelRegistry } from './ModelRegistry'\nimport { AbstractPaginator } from './Pagination/AbstractPaginator'\nimport { RouteModelResolverImpl } from './RouteModelResolver'\n\nconst env = (key: string, fallback?: string): string | undefined => {\n const value = process.env[key]\n return value === undefined || value === '' ? fallback : value\n}\n\n/** Laravel 11's config/database.php defaults (the app's config/database.ts wins, key by key). */\nexport function databaseConfigDefaults(app: Pick<Application, 'databasePath'>): DatabaseConfig & Record<string, unknown> {\n return {\n default: env('DB_CONNECTION', 'sqlite')!,\n connections: {\n sqlite: {\n driver: 'sqlite',\n url: env('DB_URL'),\n database: env('DB_DATABASE', app.databasePath('database.sqlite')),\n foreign_key_constraints: env('DB_FOREIGN_KEYS', 'true') !== 'false',\n },\n mysql: {\n driver: 'mysql',\n url: env('DB_URL'),\n host: env('DB_HOST', '127.0.0.1'),\n port: env('DB_PORT', '3306'),\n database: env('DB_DATABASE', 'laravel'),\n username: env('DB_USERNAME', 'root'),\n password: env('DB_PASSWORD', ''),\n charset: env('DB_CHARSET', 'utf8mb4'),\n collation: env('DB_COLLATION', 'utf8mb4_unicode_ci'),\n },\n pgsql: {\n driver: 'pgsql',\n url: env('DB_URL'),\n host: env('DB_HOST', '127.0.0.1'),\n port: env('DB_PORT', '5432'),\n database: env('DB_DATABASE', 'laravel'),\n username: env('DB_USERNAME', 'root'),\n password: env('DB_PASSWORD', ''),\n charset: env('DB_CHARSET', 'utf8'),\n search_path: 'public',\n },\n },\n migrations: { table: 'migrations', update_date_on_publish: true } as DatabaseConfig['migrations'],\n // Laravel keeps the Redis connections here; Cache, Queue and Session resolve database.redis.<connection>.\n redis: {\n client: 'ioredis',\n default: { url: env('REDIS_URL'), host: '127.0.0.1', port: 6379, password: undefined, db: 0 },\n cache: { url: env('REDIS_URL'), host: '127.0.0.1', port: 6379, password: undefined, db: 1 },\n },\n }\n}\n\n/** The current request, when the current container is a request scope with one. */\nfunction currentRequest(): HttpRequest | undefined {\n const container = currentContainer()\n if (!container?.bound(HttpRequest)) return undefined\n try {\n return container.make(HttpRequest)\n } catch {\n return undefined // scoped binding resolved outside a request scope (R13)\n }\n}\n\n/** Points the paginators at the current request: ?page=, ?cursor=, the URL and the query string (Laravel's resolvers). */\nexport function usePaginationResolvers(): void {\n AbstractPaginator.currentPathResolver = () => currentRequest()?.url() ?? '/'\n AbstractPaginator.currentPageResolver = (pageName) => {\n const page = Number(currentRequest()?.input(pageName))\n return Number.isInteger(page) && page >= 1 ? page : 1\n }\n AbstractPaginator.queryStringResolver = () => (currentRequest()?.query<Record<string, unknown>>() ?? {})\n AbstractPaginator.currentCursorResolver = (cursorName) => currentRequest()?.input(cursorName)\n}\n\n/**\n * Binds the database layer: the DatabaseManager (a root singleton owning the pools) behind the DB facade, the\n * Schema facade's SchemaBuilder, the ModelRegistry and the RouteModelResolver. At boot it discovers app/Models,\n * factories (console and tests), points pagination at the current request, and registers the migrate*, db:seed,\n * make:migration and model:types commands when a ConsoleKernel is bound. It also merges Laravel's database.redis\n * connections, which Cache, Queue and Session read.\n */\nexport class DatabaseServiceProvider extends ServiceProvider {\n override register(): void {\n // Models booted by an earlier application (tests make one per test) boot again, so the listeners that\n // static booted() registers reach this application's EventDispatcher.\n Model.clearBootedModels()\n this.mergeConfigFrom(databaseConfigDefaults(this.app), 'database')\n this.app.singleton(DatabaseManager, () => new DatabaseManagerImpl(() => this.app.make(ConfigRepository).get<DatabaseConfig>('database')))\n this.app.singleton(ModelRegistry)\n this.app.singleton(RouteModelResolver, () => new RouteModelResolverImpl(this.app.make(ModelRegistry)))\n this.app.bind(SchemaBuilderToken, () => this.manager().getSchemaBuilder())\n }\n\n override async boot(): Promise<void> {\n usePaginationResolvers()\n const registry = this.app.make(ModelRegistry)\n const classes = this.app.bound(ClassRegistry) ? this.app.make(ClassRegistry) : undefined\n for (const entry of await registry.discover(this.app.appPath('Models'))) {\n // Queue and Live serialize models as class name + key.\n if (classes && !classes.has(entry.name)) classes.register(entry.model, entry.name)\n }\n if (this.app.runningInConsole() || this.app.runningUnitTests()) await discoverFactories(this.app.databasePath('factories'))\n if (this.app.bound(ConsoleKernel)) {\n const kernel = this.app.make(ConsoleKernel)\n const context: DatabaseCommandContext = { app: this.app, manager: () => this.manager(), models: async () => registry }\n registerMigrationCommands(kernel, context)\n registerModelTypesCommand(kernel, context)\n }\n }\n\n private manager(): DatabaseManagerImpl {\n return this.app.make(DatabaseManager) as DatabaseManagerImpl\n }\n}\n","import type { OrielError } from '@orieljs/contracts'\n\n/**\n * Encryption errors use the 'Server' kind: Http's handler reports them and renders a generic 500 (the message is\n * shown only with app.debug), like Laravel's DecryptException/EncryptException/MissingAppKeyException.\n */\nabstract class EncryptionFailure extends Error implements OrielError {\n readonly kind = 'Server' as const\n readonly status = 500\n}\n\nexport class DecryptError extends EncryptionFailure {\n override readonly name = 'DecryptError'\n}\n\nexport class EncryptError extends EncryptionFailure {\n override readonly name = 'EncryptError'\n}\n\nexport class MissingAppKeyError extends EncryptionFailure {\n override readonly name = 'MissingAppKeyError'\n constructor(message = 'No application encryption key has been specified.') {\n super(message)\n }\n}\n\nexport class UnsupportedCipherError extends EncryptionFailure {\n override readonly name = 'UnsupportedCipherError'\n constructor() {\n super(\n 'Unsupported cipher or incorrect key length. Supported ciphers are: aes-128-cbc, aes-256-cbc, aes-128-gcm, aes-256-gcm.',\n )\n }\n}\n","import { createCipheriv, createDecipheriv, createHmac, randomBytes, timingSafeEqual } from 'node:crypto'\nimport type { Encrypter as EncrypterContract } from '@orieljs/contracts'\nimport { DecryptError, EncryptError, MissingAppKeyError, UnsupportedCipherError } from './errors'\n\nexport type CipherName = 'aes-128-cbc' | 'aes-256-cbc' | 'aes-128-gcm' | 'aes-256-gcm'\n\ninterface CipherSpec {\n size: number\n aead: boolean\n ivLength: number\n}\n\n/** Laravel's Encrypter::$supportedCiphers, with the IV length openssl_cipher_iv_length() reports. */\nconst CIPHERS: Record<CipherName, CipherSpec> = {\n 'aes-128-cbc': { size: 16, aead: false, ivLength: 16 },\n 'aes-256-cbc': { size: 32, aead: false, ivLength: 16 },\n 'aes-128-gcm': { size: 16, aead: true, ivLength: 12 },\n 'aes-256-gcm': { size: 32, aead: true, ivLength: 12 },\n}\n\ninterface Payload {\n iv: string\n value: string\n mac: string\n tag?: string\n}\n\nconst cipherSpec = (cipher: string): CipherSpec | undefined =>\n Object.hasOwn(CIPHERS, cipher.toLowerCase()) ? CIPHERS[cipher.toLowerCase() as CipherName] : undefined\n\n/** Constant-time string comparison (hash_equals). */\nfunction equals(known: string, user: string): boolean {\n const a = Buffer.from(known)\n const b = Buffer.from(user)\n return a.length === b.length && timingSafeEqual(a, b)\n}\n\n/**\n * Turns config('app.key') into key bytes: `base64:...` is decoded, anything else is used as UTF-8 bytes\n * (Laravel's EncryptionServiceProvider::parseKey). Throws MissingAppKeyError when the key is empty.\n */\nexport function parseKey(key: string | undefined | null): Uint8Array {\n if (typeof key !== 'string' || key === '') throw new MissingAppKeyError()\n return key.startsWith('base64:') ? new Uint8Array(Buffer.from(key.slice(7), 'base64')) : new Uint8Array(Buffer.from(key, 'utf8'))\n}\n\n/**\n * Laravel's Illuminate\\Encryption\\Encrypter. Payloads are base64(JSON {iv, value, mac, tag}):\n * - CBC: `value` is base64 ciphertext, `mac` = hex HMAC-SHA256(iv + value) under the key, `tag` is ''.\n * - GCM: `mac` is '' and `tag` is the base64 authentication tag.\n * Values are JSON-serialized (not PHP-serialized), so only encryptString() payloads are interchangeable with PHP.\n */\nexport class Encrypter implements EncrypterContract {\n readonly #key: Uint8Array\n readonly #cipher: CipherName\n #previousKeys: Uint8Array[] = []\n\n constructor(key: Uint8Array, cipher: string = 'aes-256-gcm') {\n if (!Encrypter.supported(key, cipher)) throw new UnsupportedCipherError()\n this.#key = key\n this.#cipher = cipher.toLowerCase() as CipherName\n }\n\n /** Whether the key length fits the cipher. */\n static supported(key: Uint8Array, cipher: string): boolean {\n const spec = cipherSpec(cipher)\n return spec !== undefined && key.byteLength === spec.size\n }\n\n /** Random key bytes for the cipher (key:generate base64-encodes them). */\n static generateKey(cipher: string = 'aes-256-gcm'): Uint8Array {\n const spec = cipherSpec(cipher)\n if (spec === undefined) throw new UnsupportedCipherError()\n return new Uint8Array(randomBytes(spec.size))\n }\n\n encrypt(value: unknown, serialize = true): string {\n const plain = serialize ? JSON.stringify(value) : value\n if (typeof plain !== 'string') throw new EncryptError('Could not encrypt the data.')\n const spec = CIPHERS[this.#cipher]\n const ivBytes = randomBytes(spec.ivLength)\n let encrypted: string\n let tagBytes: Buffer | undefined\n try {\n const cipher = createCipheriv(this.#cipher, this.#key, ivBytes)\n encrypted = cipher.update(plain, 'utf8', 'base64') + cipher.final('base64')\n if (spec.aead) tagBytes = (cipher as unknown as { getAuthTag(): Buffer }).getAuthTag()\n } catch {\n throw new EncryptError('Could not encrypt the data.')\n }\n const iv = ivBytes.toString('base64')\n const tag = tagBytes?.toString('base64') ?? ''\n const mac = spec.aead ? '' : this.#hash(iv, encrypted, this.#key)\n return Buffer.from(JSON.stringify({ iv, value: encrypted, mac, tag })).toString('base64')\n }\n\n encryptString(value: string): string {\n return this.encrypt(value, false)\n }\n\n decrypt<T = unknown>(payload: string, unserialize = true): T {\n const data = this.#payload(payload)\n const spec = CIPHERS[this.#cipher]\n const iv = Buffer.from(data.iv, 'base64')\n const tag = data.tag === undefined || data.tag === '' ? undefined : Buffer.from(data.tag, 'base64')\n if (spec.aead && tag?.length !== 16) throw new DecryptError('Could not decrypt the data.')\n if (!spec.aead && tag !== undefined) {\n throw new DecryptError('Unable to use tag because the cipher algorithm does not support AEAD.')\n }\n\n let foundValidMac = false\n let decrypted: string | undefined\n for (const key of this.getAllKeys()) {\n if (!spec.aead) {\n foundValidMac = foundValidMac || equals(this.#hash(data.iv, data.value, key), data.mac)\n if (!foundValidMac) continue\n }\n decrypted = this.#decryptWith(key, iv, data.value, tag)\n if (decrypted !== undefined) break\n }\n if (!spec.aead && !foundValidMac) throw new DecryptError('The MAC is invalid.')\n if (decrypted === undefined) throw new DecryptError('Could not decrypt the data.')\n if (!unserialize) return decrypted as T\n try {\n return JSON.parse(decrypted) as T\n } catch {\n throw new DecryptError('Could not decrypt the data.')\n }\n }\n\n decryptString(payload: string): string {\n return this.decrypt<string>(payload, false)\n }\n\n getKey(): Uint8Array {\n return this.#key\n }\n\n /** The current key first, then the previous keys (Laravel's getAllKeys()). */\n getAllKeys(): Uint8Array[] {\n return [this.#key, ...this.#previousKeys]\n }\n\n getPreviousKeys(): Uint8Array[] {\n return [...this.#previousKeys]\n }\n\n /** Keys that still decrypt (config('app.previous_keys')). Each must fit the cipher. */\n previousKeys(keys: Uint8Array[]): this {\n for (const key of keys) if (!Encrypter.supported(key, this.#cipher)) throw new UnsupportedCipherError()\n this.#previousKeys = [...keys]\n return this\n }\n\n #hash(iv: string, value: string, key: Uint8Array): string {\n return createHmac('sha256', key).update(iv + value).digest('hex')\n }\n\n #decryptWith(key: Uint8Array, iv: Buffer, value: string, tag: Buffer | undefined): string | undefined {\n try {\n const decipher = createDecipheriv(this.#cipher, key, iv)\n if (tag !== undefined) (decipher as unknown as { setAuthTag(tag: Buffer): void }).setAuthTag(tag)\n return decipher.update(value, 'base64', 'utf8') + decipher.final('utf8')\n } catch {\n return undefined\n }\n }\n\n /** Decodes and validates the payload (Laravel's getJsonPayload + validPayload). */\n #payload(payload: string): Payload {\n let data: unknown\n try {\n data = typeof payload === 'string' ? JSON.parse(Buffer.from(payload, 'base64').toString('utf8')) : undefined\n } catch {\n data = undefined\n }\n if (typeof data !== 'object' || data === null || Array.isArray(data)) throw new DecryptError('The payload is invalid.')\n const record = data as Record<string, unknown>\n for (const item of ['iv', 'value', 'mac']) {\n if (typeof record[item] !== 'string') throw new DecryptError('The payload is invalid.')\n }\n if (record.tag !== undefined && record.tag !== null && typeof record.tag !== 'string') {\n throw new DecryptError('The payload is invalid.')\n }\n if (Buffer.from(record.iv as string, 'base64').length !== CIPHERS[this.#cipher].ivLength) {\n throw new DecryptError('The payload is invalid.')\n }\n return {\n iv: record.iv as string,\n value: record.value as string,\n mac: record.mac as string,\n ...(typeof record.tag === 'string' ? { tag: record.tag } : {}),\n }\n }\n}\n","import { readFile, writeFile } from 'node:fs/promises'\nimport {\n ConfigRepository,\n Encrypter as EncrypterToken,\n type Application,\n type CommandContext,\n type ConsoleKernel,\n} from '@orieljs/contracts'\nimport { Encrypter } from './Encrypter'\n\n/** The part of Console's closure-command `this` (CommandContext) that key:generate uses. */\nexport type KeyGenerateIO = Pick<CommandContext, 'option' | 'info' | 'line' | 'error'>\n\nexport const KEY_GENERATE_SIGNATURE =\n 'key:generate {--show : Display the key instead of modifying files} {--force : Force the operation to run when in production}'\n\n/** A fresh `base64:` key for the configured cipher. */\nexport function generateAppKey(cipher: string = 'aes-256-gcm'): string {\n return `base64:${Buffer.from(Encrypter.generateKey(cipher)).toString('base64')}`\n}\n\n/** Laravel's KeyGenerateCommand, as a closure-command handler (`this` is Console's CommandContext). */\nexport function keyGenerateHandler(app: Application): (this: KeyGenerateIO) => Promise<number> {\n return async function (this: KeyGenerateIO): Promise<number> {\n const config = app.make(ConfigRepository)\n const key = generateAppKey(String(config.get('app.cipher', 'aes-256-gcm')))\n if (this.option('show') === true) {\n this.line(key)\n return 0\n }\n\n const current = config.get<unknown>('app.key', '')\n if (typeof current === 'string' && current !== '' && app.isProduction() && this.option('force') !== true) {\n this.error('Application In Production! Use --force to replace the existing application key.')\n return 1\n }\n\n const path = app.basePath('.env')\n const contents = await readFile(path, 'utf8').catch(() => undefined)\n const pattern = /^APP_KEY=.*$/m\n if (contents === undefined || !pattern.test(contents)) {\n this.error('Unable to set application key. No APP_KEY variable was found in the .env file.')\n return 1\n }\n await writeFile(path, contents.replace(pattern, () => `APP_KEY=${key}`))\n config.set('app.key', key)\n app.forgetInstance(EncrypterToken)\n this.info('Application key set successfully.')\n return 0\n }\n}\n\n/** Registers `key:generate` on the console kernel (closure command, PC1). */\nexport function registerKeyGenerateCommand(kernel: ConsoleKernel, app: Application): void {\n kernel.command(KEY_GENERATE_SIGNATURE, keyGenerateHandler(app)).purpose('Set the application key')\n}\n","import { Encrypter } from '@orieljs/contracts'\nimport { inject } from '@orieljs/container'\nimport { facade } from '@orieljs/support'\n\n/** The Crypt facade (Laravel's Illuminate\\Support\\Facades\\Crypt). */\nexport const Crypt = facade(Encrypter)\n\n/** encrypt() helper: JSON-serializes unless serialize is false. */\nexport function encrypt(value: unknown, serialize = true): string {\n return inject(Encrypter).encrypt(value, serialize)\n}\n\n/** decrypt() helper. */\nexport function decrypt<T = unknown>(payload: string, unserialize = true): T {\n return inject(Encrypter).decrypt<T>(payload, unserialize)\n}\n","import { ConfigRepository, ConsoleKernel, Encrypter as EncrypterToken } from '@orieljs/contracts'\nimport { ServiceProvider } from '@orieljs/support'\nimport { Encrypter, parseKey } from './Encrypter'\nimport { registerKeyGenerateCommand } from './KeyGenerateCommand'\n\n/** config('app.previous_keys'): an array, or a comma-separated string (APP_PREVIOUS_KEYS). */\nfunction previousKeys(value: unknown): string[] {\n const list = Array.isArray(value) ? value : typeof value === 'string' ? value.split(',') : []\n return list.map((key) => String(key).trim()).filter((key) => key !== '')\n}\n\nexport class EncryptionServiceProvider extends ServiceProvider {\n override register(): void {\n this.mergeConfigFrom({ cipher: 'AES-256-GCM', previous_keys: [] }, 'app')\n this.app.singleton(EncrypterToken, (container) => {\n const config = container.make(ConfigRepository)\n const encrypter = new Encrypter(parseKey(config.get<string | undefined>('app.key')), String(config.get('app.cipher', 'AES-256-GCM')))\n return encrypter.previousKeys(previousKeys(config.get('app.previous_keys')).map((key) => parseKey(key)))\n })\n }\n\n override boot(): void {\n if (this.app.bound(ConsoleKernel)) registerKeyGenerateCommand(this.app.make(ConsoleKernel), this.app)\n }\n}\n","import type { Job } from '@orieljs/contracts'\nimport { ClassRegistry } from '@orieljs/contracts'\nimport { inject } from '@orieljs/container'\nimport { InvalidListenerError } from './errors'\n\nconst SHOULD_QUEUE = Symbol.for('oriel:bus.shouldQueue')\n\ntype ListenerMembers = Record<string, ((...args: unknown[]) => unknown) | undefined>\n\n/**\n * Wraps a queued listener call as a job (Laravel's CallQueuedListener). Always queueable: Dispatcher only ever\n * builds one after it already decided the wrapped listener wants queueing, so this wrapper's own queueability is\n * unconditional — set on its prototype below — unlike the structural, opt-in check `isQueueableListener()` runs on\n * the wrapped listener itself. Forwards `failed()`, `displayName()`, `retryUntil()` and `middleware()` to a fresh\n * instance of the wrapped listener (the Queue/Bus protocol), so a failing queued listener's own\n * `failed()` hook runs, `queue:failed`/`displayName()` shows the listener's own class name instead of\n * `CallQueuedListener`, and a listener's own `retryUntil()`/`middleware()` are honoured. `delay` (like `queue`,\n * `connection`, `tries`, `backoff`, `timeout`) is a plain field, copied by `Dispatcher.queue()` from\n * `queueOptionsOf()` — never a method — so it needs no forwarding here.\n */\nexport class CallQueuedListener implements Job {\n connection?: string\n queue?: string\n delay?: number\n tries?: number\n backoff?: number | number[]\n timeout?: number\n\n constructor(\n public readonly listenerClass: string,\n public readonly method: string,\n public readonly data: unknown[],\n ) {}\n\n /** A fresh listener instance, resolved through the container (never called with constructor arguments — DI only). */\n private resolve(): ListenerMembers {\n const registry = inject(ClassRegistry)\n const cls = registry.resolve(this.listenerClass)\n return inject(cls) as unknown as ListenerMembers\n }\n\n async handle(): Promise<void> {\n const instance = this.resolve()\n const method = instance[this.method]\n if (typeof method !== 'function') throw new InvalidListenerError(this.listenerClass)\n await method.apply(instance, this.data)\n }\n\n async failed(error: unknown): Promise<void> {\n await this.resolve().failed?.(...this.data, error)\n }\n\n displayName(): string {\n return this.listenerClass\n }\n\n retryUntil(): unknown {\n return this.resolve().retryUntil?.()\n }\n\n middleware(): unknown[] {\n return (this.resolve().middleware?.() as unknown[] | undefined) ?? []\n }\n}\n;(CallQueuedListener.prototype as unknown as Record<symbol, boolean>)[SHOULD_QUEUE] = true\n","import type { OrielError } from '@orieljs/contracts'\n\nexport class InvalidListenerError extends Error implements OrielError {\n readonly kind = 'Server' as const\n override readonly name = 'InvalidListenerError'\n constructor(event: string) {\n super(\n `The listener registered for [${event}] is not a function, a class with a handle() method, ` +\n `or a [Class, 'method'] tuple.`,\n )\n }\n}\n\nexport class EventsNeedBusDispatcherError extends Error implements OrielError {\n readonly kind = 'Server' as const\n override readonly name = 'EventsNeedBusDispatcherError'\n constructor(listenerName: string) {\n super(`[${listenerName}] is a queued listener, but no BusDispatcher is bound. Register the BusServiceProvider.`)\n }\n}\n\nexport class EventsNeedClassRegistryError extends Error implements OrielError {\n readonly kind = 'Server' as const\n override readonly name = 'EventsNeedClassRegistryError'\n constructor(listenerName: string) {\n super(`[${listenerName}] is a queued listener, but no ClassRegistry is bound.`)\n }\n}\n","import { existsSync, readdirSync, statSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport type { Class, ClassRegistry, EventDispatcher } from '@orieljs/contracts'\n\nconst EXTENSIONS = ['.ts', '.js', '.mts', '.mjs']\n\nfunction files(directory: string): string[] {\n const found: string[] = []\n for (const entry of readdirSync(directory).sort()) {\n const path = join(directory, entry)\n if (statSync(path).isDirectory()) found.push(...files(path))\n else if (EXTENSIONS.some((extension) => entry.endsWith(extension)) && !entry.endsWith('.d.ts')) found.push(path)\n }\n return found\n}\n\ntype DiscoverableListener = Class<{ handle(...args: unknown[]): unknown }> & {\n listensTo: Class<unknown> | string | Array<Class<unknown> | string>\n}\n\n/**\n * A discoverable listener class: has a handle() method (any listener class does) and a static `listensTo` field\n * naming the event(s) it handles. TS erases parameter types at runtime, so — unlike Laravel's reflection on\n * handle()'s parameter type — Oriel listeners declare what they listen to explicitly:\n * export class SendWelcomeEmail {\n * static listensTo = UserRegistered // a class, a string, or an array of either\n * async handle(event: UserRegistered) { ... }\n * }\n * Any other export (a helper function, a plain type) is silently skipped, not every export in a listener file is\n * necessarily a listener.\n */\nconst isDiscoverableListener = (value: unknown): value is DiscoverableListener =>\n typeof value === 'function' &&\n typeof (value.prototype as { handle?: unknown } | undefined)?.handle === 'function' &&\n 'listensTo' in value\n\n/** Classes already `listen()`ed by discovery itself, per dispatcher — so re-running discovery is a no-op. */\nconst discoveredByDispatcher = new WeakMap<EventDispatcher, WeakSet<Class<unknown>>>()\n\n/**\n * Imports every module under `directory` (recursively), registers each discoverable listener class into `registry`\n * and calls `dispatcher.listen()` for it. Returns the registered names. Safe to call more than once for the same\n * `dispatcher` (a worker process re-importing the same files re-registers each class in `ClassRegistry` — already\n * idempotent — but is not `listen()`ed again).\n */\nexport async function discoverListeners(directory: string, dispatcher: EventDispatcher, registry: ClassRegistry): Promise<string[]> {\n if (!existsSync(directory)) return []\n let discovered = discoveredByDispatcher.get(dispatcher)\n if (!discovered) {\n discovered = new WeakSet()\n discoveredByDispatcher.set(dispatcher, discovered)\n }\n const names: string[] = []\n for (const file of files(directory)) {\n const module = (await import(pathToFileURL(file).href)) as Record<string, unknown>\n for (const exported of Object.values(module)) {\n if (!isDiscoverableListener(exported)) continue\n names.push(registry.nameOf(exported) ?? registry.register(exported))\n if (discovered.has(exported)) continue\n discovered.add(exported)\n const events = Array.isArray(exported.listensTo) ? exported.listensTo : [exported.listensTo]\n dispatcher.listen(events as never, exported as never)\n }\n }\n return names\n}\n","import type { EventDispatcher } from '@orieljs/contracts'\nimport { EventDispatcher as EventDispatcherToken } from '@orieljs/contracts'\nimport { inject } from '@orieljs/container'\nimport { facade } from '@orieljs/support'\n\nexport const Event = facade<EventDispatcher>(EventDispatcherToken)\n\n/** Laravel's event() helper: dispatches through the current container's EventDispatcher. */\nexport function event(eventValue: object | string, payload?: unknown[]): Promise<unknown[]> {\n return inject(EventDispatcherToken).dispatch(eventValue, payload)\n}\n","import {\n ClassRegistry,\n ConfigRepository,\n ConsoleKernel,\n EventDispatcher,\n type Class,\n type CommandContext,\n type Listener,\n} from '@orieljs/contracts'\nimport { ServiceProvider } from '@orieljs/support'\nimport { CallQueuedListener } from './CallQueuedListener'\nimport { discoverListeners } from './discover'\nimport { Dispatcher } from './Dispatcher'\nimport type { ListenerTuple } from './listeners'\n\n/**\n * `config('events.listen')`'s shape. Laravel's EventServiceProvider::$listen is a PHP array keyed by FQCN string\n * constants; TypeScript object keys must be strings, so a real class reference can't be a plain-object key without\n * losing type safety. This is a list of [event, listeners] pairs instead, so either side can be a class reference:\n * [[UserRegistered, [SendWelcomeEmail]], ['order.shipped', [NotifyWarehouse]]]\n */\nexport type EventListenMap = Array<[Class<unknown> | string, Array<Listener<unknown> | ListenerTuple<unknown>>]>\n\nexport class EventServiceProvider extends ServiceProvider {\n override register(): void {\n this.mergeConfigFrom({ discover: true, listen: [] as EventListenMap }, 'events')\n this.app.singleton(EventDispatcher, (container) => new Dispatcher(container))\n // Registered here, not in boot() — a queued listener firing during an earlier provider's boot() must never\n // auto-register CallQueuedListener under the plain 'CallQueuedListener' name before this explicit, namespaced\n // registration runs.\n this.app.make(ClassRegistry).register(CallQueuedListener, 'Events.CallQueuedListener')\n }\n\n override async boot(): Promise<void> {\n const dispatcher = this.app.make(EventDispatcher) as Dispatcher\n const registry = this.app.make(ClassRegistry)\n\n const config = this.app.make(ConfigRepository)\n for (const [event, listeners] of config.get<EventListenMap>('events.listen', [])) {\n for (const listener of listeners) dispatcher.listen(event as never, listener as never)\n }\n\n if (config.get<boolean>('events.discover', true)) {\n await discoverListeners(this.app.appPath('Listeners'), dispatcher, registry)\n }\n\n if (this.app.bound(ConsoleKernel)) {\n const kernel = this.app.make(ConsoleKernel)\n kernel\n .command('event:list', function (this: CommandContext) {\n const rows = dispatcher.registeredEvents()\n if (rows.length === 0) {\n this.line('No events are registered.')\n return 0\n }\n for (const row of rows) this.line(` ${row.event} ${row.listeners} ${row.listeners === 1 ? 'listener' : 'listeners'}`)\n return 0\n })\n .purpose(\"List the application's events and listeners\")\n }\n }\n}\n","import type { Class, Container, EventDispatcher, ListenerClass } from '@orieljs/contracts'\nimport { BusDispatcher, ClassRegistry } from '@orieljs/contracts'\nimport { Str } from '@orieljs/support'\nimport { CallQueuedListener } from './CallQueuedListener'\nimport { EventsNeedBusDispatcherError, EventsNeedClassRegistryError, InvalidListenerError } from './errors'\nimport { isListenerClass, isListenerTuple, type ListenerTuple } from './listeners'\nimport { isQueueableListener, queueOptionsOf } from './queueable'\n\nexport type EventKey = Class<unknown> | string\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- a listener closure's parameter list is arbitrary\ntype Registration<E> = ((...args: any[]) => unknown) | ListenerClass<E> | ListenerTuple<E>\n\nconst nameOf = (key: EventKey): string => (typeof key === 'string' ? key : (key as unknown as { name: string }).name)\n\n/**\n * Laravel's Illuminate\\Events\\Dispatcher, on top of Oriel's Container. dispatch() and until() share run(), which\n * mirrors Dispatcher::dispatch($event, $payload, $halt): halt=true (until()) returns the first non-undefined\n * response and stops; either way, a literal `false` response stops the remaining listeners.\n */\nexport class Dispatcher implements EventDispatcher {\n private readonly listeners = new Map<EventKey, Array<Registration<unknown>>>()\n\n constructor(protected readonly container: Container) {}\n\n listen<E>(events: Class<E> | string | Array<Class<E> | string>, listener: Registration<E>): void {\n if (typeof listener !== 'function' && !isListenerTuple(listener)) {\n const label = Array.isArray(events) ? events.map((e) => nameOf(e as EventKey)).join(', ') : nameOf(events as EventKey)\n throw new InvalidListenerError(label)\n }\n for (const event of (Array.isArray(events) ? events : [events]) as EventKey[]) {\n const list = this.listeners.get(event) ?? []\n list.push(listener as Registration<unknown>)\n this.listeners.set(event, list)\n }\n }\n\n hasListeners(event: Class<unknown> | string): boolean {\n if ((this.listeners.get(event)?.length ?? 0) > 0) return true\n return typeof event === 'string' && this.wildcardPatternsFor(event).some((pattern) => (this.listeners.get(pattern)?.length ?? 0) > 0)\n }\n\n forget(event: Class<unknown> | string): void {\n this.listeners.delete(event)\n }\n\n /** Introspection for the event:list command. Not part of the EventDispatcher contract. */\n registeredEvents(): Array<{ event: string; listeners: number }> {\n const rows: Array<{ event: string; listeners: number }> = []\n for (const [key, list] of this.listeners) rows.push({ event: nameOf(key), listeners: list.length })\n return rows.sort((a, b) => a.event.localeCompare(b.event))\n }\n\n subscribe(subscriber: Class<{ subscribe(events: EventDispatcher): void }>): void {\n const instance = this.container.make(subscriber) as { subscribe: (events: EventDispatcher) => unknown }\n const result = instance.subscribe(this)\n if (!result || typeof result !== 'object') return\n for (const [event, methods] of Object.entries(result as Record<string, string | string[]>)) {\n for (const method of Array.isArray(methods) ? methods : [methods]) {\n this.listen(event, [subscriber, method] as ListenerTuple<unknown>)\n }\n }\n }\n\n async dispatch(event: object | string, payload: unknown[] = []): Promise<unknown[]> {\n return (await this.run(event, payload, false)) as unknown[]\n }\n\n /** Stops at the first listener whose response isn't undefined, and returns it. */\n async until(event: object | string, payload: unknown[] = []): Promise<unknown> {\n return this.run(event, payload, true)\n }\n\n private async run(event: object | string, payload: unknown[], halt: boolean): Promise<unknown> {\n const isString = typeof event === 'string'\n const key: EventKey = isString ? event : (event.constructor as Class<unknown>)\n const args: unknown[] = isString ? payload : [event]\n const responses: unknown[] = []\n for (const { listener, wildcard } of this.listenersFor(key)) {\n const response = await this.call(listener, key, args, wildcard)\n if (halt && response !== undefined) return response\n if (response === false) break\n responses.push(response)\n }\n return halt ? undefined : responses\n }\n\n /**\n * Exact-key listeners first, in registration order, then every matching wildcard pattern's listeners. Both the\n * exact-key list and the set of matching wildcard patterns (and their listeners) are snapshotted into plain\n * arrays before the first listener runs, so a listener that registers another listener for this same event (or\n * a new matching wildcard) while running does not also run in this dispatch — it only runs starting with the\n * next one, like Laravel.\n */\n protected *listenersFor(key: EventKey): Iterable<{ listener: Registration<unknown>; wildcard: boolean }> {\n const exact = [...(this.listeners.get(key) ?? [])]\n const wildcardLists = typeof key === 'string' ? this.wildcardPatternsFor(key).map((pattern) => [...(this.listeners.get(pattern) ?? [])]) : []\n for (const listener of exact) yield { listener, wildcard: false }\n for (const list of wildcardLists) {\n for (const listener of list) yield { listener, wildcard: true }\n }\n }\n\n private wildcardPatternsFor(event: string): string[] {\n const patterns: string[] = []\n for (const key of this.listeners.keys()) {\n if (typeof key === 'string' && key !== event && key.includes('*') && Str.is(key, event)) patterns.push(key)\n }\n return patterns\n }\n\n /**\n * Instantiates class/tuple listeners through the container (listener classes have DI-only constructors, so this\n * is cheap and side-effect-free even when the listener turns out to be queued), then queues instead of invoking\n * inline when the constructed instance opts into queueing (the decision reads the instance, matching the\n * Queue/Bus protocol's own isQueueable(), not just the class's static members).\n */\n protected async call(listener: Registration<unknown>, key: EventKey, args: unknown[], wildcard: boolean): Promise<unknown> {\n const callArgs = wildcard ? [nameOf(key), args] : args\n if (isListenerTuple(listener)) {\n const [cls, method] = listener\n const instance = this.container.make(cls) as Record<string, unknown>\n if (isQueueableListener(cls, instance)) return this.queue(cls, instance, method, callArgs)\n return (instance[method] as (...a: unknown[]) => unknown)(...callArgs)\n }\n if (isListenerClass(listener)) {\n const instance = this.container.make(listener) as Record<string, unknown> & { handle: (...a: unknown[]) => unknown }\n if (isQueueableListener(listener, instance)) return this.queue(listener, instance, 'handle', callArgs)\n return instance.handle(...callArgs)\n }\n return (listener as (...a: unknown[]) => unknown)(...callArgs)\n }\n\n /**\n * Wraps the call as a CallQueuedListener job and dispatches it through BusDispatcher. Never runs inline; the\n * already-constructed `instance` is used only to read its ShouldQueue options (queueOptionsOf), never to run\n * handle()/method() — the worker builds its own instance from the registered class name.\n */\n private async queue(cls: Class<unknown>, instance: object, method: string, data: unknown[]): Promise<undefined> {\n const name = nameOf(cls)\n if (!this.container.bound(BusDispatcher)) throw new EventsNeedBusDispatcherError(name)\n if (!this.container.bound(ClassRegistry)) throw new EventsNeedClassRegistryError(name)\n const registry = this.container.make(ClassRegistry)\n const registeredName = registry.nameOf(cls) ?? registry.register(cls)\n const job = new CallQueuedListener(registeredName, method, data)\n Object.assign(job, queueOptionsOf(cls, instance))\n await this.container.make(BusDispatcher).dispatch(job)\n return undefined\n }\n}\n","import type { Class } from '@orieljs/contracts'\n\n/** A [ListenerClass, methodName] pair, e.g. [Subscriber, 'onUserRegistered']. */\n// eslint-disable-next-line @typescript-eslint/no-unused-vars -- E documents the event type the method handles\nexport type ListenerTuple<E> = [Class<object>, string]\n\nexport function isListenerTuple(value: unknown): value is ListenerTuple<unknown> {\n return Array.isArray(value) && value.length === 2 && typeof value[0] === 'function' && typeof value[1] === 'string'\n}\n\n/** A class with a handle() method on its prototype, as opposed to a plain closure listener. */\nexport function isListenerClass(value: unknown): value is Class<{ handle(...args: unknown[]): unknown }> {\n return typeof value === 'function' && typeof (value.prototype as { handle?: unknown } | undefined)?.handle === 'function'\n}\n","import type { Class } from '@orieljs/contracts'\n\n/** The same Symbol.for key Bus's real `Queueable` mixin sets on job prototypes (the Queue/Bus protocol). */\nconst SHOULD_QUEUE = Symbol.for('oriel:bus.shouldQueue')\n\nconst QUEUE_OPTION_KEYS = ['connection', 'queue', 'delay', 'tries', 'backoff', 'timeout'] as const\ntype QueueOptionKey = (typeof QUEUE_OPTION_KEYS)[number]\n\n/**\n * Whether a listener opts into queueing. `implements ShouldQueue` leaves no runtime trace, so this is structural,\n * like the Queue/Bus protocol's own `isQueueable(job)`: the marker, or an option, or a `uniqueId`/`retryUntil`\n * method. Unlike a job (already an instance by the time Bus sees it), a listener is a *class* registered with\n * `listen()`, so Events must build it first — `this.container.make(cls)` is cheap and side-effect-free for listener\n * classes, which have DI-only constructors — and then applies the protocol rule to that instance: the marker\n * (readable off the instance through the prototype chain), an **instance** option field with a defined value, or an\n * instance `uniqueId`/`retryUntil` method — the same fields Mail's and Notifications' `isQueueableMailable`/\n * equivalent read. A **static** field or method on the class counts too, as an extra on top of the protocol rule\n * (not instead of it), so an existing `static queue = '...'` listener still works.\n */\nexport function isQueueableListener(cls: Class<unknown>, instance: object): boolean {\n const members = instance as Record<PropertyKey, unknown>\n if (members[SHOULD_QUEUE] === true) return true\n const statics = cls as unknown as Record<string, unknown>\n if (QUEUE_OPTION_KEYS.some((key) => members[key] !== undefined || statics[key] !== undefined)) return true\n // Laravel doesn't support ShouldBeUnique on listeners: a `uniqueId`/`retryUntil` method only marks the listener as\n // queued here — it is never forwarded to the wrapper job (see queueOptionsOf and CallQueuedListener.retryUntil).\n return (\n typeof members.uniqueId === 'function' ||\n typeof members.retryUntil === 'function' ||\n typeof statics.uniqueId === 'function' ||\n typeof statics.retryUntil === 'function'\n )\n}\n\nconst isString = (value: unknown): value is string => typeof value === 'string'\nconst isNumber = (value: unknown): value is number => typeof value === 'number'\nconst isNumberOrNumberArray = (value: unknown): value is number | number[] =>\n isNumber(value) || (Array.isArray(value) && value.every(isNumber))\n\n/** Each option key's expected shape, so a method's return value (or a mistyped field) never reaches the job untyped. */\nconst VALIDATORS: Record<QueueOptionKey, (value: unknown) => boolean> = {\n connection: isString,\n queue: isString,\n delay: isNumber,\n tries: isNumber,\n timeout: isNumber,\n backoff: isNumberOrNumberArray,\n}\n\n/**\n * Copies the instance's (falling back to the class's static) ShouldQueue options onto the wrapper job. Laravel lets\n * these be methods (`backoff() { return [1, 5] }`) as well as plain fields — a method value is called (on the\n * instance, or on the class for a static) before use, never copied as-is, since Bus's serializer rejects functions.\n * Anything that isn't the expected type for its key (after resolving a method) is dropped rather than forwarded.\n */\nexport function queueOptionsOf(cls: Class<unknown>, instance: object): Partial<Record<QueueOptionKey, unknown>> {\n const statics = cls as unknown as Record<string, unknown>\n const members = instance as Record<string, unknown>\n const options: Partial<Record<QueueOptionKey, unknown>> = {}\n for (const key of QUEUE_OPTION_KEYS) {\n let value: unknown\n let onInstance = true\n if (members[key] !== undefined) value = members[key]\n else if (statics[key] !== undefined) {\n value = statics[key]\n onInstance = false\n } else continue\n if (typeof value === 'function') value = onInstance ? value.call(instance) : value.call(cls)\n if (VALIDATORS[key](value)) options[key] = value\n }\n return options\n}\n","import type { ErrorKind, OrielError } from '@orieljs/contracts'\n\n/**\n * A path escaped the disk root (e.g. `../../etc/passwd`, or an absolute path). Never served.\n *\n * `kind: 'Server'`, not `'Http'`: this isn't a condition Laravel maps to a specific HTTP status either — an\n * uncaught path escape is a security-relevant internal failure, reported and rendered as a generic 500 unless\n * `app.debug` is on, exactly like the other errors in this file.\n */\nexport class PathTraversalError extends Error implements OrielError {\n readonly kind: ErrorKind = 'Server'\n constructor(readonly path: string) {\n super(`Path traversal detected: \"${path}\" resolves outside the disk root.`)\n this.name = 'PathTraversalError'\n }\n}\n\n/** `kind: 'Server'`: an uncaught `Storage::get()` miss is a reported 500 in Laravel too, not a 404. */\nexport class FileNotFoundError extends Error implements OrielError {\n readonly kind: ErrorKind = 'Server'\n constructor(readonly path: string) {\n super(`File not found at path: ${path}`)\n this.name = 'FileNotFoundError'\n }\n}\n\nexport class UnknownDiskError extends Error implements OrielError {\n readonly kind: ErrorKind = 'Server'\n constructor(readonly disk: string) {\n super(`Disk [${disk}] is not defined in config('filesystems.disks').`)\n this.name = 'UnknownDiskError'\n }\n}\n\nexport class UnknownFilesystemDriverError extends Error implements OrielError {\n readonly kind: ErrorKind = 'Server'\n constructor(readonly driver: string) {\n super(`Filesystem driver [${driver}] is not registered. Use FilesystemManager.extend() to add it.`)\n this.name = 'UnknownFilesystemDriverError'\n }\n}\n\n/** An operation the driver genuinely can't do (local disks with no configured `url`, S3's `path()`, local `temporaryUrl()`). */\nexport class UnsupportedOperationError extends Error implements OrielError {\n readonly kind: ErrorKind = 'Server'\n constructor(operation: string, reason: string) {\n super(`${operation}() is not supported: ${reason}`)\n this.name = 'UnsupportedOperationError'\n }\n}\n","import type { FilesystemManager } from '@orieljs/contracts'\nimport { FilesystemManager as FilesystemManagerToken } from '@orieljs/contracts'\nimport { facade } from '@orieljs/support'\n\n/** The `Storage` facade (Laravel's `Illuminate\\Support\\Facades\\Storage`). `Storage.disk('public')...`. */\nexport const Storage = facade<FilesystemManager>(FilesystemManagerToken)\n","import { S3Client } from '@aws-sdk/client-s3'\nimport type { Container, Filesystem, PutOptions, UploadedFile } from '@orieljs/contracts'\nimport { FilesystemManager as FilesystemManagerToken, ConfigRepository } from '@orieljs/contracts'\nimport { UnknownDiskError, UnknownFilesystemDriverError } from './errors'\nimport { LocalFilesystem } from './LocalFilesystem'\nimport { S3Filesystem, type S3ClientLike } from './S3Filesystem'\n\ntype DiskConfig = Record<string, unknown>\ntype Driver = (config: DiskConfig) => Filesystem\n\ninterface FilesystemsConfig {\n default: string\n disks: Record<string, DiskConfig>\n}\n\n/** `Storage`'s backing manager: resolves disks by name from `config('filesystems')`, lazily and cached. */\nexport class FilesystemManager implements FilesystemManagerToken {\n private readonly disks = new Map<string, Filesystem>()\n private readonly drivers = new Map<string, Driver>()\n\n constructor(private readonly container: Container) {\n this.drivers.set(\n 'local',\n (config) =>\n new LocalFilesystem({\n root: String(config.root ?? ''),\n url: config.url as string | undefined,\n visibility: config.visibility as 'public' | 'private' | undefined,\n }),\n )\n this.drivers.set('s3', (config) => new S3Filesystem(this.buildS3Client(config), this.s3Config(config)))\n }\n\n private buildS3Client(config: DiskConfig): S3ClientLike {\n const key = config.key as string | undefined\n const secret = config.secret as string | undefined\n return new S3Client({\n region: (config.region as string | undefined) ?? 'us-east-1',\n endpoint: config.endpoint as string | undefined,\n forcePathStyle: config.usePathStyleEndpoint as boolean | undefined,\n credentials: key && secret ? { accessKeyId: key, secretAccessKey: secret } : undefined,\n })\n }\n\n private s3Config(config: DiskConfig) {\n return {\n bucket: String(config.bucket ?? ''),\n url: config.url as string | undefined,\n endpoint: config.endpoint as string | undefined,\n usePathStyleEndpoint: config.usePathStyleEndpoint as boolean | undefined,\n }\n }\n\n private filesystemsConfig(): FilesystemsConfig {\n return this.container.make(ConfigRepository).get<FilesystemsConfig>('filesystems', { default: 'local', disks: {} })\n }\n\n disk(name?: string): Filesystem {\n const filesystemsConfig = this.filesystemsConfig()\n const diskName = name ?? filesystemsConfig.default\n let disk = this.disks.get(diskName)\n if (!disk) {\n const diskConfig = filesystemsConfig.disks[diskName]\n if (!diskConfig) throw new UnknownDiskError(diskName)\n const driverName = diskConfig.driver as string | undefined\n const driver = driverName ? this.drivers.get(driverName) : undefined\n if (!driver) throw new UnknownFilesystemDriverError(String(driverName))\n disk = driver(diskConfig)\n this.disks.set(diskName, disk)\n }\n return disk\n }\n\n extend(driver: string, factory: Driver): void {\n this.drivers.set(driver, factory)\n }\n\n exists(path: string): Promise<boolean> {\n return this.disk().exists(path)\n }\n missing(path: string): Promise<boolean> {\n return this.disk().missing(path)\n }\n get(path: string): Promise<string> {\n return this.disk().get(path)\n }\n getBytes(path: string): Promise<Uint8Array> {\n return this.disk().getBytes(path)\n }\n readStream(path: string): Promise<ReadableStream<Uint8Array>> {\n return this.disk().readStream(path)\n }\n put(path: string, contents: string | Uint8Array | ReadableStream<Uint8Array>, options?: PutOptions): Promise<boolean> {\n return this.disk().put(path, contents, options)\n }\n putFile(directory: string, file: UploadedFile, options?: PutOptions): Promise<string> {\n return this.disk().putFile(directory, file, options)\n }\n putFileAs(directory: string, file: UploadedFile, name: string, options?: PutOptions): Promise<string> {\n return this.disk().putFileAs(directory, file, name, options)\n }\n delete(paths: string | string[]): Promise<boolean> {\n return this.disk().delete(paths)\n }\n copy(from: string, to: string): Promise<boolean> {\n return this.disk().copy(from, to)\n }\n move(from: string, to: string): Promise<boolean> {\n return this.disk().move(from, to)\n }\n size(path: string): Promise<number> {\n return this.disk().size(path)\n }\n lastModified(path: string): Promise<Date> {\n return this.disk().lastModified(path)\n }\n mimeType(path: string): Promise<string | undefined> {\n return this.disk().mimeType(path)\n }\n url(path: string): string {\n return this.disk().url(path)\n }\n temporaryUrl(path: string, expiresAt: Date): Promise<string> {\n return this.disk().temporaryUrl(path, expiresAt)\n }\n files(directory?: string, recursive?: boolean): Promise<string[]> {\n return this.disk().files(directory, recursive)\n }\n directories(directory?: string, recursive?: boolean): Promise<string[]> {\n return this.disk().directories(directory, recursive)\n }\n makeDirectory(path: string): Promise<boolean> {\n return this.disk().makeDirectory(path)\n }\n deleteDirectory(path: string): Promise<boolean> {\n return this.disk().deleteDirectory(path)\n }\n path(path: string): string {\n return this.disk().path(path)\n }\n}\n","import { createReadStream, createWriteStream, type Dirent } from 'node:fs'\nimport { chmod, copyFile, mkdir, readFile, readdir, rename, rm, stat, writeFile } from 'node:fs/promises'\nimport { dirname, extname, resolve } from 'node:path'\nimport { Readable } from 'node:stream'\nimport { pipeline } from 'node:stream/promises'\nimport type { Filesystem, PutOptions, UploadedFile } from '@orieljs/contracts'\nimport { FileNotFoundError, UnsupportedOperationError } from './errors'\nimport { mimeFromExtension } from './mime'\nimport { joinDiskPath, resolveDiskPath, uniqueFileName } from './paths'\n\nexport interface LocalDiskConfig {\n /** Absolute (or app-relative, already resolved by the caller) root directory for this disk. */\n root: string\n /** Public base URL for `url()`. Omit to make `url()` throw, like Laravel's private `local` disk. */\n url?: string\n /** Default visibility for files/directories written without an explicit `options.visibility`. */\n visibility?: 'public' | 'private'\n}\n\nconst FILE_MODE = { public: 0o644, private: 0o600 } as const\nconst DIR_MODE = { public: 0o755, private: 0o700 } as const\n\n/** A local disk (Laravel's `local` and `public` drivers are both this class, with different config). */\nexport class LocalFilesystem implements Filesystem {\n private readonly root: string\n\n constructor(private readonly config: LocalDiskConfig) {\n this.root = resolve(config.root)\n }\n\n private resolve(path: string): string {\n return resolveDiskPath(this.root, path)\n }\n\n private async statOrThrow(path: string, full: string) {\n try {\n return await stat(full)\n } catch {\n throw new FileNotFoundError(path)\n }\n }\n\n async exists(path: string): Promise<boolean> {\n const full = this.resolve(path)\n try {\n await stat(full)\n return true\n } catch {\n return false\n }\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 const full = this.resolve(path)\n await this.statOrThrow(path, full)\n return readFile(full, 'utf8')\n }\n\n async getBytes(path: string): Promise<Uint8Array> {\n const full = this.resolve(path)\n await this.statOrThrow(path, full)\n return new Uint8Array(await readFile(full))\n }\n\n async readStream(path: string): Promise<ReadableStream<Uint8Array>> {\n const full = this.resolve(path)\n await this.statOrThrow(path, full)\n return Readable.toWeb(createReadStream(full)) as ReadableStream<Uint8Array>\n }\n\n async put(path: string, contents: string | Uint8Array | ReadableStream<Uint8Array>, options?: PutOptions): Promise<boolean> {\n const full = this.resolve(path)\n await mkdir(dirname(full), { recursive: true })\n if (contents instanceof ReadableStream) {\n await pipeline(Readable.fromWeb(contents), createWriteStream(full))\n } else {\n await writeFile(full, contents)\n }\n await this.applyVisibility(full, options?.visibility, 'file')\n return true\n }\n\n async putFile(directory: string, file: UploadedFile, options?: PutOptions): Promise<string> {\n return this.putFileAs(directory, file, uniqueFileName(file.extension()), options)\n }\n\n async putFileAs(directory: string, file: UploadedFile, name: string, options?: PutOptions): Promise<string> {\n const path = joinDiskPath(directory, name)\n const bytes = new Uint8Array(await file.arrayBuffer())\n await this.put(path, bytes, { mimeType: file.mimeType, ...options })\n return path\n }\n\n async delete(paths: string | string[]): Promise<boolean> {\n for (const path of Array.isArray(paths) ? paths : [paths]) {\n await rm(this.resolve(path), { force: true })\n }\n return true\n }\n\n async copy(from: string, to: string): Promise<boolean> {\n const fromFull = this.resolve(from)\n const toFull = this.resolve(to)\n await this.statOrThrow(from, fromFull)\n await mkdir(dirname(toFull), { recursive: true })\n await copyFile(fromFull, toFull)\n return true\n }\n\n async move(from: string, to: string): Promise<boolean> {\n const fromFull = this.resolve(from)\n const toFull = this.resolve(to)\n await this.statOrThrow(from, fromFull)\n await mkdir(dirname(toFull), { recursive: true })\n try {\n await rename(fromFull, toFull)\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EXDEV') throw error\n await copyFile(fromFull, toFull)\n await rm(fromFull, { force: true })\n }\n return true\n }\n\n async size(path: string): Promise<number> {\n const full = this.resolve(path)\n return (await this.statOrThrow(path, full)).size\n }\n\n async lastModified(path: string): Promise<Date> {\n const full = this.resolve(path)\n return (await this.statOrThrow(path, full)).mtime\n }\n\n async mimeType(path: string): Promise<string | undefined> {\n const full = this.resolve(path)\n await this.statOrThrow(path, full)\n return mimeFromExtension(extname(full))\n }\n\n url(path: string): string {\n if (!this.config.url) throw new UnsupportedOperationError('url', 'this disk has no \"url\" configured')\n return `${this.config.url.replace(/\\/+$/, '')}/${path.replace(/^\\/+/, '')}`\n }\n\n async temporaryUrl(_path: string, _expiresAt: Date): Promise<string> {\n throw new UnsupportedOperationError('temporaryUrl', 'local disks cannot generate signed URLs; configure the s3 disk')\n }\n\n async files(directory = '', recursive = false): Promise<string[]> {\n return this.walk(directory, recursive, 'file')\n }\n\n async directories(directory = '', recursive = false): Promise<string[]> {\n return this.walk(directory, recursive, 'directory')\n }\n\n async makeDirectory(path: string): Promise<boolean> {\n const full = this.resolve(path)\n await mkdir(full, { recursive: true })\n await this.applyVisibility(full, this.config.visibility, 'directory')\n return true\n }\n\n async deleteDirectory(path: string): Promise<boolean> {\n await rm(this.resolve(path), { recursive: true, force: true })\n return true\n }\n\n path(path: string): string {\n return this.resolve(path)\n }\n\n private async walk(directory: string, recursive: boolean, want: 'file' | 'directory'): Promise<string[]> {\n const full = this.resolve(directory)\n let entries: Dirent[]\n try {\n entries = await readdir(full, { withFileTypes: true })\n } catch {\n return []\n }\n const results: string[] = []\n for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {\n const rel = joinDiskPath(directory, entry.name)\n if (entry.isDirectory()) {\n if (want === 'directory') results.push(rel)\n if (recursive) results.push(...(await this.walk(rel, recursive, want)))\n } else if (want === 'file') {\n results.push(rel)\n }\n }\n return results\n }\n\n private async applyVisibility(full: string, visibility: 'public' | 'private' | undefined, kind: 'file' | 'directory'): Promise<void> {\n const resolved = visibility ?? this.config.visibility\n if (!resolved) return\n const mode = (kind === 'file' ? FILE_MODE : DIR_MODE)[resolved]\n await chmod(full, mode)\n }\n}\n","/** A small extension -> MIME type table (not content-sniffed), enough for common uploads and assets. */\nconst MIME_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 png: 'image/png',\n jpg: 'image/jpeg',\n jpeg: 'image/jpeg',\n gif: 'image/gif',\n webp: 'image/webp',\n svg: 'image/svg+xml',\n ico: 'image/x-icon',\n bmp: 'image/bmp',\n mp3: 'audio/mpeg',\n wav: 'audio/wav',\n mp4: 'video/mp4',\n webm: 'video/webm',\n woff: 'font/woff',\n woff2: 'font/woff2',\n ttf: 'font/ttf',\n}\n\n/** Guesses a MIME type from a file extension (with or without a leading dot). Undefined if unrecognized. */\nexport function mimeFromExtension(extension: string): string | undefined {\n return MIME_TYPES[extension.replace(/^\\./, '').toLowerCase()]\n}\n","import { resolve, sep } from 'node:path'\nimport { Str } from '@orieljs/support'\nimport { PathTraversalError } from './errors'\n\n/**\n * Resolves `path` against `root`, throwing PathTraversalError if the result would escape the root\n * (a `../` climb, or an absolute path that replaces the root entirely). `root` itself is always allowed.\n */\nexport function resolveDiskPath(root: string, path: string): string {\n const resolvedRoot = resolve(root)\n const resolved = resolve(resolvedRoot, path)\n if (resolved !== resolvedRoot && !resolved.startsWith(resolvedRoot + sep)) {\n throw new PathTraversalError(path)\n }\n return resolved\n}\n\n/** Joins a directory and a name with a single `/`, tolerating an empty directory or trailing slash. */\nexport function joinDiskPath(directory: string, name: string): string {\n const trimmed = directory.replace(/\\/+$/, '')\n return trimmed === '' ? name : `${trimmed}/${name}`\n}\n\n/**\n * A random 40-character name for `putFile()`. The client-supplied `extension` (without a leading dot) is kept only\n * when it is purely alphanumeric; anything else (a `/`, `\\`, `..`, whitespace, ...) is dropped entirely so it can\n * never steer the file out of the target directory.\n */\nexport function uniqueFileName(extension: string): string {\n return /^[a-z0-9]+$/i.test(extension) ? `${Str.random(40)}.${extension}` : Str.random(40)\n}\n","import {\n CopyObjectCommand,\n DeleteObjectCommand,\n GetObjectCommand,\n HeadObjectCommand,\n ListObjectsV2Command,\n PutObjectCommand,\n type CommonPrefix,\n type ListObjectsV2CommandOutput,\n type S3ServiceException,\n type _Object as S3Object,\n} from '@aws-sdk/client-s3'\nimport { getSignedUrl } from '@aws-sdk/s3-request-presigner'\nimport type { Filesystem, PutOptions, UploadedFile } from '@orieljs/contracts'\nimport { FileNotFoundError, UnsupportedOperationError } from './errors'\nimport { joinDiskPath, uniqueFileName } from './paths'\n\n/** The subset of `S3Client` this driver needs. A test fake only has to implement `send()`. */\nexport interface S3ClientLike {\n send(command: unknown): Promise<unknown>\n}\n\nexport interface S3DiskConfig {\n bucket: string\n /** Public base URL for `url()`, e.g. a CloudFront domain. Falls back to the S3 virtual-hosted URL. */\n url?: string\n endpoint?: string\n usePathStyleEndpoint?: boolean\n}\n\nconst isNotFound = (error: unknown): boolean => {\n const name = (error as { name?: string }).name\n const status = (error as S3ServiceException).$metadata?.httpStatusCode\n return name === 'NotFound' || name === 'NoSuchKey' || status === 404\n}\n\nasync function readBody(body: unknown): Promise<Uint8Array> {\n return (await (body as { transformToByteArray(): Promise<Uint8Array> }).transformToByteArray()) ?? new Uint8Array()\n}\n\nasync function collectStream(stream: ReadableStream<Uint8Array>): Promise<Uint8Array> {\n const reader = stream.getReader()\n const chunks: Uint8Array[] = []\n let total = 0\n for (;;) {\n const { done, value } = await reader.read()\n if (done) break\n chunks.push(value)\n total += value.byteLength\n }\n const result = new Uint8Array(total)\n let offset = 0\n for (const chunk of chunks) {\n result.set(chunk, offset)\n offset += chunk.byteLength\n }\n return result\n}\n\n/** The `s3` disk driver. Every operation is a single S3 API call through the injected client. */\nexport class S3Filesystem implements Filesystem {\n constructor(\n private readonly client: S3ClientLike,\n private readonly config: S3DiskConfig,\n ) {}\n\n private async head(key: string) {\n return (await this.client.send(new HeadObjectCommand({ Bucket: this.config.bucket, Key: key }))) as {\n ContentLength?: number\n LastModified?: Date\n ContentType?: string\n }\n }\n\n async exists(path: string): Promise<boolean> {\n try {\n await this.head(path)\n return true\n } catch (error) {\n if (isNotFound(error)) return false\n throw error\n }\n }\n\n async missing(path: string): Promise<boolean> {\n return !(await this.exists(path))\n }\n\n private async getObject(path: string) {\n try {\n return (await this.client.send(new GetObjectCommand({ Bucket: this.config.bucket, Key: path }))) as { Body?: unknown }\n } catch (error) {\n if (isNotFound(error)) throw new FileNotFoundError(path)\n throw error\n }\n }\n\n async get(path: string): Promise<string> {\n const response = await this.getObject(path)\n return new TextDecoder().decode(await readBody(response.Body))\n }\n\n async getBytes(path: string): Promise<Uint8Array> {\n const response = await this.getObject(path)\n return readBody(response.Body)\n }\n\n async readStream(path: string): Promise<ReadableStream<Uint8Array>> {\n const response = await this.getObject(path)\n return (response.Body as { transformToWebStream(): ReadableStream<Uint8Array> }).transformToWebStream()\n }\n\n async put(path: string, contents: string | Uint8Array | ReadableStream<Uint8Array>, options?: PutOptions): Promise<boolean> {\n const body = contents instanceof ReadableStream ? await collectStream(contents) : contents\n await this.client.send(\n new PutObjectCommand({\n Bucket: this.config.bucket,\n Key: path,\n Body: body,\n ContentType: options?.mimeType,\n ACL: options?.visibility === 'public' ? 'public-read' : undefined,\n }),\n )\n return true\n }\n\n async putFile(directory: string, file: UploadedFile, options?: PutOptions): Promise<string> {\n return this.putFileAs(directory, file, uniqueFileName(file.extension()), options)\n }\n\n async putFileAs(directory: string, file: UploadedFile, name: string, options?: PutOptions): Promise<string> {\n const path = joinDiskPath(directory, name)\n await this.put(path, new Uint8Array(await file.arrayBuffer()), { mimeType: file.mimeType, ...options })\n return path\n }\n\n async delete(paths: string | string[]): Promise<boolean> {\n for (const path of Array.isArray(paths) ? paths : [paths]) {\n await this.client.send(new DeleteObjectCommand({ Bucket: this.config.bucket, Key: path }))\n }\n return true\n }\n\n async copy(from: string, to: string): Promise<boolean> {\n try {\n await this.client.send(\n new CopyObjectCommand({ Bucket: this.config.bucket, Key: to, CopySource: `${this.config.bucket}/${encodeURIComponent(from)}` }),\n )\n } catch (error) {\n if (isNotFound(error)) throw new FileNotFoundError(from)\n throw error\n }\n return true\n }\n\n async move(from: string, to: string): Promise<boolean> {\n await this.copy(from, to)\n await this.delete(from)\n return true\n }\n\n async size(path: string): Promise<number> {\n try {\n return (await this.head(path)).ContentLength ?? 0\n } catch (error) {\n if (isNotFound(error)) throw new FileNotFoundError(path)\n throw error\n }\n }\n\n async lastModified(path: string): Promise<Date> {\n try {\n const modified = (await this.head(path)).LastModified\n if (!modified) throw new FileNotFoundError(path)\n return modified\n } catch (error) {\n if (isNotFound(error)) throw new FileNotFoundError(path)\n throw error\n }\n }\n\n async mimeType(path: string): Promise<string | undefined> {\n try {\n return (await this.head(path)).ContentType\n } catch (error) {\n if (isNotFound(error)) throw new FileNotFoundError(path)\n throw error\n }\n }\n\n url(path: string): string {\n if (this.config.url) return `${this.config.url.replace(/\\/+$/, '')}/${path.replace(/^\\/+/, '')}`\n const endpoint = this.config.endpoint ?? 'https://s3.amazonaws.com'\n return this.config.usePathStyleEndpoint\n ? `${endpoint.replace(/\\/+$/, '')}/${this.config.bucket}/${path}`\n : `${endpoint.replace(/^https?:\\/\\//, (proto) => `${proto}${this.config.bucket}.`)}/${path}`\n }\n\n async temporaryUrl(path: string, expiresAt: Date): Promise<string> {\n const command = new GetObjectCommand({ Bucket: this.config.bucket, Key: path })\n const expiresIn = Math.max(1, Math.round((expiresAt.getTime() - Date.now()) / 1000))\n return getSignedUrl(this.client as never, command, { expiresIn })\n }\n\n async files(directory = '', recursive = false): Promise<string[]> {\n const { objects } = await this.list(directory, recursive)\n return objects.filter((key) => !key.endsWith('/')).sort()\n }\n\n async directories(directory = '', recursive = false): Promise<string[]> {\n const { prefixes } = await this.list(directory, recursive)\n return [...prefixes].sort()\n }\n\n async makeDirectory(path: string): Promise<boolean> {\n const key = path.endsWith('/') ? path : `${path}/`\n await this.client.send(new PutObjectCommand({ Bucket: this.config.bucket, Key: key, Body: new Uint8Array() }))\n return true\n }\n\n async deleteDirectory(path: string): Promise<boolean> {\n const prefix = path === '' ? '' : path.endsWith('/') ? path : `${path}/`\n const keys = await this.listAllKeys(prefix)\n for (const key of keys) await this.client.send(new DeleteObjectCommand({ Bucket: this.config.bucket, Key: key }))\n return true\n }\n\n path(_path: string): string {\n throw new UnsupportedOperationError('path', 's3 disks have no local filesystem path')\n }\n\n private async listAllKeys(prefix: string): Promise<string[]> {\n const keys: string[] = []\n let continuationToken: string | undefined\n do {\n const page = (await this.client.send(\n new ListObjectsV2Command({ Bucket: this.config.bucket, Prefix: prefix, ContinuationToken: continuationToken }),\n )) as ListObjectsV2CommandOutput\n for (const object of page.Contents ?? []) if (object.Key) keys.push(object.Key)\n continuationToken = page.IsTruncated ? page.NextContinuationToken : undefined\n } while (continuationToken)\n return keys\n }\n\n /**\n * Non-recursive: every ListObjectsV2 page with a `/` delimiter (Contents = files, CommonPrefixes =\n * subdirectories), following the continuation token until the listing is complete.\n */\n private async list(directory: string, recursive: boolean): Promise<{ objects: string[]; prefixes: string[] }> {\n const prefix = directory === '' ? '' : directory.endsWith('/') ? directory : `${directory}/`\n if (!recursive) {\n const objects: string[] = []\n const prefixes: string[] = []\n let continuationToken: string | undefined\n do {\n const page = (await this.client.send(\n new ListObjectsV2Command({ Bucket: this.config.bucket, Prefix: prefix, Delimiter: '/', ContinuationToken: continuationToken }),\n )) as ListObjectsV2CommandOutput\n for (const key of (page.Contents ?? []).map((o: S3Object) => o.Key)) if (key && key !== prefix) objects.push(key)\n for (const p of (page.CommonPrefixes ?? []).map((c: CommonPrefix) => c.Prefix)) if (p) prefixes.push(p.replace(/\\/$/, ''))\n continuationToken = page.IsTruncated ? page.NextContinuationToken : undefined\n } while (continuationToken)\n return { objects, prefixes }\n }\n const allKeys = await this.listAllKeys(prefix)\n const objects = allKeys.filter((key) => key !== prefix)\n const dirs = new Set<string>()\n for (const key of allKeys) {\n const rest = key.slice(prefix.length)\n const segments = rest.split('/').slice(0, -1)\n let built = prefix\n for (const segment of segments) {\n built += `${segment}/`\n dirs.add(built.replace(/\\/$/, ''))\n }\n }\n return { objects, prefixes: [...dirs] }\n }\n}\n","import { ConsoleKernel, FilesystemManager as FilesystemManagerToken } from '@orieljs/contracts'\nimport { ServiceProvider } from '@orieljs/support'\nimport { FilesystemManager } from './FilesystemManager'\nimport { registerStorageLinkCommand } from './StorageLinkCommand'\n\n/** Binds the FilesystemManager, merges Laravel 11's `filesystems` defaults, and registers `storage:link`. */\nexport class FilesystemServiceProvider extends ServiceProvider {\n override register(): void {\n this.mergeConfigFrom(\n {\n default: process.env.FILESYSTEM_DISK ?? 'local',\n disks: {\n local: {\n driver: 'local',\n root: this.app.storagePath('app/private'),\n },\n public: {\n driver: 'local',\n root: this.app.storagePath('app/public'),\n url: `${process.env.APP_URL ?? ''}/storage`,\n visibility: 'public',\n },\n s3: {\n driver: 's3',\n key: process.env.AWS_ACCESS_KEY_ID,\n secret: process.env.AWS_SECRET_ACCESS_KEY,\n region: process.env.AWS_DEFAULT_REGION,\n bucket: process.env.AWS_BUCKET,\n url: process.env.AWS_URL,\n endpoint: process.env.AWS_ENDPOINT,\n usePathStyleEndpoint: process.env.AWS_USE_PATH_STYLE_ENDPOINT === 'true',\n },\n },\n },\n 'filesystems',\n )\n this.app.singleton(FilesystemManagerToken, (container) => new FilesystemManager(container))\n }\n\n override boot(): void {\n if (this.app.bound(ConsoleKernel)) registerStorageLinkCommand(this.app.make(ConsoleKernel), this.app)\n }\n}\n","import { lstat, mkdir, symlink, unlink } from 'node:fs/promises'\nimport { dirname, relative } from 'node:path'\nimport type { Application, CommandContext, ConsoleKernel } from '@orieljs/contracts'\n\nexport const STORAGE_LINK_SIGNATURE =\n 'storage:link {--relative : Create the symbolic link using relative paths} {--force : Recreate an existing symbolic link}'\n\n/**\n * Laravel's `storage:link`, as a closure-command handler. `this` is Console's `CommandContext` —\n * the exact type `ConsoleKernel.command()`'s handler parameter expects, so no cast is needed to register it.\n */\nexport function storageLinkHandler(app: Application): (this: CommandContext) => Promise<number> {\n return async function (this: CommandContext): Promise<number> {\n const option = (name: string) => this.option(name) === true\n\n const link = app.publicPath('storage')\n const target = app.storagePath('app/public')\n\n try {\n const stats = await lstat(link)\n if (!option('force')) {\n this.info(`The [${link}] link already exists.`)\n return 0\n }\n if (!stats.isSymbolicLink()) {\n this.error(`The [${link}] link already exists and is not a symlink.`)\n return 1\n }\n await unlink(link)\n } catch {\n // No existing file at `link`: proceed to create it.\n }\n\n await mkdir(dirname(link), { recursive: true })\n const linkTarget = option('relative') ? relative(dirname(link), target) : target\n await symlink(linkTarget, link, 'dir')\n this.info(`The [${link}] link has been connected to [${target}].`)\n return 0\n }\n}\n\n/**\n * Registers `storage:link` on the console kernel as a closure command, with a real `oriel list` description.\n * `kernel.command()` returns `ClosureCommand`, so `.purpose()` is called directly, with no cast.\n */\nexport function registerStorageLinkCommand(kernel: ConsoleKernel, app: Application): void {\n kernel\n .command(STORAGE_LINK_SIGNATURE, storageLinkHandler(app))\n .purpose('Create the symbolic links configured for the application')\n}\n","import type { OrielError } from '@orieljs/contracts'\n\n/**\n * Thrown by check() when `verify` is on and the hash uses another algorithm (Laravel's RuntimeException).\n * A reported 500 ('Server' kind); the message is shown only with app.debug.\n */\nexport class HashAlgorithmError extends Error implements OrielError {\n override readonly name = 'HashAlgorithmError'\n readonly kind = 'Server' as const\n readonly status = 500\n}\n","import bcrypt from 'bcryptjs'\nimport { verify as argonVerify } from '@node-rs/argon2'\n\nexport interface HashInfo {\n algorithm: string\n options: Record<string, unknown>\n}\n\nconst BCRYPT = /^\\$2[abxy]\\$(\\d{2})\\$[./A-Za-z0-9]{53}$/\nconst ARGON = /^\\$(argon2id|argon2i)\\$v=\\d+\\$m=(\\d+),t=(\\d+),p=(\\d+)\\$/\n\n/** PHP's password_get_info(): the algorithm name ('bcrypt', 'argon2i', 'argon2id' or 'unknown') and its options. */\nexport function hashInfo(hashed: string): HashInfo {\n const bcryptMatch = BCRYPT.exec(hashed)\n if (bcryptMatch) return { algorithm: 'bcrypt', options: { cost: Number(bcryptMatch[1]) } }\n const argonMatch = ARGON.exec(hashed)\n if (argonMatch) {\n return {\n algorithm: argonMatch[1]!,\n options: { memory_cost: Number(argonMatch[2]), time_cost: Number(argonMatch[3]), threads: Number(argonMatch[4]) },\n }\n }\n return { algorithm: 'unknown', options: {} }\n}\n\n/** PHP's password_verify(): checks a value against a bcrypt or argon2 hash, whatever the configured driver. */\nexport async function passwordVerify(value: string, hashed: string): Promise<boolean> {\n const { algorithm } = hashInfo(hashed)\n try {\n if (algorithm === 'bcrypt') return await bcrypt.compare(value, hashed)\n if (algorithm === 'argon2i' || algorithm === 'argon2id') return await argonVerify(hashed, value)\n } catch {\n return false\n }\n return false\n}\n","import bcrypt from 'bcryptjs'\nimport type { Hasher } from '@orieljs/contracts'\nimport { coerceOption } from './coerce'\nimport { HashAlgorithmError } from './errors'\nimport { hashInfo, passwordVerify, type HashInfo } from './info'\n\nexport interface BcryptOptions {\n rounds?: number\n verify?: boolean\n}\n\n/** Laravel's BcryptHasher: `$2y$` hashes (what PHP's password_hash produces), cost `rounds` (default 12). */\nexport class BcryptHasher implements Hasher {\n readonly #rounds: number\n readonly #verify: boolean\n\n constructor(options: BcryptOptions = {}) {\n this.#rounds = coerceOption('hashing.bcrypt.rounds', options.rounds, 12)\n this.#verify = options.verify ?? true\n }\n\n async make(value: string, options: { rounds?: number } = {}): Promise<string> {\n const rounds = coerceOption('hashing.bcrypt.rounds', options.rounds, this.#rounds)\n const hashed = await bcrypt.hash(value, rounds)\n return hashed.replace(/^\\$2b\\$/, '$2y$')\n }\n\n async check(value: string, hashed: string): Promise<boolean> {\n if (typeof hashed !== 'string' || hashed === '') return false\n if (this.#verify && hashInfo(hashed).algorithm !== 'bcrypt') {\n throw new HashAlgorithmError('This password does not use the Bcrypt algorithm.')\n }\n return passwordVerify(value, hashed)\n }\n\n needsRehash(hashed: string, options: { rounds?: number } = {}): boolean {\n const info = hashInfo(hashed)\n const rounds = coerceOption('hashing.bcrypt.rounds', options.rounds, this.#rounds)\n return info.algorithm !== 'bcrypt' || info.options.cost !== rounds\n }\n\n info(hashed: string): HashInfo {\n return hashInfo(hashed)\n }\n}\n","/**\n * `env()` returns numeric values as strings, so a config file that writes `rounds: env('BCRYPT_ROUNDS', 12)` (or\n * the argon equivalents) hands the hasher a string. bcryptjs and @node-rs/argon2 both misbehave on a string cost\n * (bcryptjs throws \"Invalid salt version\"), so every numeric hashing option is coerced with Number() here, with a\n * clear configuration error for anything that doesn't come out finite.\n */\nexport function coerceOption(name: string, value: unknown, fallback: number): number {\n if (value === undefined || value === null) return fallback\n const coerced = Number(value)\n if (!Number.isFinite(coerced)) {\n throw new Error(`Invalid hashing configuration: [${name}] must be a number, got ${JSON.stringify(value)}.`)\n }\n return coerced\n}\n","import { hash, type Algorithm } from '@node-rs/argon2'\nimport type { Hasher } from '@orieljs/contracts'\nimport { coerceOption } from './coerce'\nimport { HashAlgorithmError } from './errors'\nimport { hashInfo, passwordVerify, type HashInfo } from './info'\n\nexport interface ArgonOptions {\n /** Memory cost in KiB (default 65536). */\n memory?: number\n /** Time cost / passes (default 4). */\n time?: number\n /** Parallelism (default 1). */\n threads?: number\n verify?: boolean\n}\n\n/** Laravel's ArgonHasher (`argon`, argon2i) and Argon2IdHasher (`argon2id`). */\nexport class ArgonHasher implements Hasher {\n readonly #memory: number\n readonly #time: number\n readonly #threads: number\n readonly #verify: boolean\n\n constructor(\n options: ArgonOptions = {},\n readonly algorithm: 'argon2i' | 'argon2id' = 'argon2i',\n ) {\n this.#memory = coerceOption('hashing.argon.memory', options.memory, 65536)\n this.#time = coerceOption('hashing.argon.time', options.time, 4)\n this.#threads = coerceOption('hashing.argon.threads', options.threads, 1)\n this.#verify = options.verify ?? true\n }\n\n make(value: string, options: Omit<ArgonOptions, 'verify'> = {}): Promise<string> {\n return hash(value, {\n // Algorithm is a const enum in @node-rs/argon2 (Argon2i = 1, Argon2id = 2); isolatedModules forbids reading it.\n algorithm: (this.algorithm === 'argon2id' ? 2 : 1) as Algorithm,\n memoryCost: coerceOption('hashing.argon.memory', options.memory, this.#memory),\n timeCost: coerceOption('hashing.argon.time', options.time, this.#time),\n parallelism: coerceOption('hashing.argon.threads', options.threads, this.#threads),\n })\n }\n\n async check(value: string, hashed: string): Promise<boolean> {\n if (typeof hashed !== 'string' || hashed === '') return false\n if (this.#verify && hashInfo(hashed).algorithm !== this.algorithm) {\n throw new HashAlgorithmError(`This password does not use the ${this.algorithm === 'argon2id' ? 'Argon2id' : 'Argon2i'} algorithm.`)\n }\n return passwordVerify(value, hashed)\n }\n\n needsRehash(hashed: string, options: Omit<ArgonOptions, 'verify'> = {}): boolean {\n const info = hashInfo(hashed)\n const memory = coerceOption('hashing.argon.memory', options.memory, this.#memory)\n const time = coerceOption('hashing.argon.time', options.time, this.#time)\n const threads = coerceOption('hashing.argon.threads', options.threads, this.#threads)\n return (\n info.algorithm !== this.algorithm ||\n info.options.memory_cost !== memory ||\n info.options.time_cost !== time ||\n info.options.threads !== threads\n )\n }\n\n info(hashed: string): HashInfo {\n return hashInfo(hashed)\n }\n}\n","import type { Hasher } from '@orieljs/contracts'\nimport { ArgonHasher, type ArgonOptions } from './ArgonHasher'\nimport { BcryptHasher, type BcryptOptions } from './BcryptHasher'\nimport { hashInfo, type HashInfo } from './info'\n\nexport interface HashingConfig {\n driver?: string\n bcrypt?: BcryptOptions\n argon?: ArgonOptions\n rehash_on_login?: boolean\n}\n\nexport type HasherFactory = (config: HashingConfig) => Hasher\n\n/** Laravel's HashManager: the `Hasher` binding. Delegates to the default driver (config('hashing.driver')). */\nexport class HashManager implements Hasher {\n readonly #drivers = new Map<string, Hasher>()\n readonly #custom = new Map<string, HasherFactory>()\n\n /** `config` is read lazily, each time a driver is first created. */\n constructor(private readonly config: () => HashingConfig) {}\n\n driver(name?: string): Hasher {\n const driver = name ?? this.getDefaultDriver()\n let hasher = this.#drivers.get(driver)\n if (hasher === undefined) {\n hasher = this.#create(driver)\n this.#drivers.set(driver, hasher)\n }\n return hasher\n }\n\n /** Register a custom driver: Hash.extend('sha', (config) => new ShaHasher()). */\n extend(driver: string, factory: HasherFactory): this {\n this.#custom.set(driver, factory)\n this.#drivers.delete(driver)\n return this\n }\n\n getDefaultDriver(): string {\n return this.config().driver ?? 'bcrypt'\n }\n\n make(value: string): Promise<string> {\n return this.driver().make(value)\n }\n\n check(value: string, hashed: string): Promise<boolean> {\n return this.driver().check(value, hashed)\n }\n\n needsRehash(hashed: string): boolean {\n return this.driver().needsRehash(hashed)\n }\n\n info(hashed: string): HashInfo {\n return this.driver().info(hashed)\n }\n\n /** Whether the value is already a bcrypt or argon2 hash (Laravel's Hash::isHashed). */\n isHashed(value: string): boolean {\n return hashInfo(value).algorithm !== 'unknown'\n }\n\n #create(driver: string): Hasher {\n const config = this.config()\n const custom = this.#custom.get(driver)\n if (custom !== undefined) return custom(config)\n if (driver === 'bcrypt') return new BcryptHasher(config.bcrypt)\n if (driver === 'argon') return new ArgonHasher(config.argon, 'argon2i')\n if (driver === 'argon2id') return new ArgonHasher(config.argon, 'argon2id')\n throw new Error(`Driver [${driver}] not supported.`)\n }\n}\n","import { Hasher } from '@orieljs/contracts'\nimport { inject } from '@orieljs/container'\nimport { facade } from '@orieljs/support'\nimport type { BcryptHasher } from './BcryptHasher'\nimport type { HashManager } from './HashManager'\n\nconst manager = (): HashManager => inject(Hasher) as HashManager\n\n/** The Hash facade. `Hash.driver('argon2id')` and `Hash.isHashed()` need the HashManager binding. */\nexport const Hash = facade(Hasher, {\n driver: (name?: string): Hasher => manager().driver(name),\n isHashed: (value: string): boolean => manager().isHashed(value),\n})\n\n/** bcrypt() helper: hashes with the bcrypt driver whatever the default driver is (Laravel's bcrypt()). */\nexport function bcrypt(value: string, options: { rounds?: number } = {}): Promise<string> {\n return (manager().driver('bcrypt') as BcryptHasher).make(value, options)\n}\n","import { ConfigRepository, Hasher } from '@orieljs/contracts'\nimport { ServiceProvider } from '@orieljs/support'\nimport { HashManager, type HashingConfig } from './HashManager'\n\nexport class HashingServiceProvider extends ServiceProvider {\n override register(): void {\n this.mergeConfigFrom(\n {\n driver: 'bcrypt',\n bcrypt: { rounds: 12, verify: true },\n argon: { memory: 65536, threads: 1, time: 4, verify: true },\n rehash_on_login: true,\n },\n 'hashing',\n )\n this.app.singleton(Hasher, (container) => new HashManager(() => container.make(ConfigRepository).get<HashingConfig>('hashing', {})))\n }\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/** 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, RedirectResponse } from '@orieljs/contracts'\nimport { currentRequest, optionalCookieJar, optionalSession } from './context'\n\ntype ErrorsInput = Record<string, string | string[]> | { toObject(): Record<string, string[]> }\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 { toObject(): Record<string, string[]> }).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/** 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 /** Remembers where a guest was going (a GET page, else the previous URL), then redirects to `path`. */\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', 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 { Str } from '@orieljs/support'\nimport { extensionFromMime } from './mime'\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 constructor(private readonly file: Blob & { readonly name?: string }) {\n this.clientName = file.name ?? ''\n this.mimeType = file.type === '' ? 'application/octet-stream' : file.type\n this.size = file.size\n }\n\n /** Guessed from the MIME type, falling back to the client's extension (Laravel's extension()). */\n extension(): string {\n return extensionFromMime(this.mimeType) ?? this.clientExtension()\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 json: 'application/json',\n md: 'text/markdown',\n mp3: 'audio/mpeg',\n mp4: 'video/mp4',\n pdf: 'application/pdf',\n png: 'image/png',\n svg: 'image/svg+xml',\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 CurrentRoute,\n Session,\n ValidationFactory,\n type HttpRequest,\n type Rules,\n type UploadedFile,\n} from '@orieljs/contracts'\nimport { currentContainer, inject } from '@orieljs/container'\nimport { Arr, Str } from '@orieljs/support'\nimport { readBody } from './body'\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}\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 #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.#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 errors (413) 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 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 this.#parseForm(await new Response(bytes, { 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 #parseForm(form: FormData): 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, new FormUploadedFile(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 string(key: string, defaultValue = ''): string {\n const value = this.input<unknown>(key)\n return value === undefined || value === null ? defaultValue : String(value)\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 user<T = unknown>(guard?: string): T | undefined {\n return this.#userResolver?.(guard) as T | undefined\n }\n\n setUserResolver(resolver: (guard?: string) => unknown): void {\n this.#userResolver = resolver\n }\n\n /** Validates all() through the ValidationFactory; throws its Validation error on failure. */\n validate<T = Record<string, unknown>>(\n rules: Rules,\n messages?: Record<string, string>,\n attributes?: Record<string, string>,\n ): Promise<T> {\n return inject(ValidationFactory).make(this.all(), rules, messages, attributes).validated<T>()\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} from '@orieljs/contracts'\nimport { inject } from '@orieljs/container'\nimport { HttpException, HttpResponseException } from './errors'\n\n/** request() → the current HttpRequest; request('key', default) → its input. */\nexport function request(): HttpRequest\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/** redirect() → the Redirector; redirect('/path', status) → a RedirectResponse. */\nexport function redirect(): Redirector\nexport function redirect(to: string, status?: number): RedirectResponse\nexport function redirect(to?: string, status?: number): Redirector | 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/** The URL of a named route. */\nexport function route(name: string, parameters?: unknown, absolute?: boolean): string {\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, { trustedProxies: this.#trustedProxies(), maxBodySize: this.#maxBodySize() })\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.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\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\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 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 (http.expectsJson()) response = this.#renderJson(error)\n else response = await this.#renderHtml(http, error)\n\n const headers = (error as Partial<OrielError> | null)?.headers\n if (headers !== undefined) for (const [name, value] of Object.entries(headers)) response.headers.set(name, value)\n return response\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 (request.expectsJson()) {\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 (request.expectsJson()) 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","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 408: 'Request Timeout',\n 409: 'Conflict',\n 410: 'Gone',\n 413: 'Content Too Large',\n 415: 'Unsupported Media Type',\n 419: 'Page Expired',\n 422: 'Unprocessable Content',\n 429: 'Too Many Requests',\n 500: 'Server Error',\n 502: 'Bad Gateway',\n 503: 'Service Unavailable',\n 504: 'Gateway Timeout',\n}\n\n/** Laravel's wording for the status (its error pages say \"Server Error\" and \"Page Expired\"). */\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 } 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\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'\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}\n\nexport interface ResolvedServeOptions {\n readonly port: number\n readonly hostname: string\n readonly signals: boolean\n readonly shutdownTimeout: number\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/** app.handle(), turning a crash outside the kernel into a plain 500. */\nexport async function handleSafely(app: Application, request: Request): Promise<Response> {\n try {\n return await app.handle(request)\n } catch (error) {\n console.error(error)\n return plainServerError()\n }\n}\n\n/** SIGINT/SIGTERM → close() → process.exit(0). The listeners go away when the server closes. */\nexport function exitOnSignals(close: () => Promise<void>, closed: Promise<void>): void {\n const onSignal = () => {\n void close().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 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)\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)\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)\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)\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 }\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'\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}\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\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 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 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. Run [oriel migrate] to create the personal access tokens table.')\n return 0\n })\n .purpose('Create an API routes file and prepare the application for API authentication')\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 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 { currentContainer } from '@orieljs/container'\n\n/** Used as the WeakMap key when there is no current container at all (context added outside any scope). */\nconst rootKey: object = {}\n\n/**\n * Log context, keyed by the current scope. `Application.handle()` creates a fresh child container per request\n * (`this.createScope()`) and runs the kernel inside `scope.run(...)`, so `currentContainer()` returns a distinct\n * object per in-flight request; two concurrent requests never share a key here, so context added during one never\n * leaks into the other. Outside of any scope (CLI, boot), everything shares `rootKey`.\n */\nconst contexts = new WeakMap<object, Record<string, unknown>>()\n\n/** Merges `context` into the log context for the current scope (Laravel's `Log::withContext()`). */\nexport function mergeLogContext(context: Record<string, unknown>): void {\n const key = currentContainer() ?? rootKey\n contexts.set(key, { ...contexts.get(key), ...context })\n}\n\n/** The merged log context for the current scope, or `{}` if none has been added. */\nexport function currentLogContext(): Record<string, unknown> {\n return contexts.get(currentContainer() ?? rootKey) ?? {}\n}\n","import type { ErrorKind, OrielError } from '@orieljs/contracts'\n\nexport class UnknownLogChannelError extends Error implements OrielError {\n readonly kind: ErrorKind = 'Server'\n constructor(readonly channel: string) {\n super(`Log channel [${channel}] is not defined in config('logging.channels').`)\n this.name = 'UnknownLogChannelError'\n }\n}\n\nexport class UnknownLogDriverError extends Error implements OrielError {\n readonly kind: ErrorKind = 'Server'\n constructor(readonly driver: string) {\n super(`Log driver [${driver}] is not registered.`)\n this.name = 'UnknownLogDriverError'\n }\n}\n\nexport class LogChannelCycleError extends Error implements OrielError {\n readonly kind: ErrorKind = 'Server'\n constructor(readonly channel: string) {\n super(`Log channel [${channel}] includes itself.`)\n this.name = 'LogChannelCycleError'\n }\n}\n\nexport class InvalidLogLevelError extends Error implements OrielError {\n readonly kind: ErrorKind = 'Server'\n constructor(readonly level: string) {\n super(`Invalid log level [${level}].`)\n this.name = 'InvalidLogLevelError'\n }\n}\n","import type { LogLevel } from '@orieljs/contracts'\nimport { InvalidLogLevelError } from './errors'\n\n/** RFC 5424 severities, most severe first. Higher numbers are more severe. */\nexport const LEVEL_SEVERITY: Record<LogLevel, number> = {\n debug: 10,\n info: 20,\n notice: 30,\n warning: 40,\n error: 50,\n critical: 60,\n alert: 70,\n emergency: 80,\n}\n\n/** Throws `InvalidLogLevelError` unless `level` is one of the eight RFC 5424 names (no aliases like `warn`). */\nexport function assertLogLevel(level: unknown): asserts level is LogLevel {\n if (typeof level !== 'string' || !Object.hasOwn(LEVEL_SEVERITY, level)) throw new InvalidLogLevelError(String(level))\n}\n\n/** True when `level` is at least as severe as `minimum` (e.g. `error` meets a `warning` threshold). */\nexport function meetsLevel(level: LogLevel, minimum: LogLevel): boolean {\n return LEVEL_SEVERITY[level] >= LEVEL_SEVERITY[minimum]\n}\n\n/**\n * `Error` objects don't survive `JSON.stringify` (message/stack/name aren't own enumerable properties), so any\n * `Error` values directly on the context object are expanded one level deep into a plain `{ name, message, stack }`.\n * This is how `LogManager.error(message, { exception })` (Http's exception handler) ends up readable in log output.\n */\nexport function serializeContext(context: Record<string, unknown> | undefined): Record<string, unknown> {\n if (!context) return {}\n const result: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(context)) {\n result[key] = value instanceof Error ? { name: value.name, message: value.message, stack: value.stack } : value\n }\n return result\n}\n","import type { Logger, LogLevel } from '@orieljs/contracts'\nimport { currentLogContext, mergeLogContext } from './context'\nimport { assertLogLevel, meetsLevel, serializeContext } from './levels'\n\n/**\n * Implements the full `Logger` contract on top of one `write()` method: level filtering, merging in the current\n * scope's context (`context.ts`) and serializing `Error` values (`levels.ts`) all happen here, once.\n */\nexport abstract class BaseLogger implements Logger {\n constructor(protected readonly minimumLevel: LogLevel = 'debug') {\n assertLogLevel(minimumLevel)\n }\n\n log(level: LogLevel, message: string, context?: Record<string, unknown>): void {\n if (!meetsLevel(level, this.minimumLevel)) return\n this.write(level, message, serializeContext({ ...currentLogContext(), ...context }))\n }\n\n emergency(message: string, context?: Record<string, unknown>): void {\n this.log('emergency', message, context)\n }\n alert(message: string, context?: Record<string, unknown>): void {\n this.log('alert', message, context)\n }\n critical(message: string, context?: Record<string, unknown>): void {\n this.log('critical', message, context)\n }\n error(message: string, context?: Record<string, unknown>): void {\n this.log('error', message, context)\n }\n warning(message: string, context?: Record<string, unknown>): void {\n this.log('warning', message, context)\n }\n notice(message: string, context?: Record<string, unknown>): void {\n this.log('notice', message, context)\n }\n info(message: string, context?: Record<string, unknown>): void {\n this.log('info', message, context)\n }\n debug(message: string, context?: Record<string, unknown>): void {\n this.log('debug', message, context)\n }\n\n withContext(context: Record<string, unknown>): this {\n mergeLogContext(context)\n return this\n }\n\n /** Called only when `level` already meets this logger's configured minimum, with context fully resolved. */\n protected abstract write(level: LogLevel, message: string, context: Record<string, unknown>): void\n}\n","import pino from 'pino'\nimport type { LogLevel } from '@orieljs/contracts'\nimport { DailyRotatingStream } from './DailyRotatingStream'\nimport { assertLogLevel } from './levels'\nimport { PinoLogger } from './PinoLogger'\nimport { reportLogWriteFailure } from './writeFailure'\n\n/** Pino passes everything through; `BaseLogger` already filtered by the channel's own minimum level. */\nconst PINO_OPTIONS = { level: 'debug' } as const\n\n/** The `single` channel: everything appended to one file, e.g. `storage/logs/oriel.log`. */\nexport function createSingleChannel(path: string, minimumLevel: LogLevel = 'debug'): PinoLogger {\n assertLogLevel(minimumLevel) // before opening the file, so a rejected channel leaves nothing open\n const destination = pino.destination({ dest: path, mkdir: true, sync: false })\n // Without a listener, an I/O error on the destination (EACCES, ENOTDIR, disk full, ...) is re-emitted as an\n // unhandled 'error' event and takes the process down.\n destination.on('error', (error: Error) => reportLogWriteFailure(path, error))\n return new PinoLogger(pino(PINO_OPTIONS, destination), minimumLevel)\n}\n\n/** The `daily` channel: one file per day under the same directory, pruned after `days`. */\nexport function createDailyChannel(path: string, days = 14, minimumLevel: LogLevel = 'debug', now?: () => Date): PinoLogger {\n assertLogLevel(minimumLevel)\n const stream = new DailyRotatingStream(path, days, now)\n return new PinoLogger(pino(PINO_OPTIONS, stream), minimumLevel)\n}\n\n/** The `stderr` channel. */\nexport function createStderrChannel(minimumLevel: LogLevel = 'debug'): PinoLogger {\n assertLogLevel(minimumLevel)\n const destination = pino.destination({ dest: 2, sync: false })\n // Nowhere left to report a failure writing to stderr itself, so it's swallowed rather than crashing the process.\n destination.on('error', () => {})\n return new PinoLogger(pino(PINO_OPTIONS, destination), minimumLevel)\n}\n","import { createWriteStream, mkdirSync, readdirSync, rmSync, type WriteStream } from 'node:fs'\nimport { basename, dirname, extname, join } from 'node:path'\nimport { Writable } from 'node:stream'\nimport { reportLogWriteFailure } from './writeFailure'\n\n/** `YYYY-MM-DD` for the local calendar day of `date`. */\nfunction localDay(date: Date): string {\n const month = String(date.getMonth() + 1).padStart(2, '0')\n const day = String(date.getDate()).padStart(2, '0')\n return `${date.getFullYear()}-${month}-${day}`\n}\n\nconst DATE_PATTERN = /^(\\d{4})-(\\d{2})-(\\d{2})$/\n\n/**\n * Writes to `<dir>/<stem>-<YYYY-MM-DD>.log`, switching files when the local calendar day changes and deleting files\n * older than `days` each time it rolls over. `now` is injectable so tests can simulate day boundaries without a\n * fake timer.\n */\nexport class DailyRotatingStream extends Writable {\n private readonly dir: string\n private readonly stem: string\n private currentDate = ''\n private stream: WriteStream | undefined\n /**\n * The in-flight `_write()`'s callback, if any, tagged with the exact child stream it was issued for. Resolved\n * either by that stream's own write completing or by that same stream's `'error'` listener, whichever comes\n * first, so a write can never hang on a broken destination. Scoping it to `stream` (rather than just tracking\n * \"the current callback\") matters across a rollover: a superseded stream can still emit a late `'error'` (e.g.\n * a failed flush during its fire-and-forget `end()`) after a write is already pending on the *new* stream, and\n * that stale error must only produce its own stderr notice, never resolve someone else's pending write.\n */\n private pending: { readonly stream: WriteStream; readonly callback: () => void } | undefined\n\n constructor(\n basePath: string,\n private readonly days: number,\n private readonly now: () => Date = () => new Date(),\n ) {\n super()\n this.dir = dirname(basePath)\n this.stem = basename(basePath, extname(basePath) || undefined)\n mkdirSync(this.dir, { recursive: true })\n }\n\n private pathFor(date: string): string {\n return join(this.dir, `${this.stem}-${date}.log`)\n }\n\n private today(): string {\n return localDay(this.now())\n }\n\n /**\n * Opens the file at `path` and attaches an `'error'` listener so an I/O failure (disk full, EACCES, EISDIR, ...)\n * on this one child stream can never crash the process: it's reported as a one-line notice on `process.stderr`,\n * the stream is dropped (the next write reopens it), and it is never re-emitted on `this`.\n *\n * `protected` rather than `private` only so a test can subclass and capture the real child streams this opens\n * (node:fs's ESM module namespace can't be `vi.spyOn()`'d), to simulate a stream retired by rollover emitting a\n * late error while a write is already pending on its replacement.\n */\n protected openStream(path: string): WriteStream {\n const stream = createWriteStream(path, { flags: 'a' })\n stream.on('error', (error: Error) => {\n reportLogWriteFailure(path, error)\n if (this.stream === stream) this.stream = undefined\n if (this.pending?.stream === stream) {\n const { callback } = this.pending\n this.pending = undefined\n callback()\n }\n })\n return stream\n }\n\n private ensureStream(): WriteStream {\n const date = this.today()\n const dateChanged = date !== this.currentDate\n if (dateChanged || !this.stream) {\n this.stream?.end()\n this.currentDate = date\n this.stream = this.openStream(this.pathFor(date))\n if (dateChanged) this.prune()\n }\n return this.stream\n }\n\n /**\n * Deletes this channel's files dated before the oldest of the `days` most recent local days (today included).\n * Only names that are exactly `<stem>-<YYYY-MM-DD>.log` count, so a sibling channel sharing the prefix\n * (e.g. `oriel-worker-<date>.log` next to `oriel-<date>.log`) is never touched.\n */\n private prune(): void {\n if (this.days <= 0) return\n const prefix = `${this.stem}-`\n const now = this.now()\n const cutoff = new Date(now.getFullYear(), now.getMonth(), now.getDate() - (this.days - 1)).getTime()\n for (const file of readdirSync(this.dir)) {\n if (!file.startsWith(prefix) || !file.endsWith('.log')) continue\n const match = DATE_PATTERN.exec(file.slice(prefix.length, -'.log'.length))\n if (!match) continue\n const time = new Date(Number(match[1]), Number(match[2]) - 1, Number(match[3])).getTime()\n if (time < cutoff) rmSync(join(this.dir, file), { force: true })\n }\n }\n\n override _write(chunk: unknown, encoding: BufferEncoding, callback: (error?: Error | null) => void): void {\n const stream = this.ensureStream()\n this.pending = { stream, callback: () => callback() }\n stream.write(chunk as Uint8Array, encoding, () => {\n if (this.pending?.stream === stream) {\n this.pending = undefined\n callback()\n }\n })\n }\n\n override _final(callback: (error?: Error | null) => void): void {\n const stream = this.stream\n if (!stream) {\n callback()\n return\n }\n let done = false\n const finish = () => {\n if (done) return\n done = true\n callback()\n }\n stream.once('finish', finish)\n stream.once('error', finish)\n stream.end()\n }\n}\n","/** Reports a log destination I/O failure as one line on `process.stderr`, so it never crashes the process. */\nexport function reportLogWriteFailure(path: string, error: Error): void {\n process.stderr.write(`Unable to write log file ${path}: ${error.message}\\n`)\n}\n","import pino from 'pino'\nimport type { LogLevel } from '@orieljs/contracts'\nimport { BaseLogger } from './BaseLogger'\n\n/** Maps an RFC 5424 level onto pino's own (narrower) level methods. The real level is kept in the payload. */\nconst PINO_METHOD: Record<LogLevel, 'fatal' | 'error' | 'warn' | 'info' | 'debug'> = {\n emergency: 'fatal',\n alert: 'fatal',\n critical: 'fatal',\n error: 'error',\n warning: 'warn',\n notice: 'info',\n info: 'info',\n debug: 'debug',\n}\n\n/** A channel backed by a pino logger writing to an arbitrary destination stream (file, stderr, ...). */\nexport class PinoLogger extends BaseLogger {\n constructor(\n private readonly pinoInstance: pino.Logger,\n minimumLevel: LogLevel = 'debug',\n ) {\n super(minimumLevel)\n }\n\n protected write(level: LogLevel, message: string, context: Record<string, unknown>): void {\n this.pinoInstance[PINO_METHOD[level]]({ ...context, rfc5424Level: level }, message)\n }\n}\n","import type { LogManager } from '@orieljs/contracts'\nimport { LogManager as LogManagerToken } from '@orieljs/contracts'\nimport { inject } from '@orieljs/container'\nimport { facade } from '@orieljs/support'\n\n/** The `Log` facade (Laravel's `Illuminate\\Support\\Facades\\Log`). `Log.channel('single').info(...)`. */\nexport const Log = facade<LogManager>(LogManagerToken)\n\n/** With no args, the LogManager itself. With a message, logs it at `debug` (Laravel's `logger()` helper). */\nexport function logger(): LogManager\nexport function logger(message: string, context?: Record<string, unknown>): void\nexport function logger(message?: string, context?: Record<string, unknown>): LogManager | void {\n const manager = inject(LogManagerToken)\n if (message === undefined) return manager\n manager.debug(message, context)\n}\n","import type { Container, Logger, LogLevel } from '@orieljs/contracts'\nimport { ConfigRepository, LogManager as LogManagerToken } from '@orieljs/contracts'\nimport { createDailyChannel, createSingleChannel, createStderrChannel } from './channels'\nimport { mergeLogContext } from './context'\nimport { LogChannelCycleError, UnknownLogChannelError, UnknownLogDriverError } from './errors'\nimport { NullLogger } from './NullLogger'\nimport { StackLogger } from './StackLogger'\n\ntype ChannelConfig = Record<string, unknown>\ntype Driver = (config: ChannelConfig) => Logger\n\ninterface LoggingConfig {\n default: string\n channels: Record<string, ChannelConfig>\n}\n\nconst level = (config: ChannelConfig): LogLevel => (config.level as LogLevel | undefined) ?? 'debug'\n\n/** `LogManager`: resolves channels by name from `config('logging')`, lazily and cached. */\nexport class LogManager implements LogManagerToken {\n private readonly channels = new Map<string, Logger>()\n private readonly drivers = new Map<string, Driver>()\n private readonly resolving = new Set<string>()\n\n constructor(private readonly container: Container) {\n this.drivers.set('single', (config) => createSingleChannel(String(config.path ?? ''), level(config)))\n this.drivers.set('daily', (config) => createDailyChannel(String(config.path ?? ''), Number(config.days ?? 14), level(config)))\n this.drivers.set('stderr', (config) => createStderrChannel(level(config)))\n this.drivers.set('null', () => new NullLogger())\n this.drivers.set('stack', (config) => this.stack((config.channels as string[] | undefined) ?? []))\n }\n\n private loggingConfig(): LoggingConfig {\n return this.container.make(ConfigRepository).get<LoggingConfig>('logging', { default: 'stack', channels: {} })\n }\n\n channel(name?: string): Logger {\n const loggingConfig = this.loggingConfig()\n const channelName = name ?? loggingConfig.default\n let channel = this.channels.get(channelName)\n if (!channel) {\n if (this.resolving.has(channelName)) throw new LogChannelCycleError(channelName)\n const channelConfig = loggingConfig.channels[channelName]\n if (!channelConfig) throw new UnknownLogChannelError(channelName)\n const driverName = channelConfig.driver as string | undefined\n const driver = driverName ? this.drivers.get(driverName) : undefined\n if (!driver) throw new UnknownLogDriverError(String(driverName))\n this.resolving.add(channelName)\n try {\n channel = driver(channelConfig)\n } finally {\n this.resolving.delete(channelName)\n }\n this.channels.set(channelName, channel)\n }\n return channel\n }\n\n stack(channels: string[]): Logger {\n return new StackLogger(channels.map((name) => this.channel(name)))\n }\n\n log(logLevel: LogLevel, message: string, context?: Record<string, unknown>): void {\n this.channel().log(logLevel, message, context)\n }\n emergency(message: string, context?: Record<string, unknown>): void {\n this.channel().emergency(message, context)\n }\n alert(message: string, context?: Record<string, unknown>): void {\n this.channel().alert(message, context)\n }\n critical(message: string, context?: Record<string, unknown>): void {\n this.channel().critical(message, context)\n }\n error(message: string, context?: Record<string, unknown>): void {\n this.channel().error(message, context)\n }\n warning(message: string, context?: Record<string, unknown>): void {\n this.channel().warning(message, context)\n }\n notice(message: string, context?: Record<string, unknown>): void {\n this.channel().notice(message, context)\n }\n info(message: string, context?: Record<string, unknown>): void {\n this.channel().info(message, context)\n }\n debug(message: string, context?: Record<string, unknown>): void {\n this.channel().debug(message, context)\n }\n\n withContext(context: Record<string, unknown>): this {\n mergeLogContext(context)\n return this\n }\n}\n","import { BaseLogger } from './BaseLogger'\n\n/** The `null` channel: discards every entry (Laravel's `NullHandler`). */\nexport class NullLogger extends BaseLogger {\n protected write(): void {\n // Intentionally does nothing.\n }\n}\n","import type { Logger, LogLevel } from '@orieljs/contracts'\nimport { mergeLogContext } from './context'\n\n/** `Log.stack([...])`: fans every entry out to each constituent channel, which does its own level filtering. */\nexport class StackLogger implements Logger {\n constructor(private readonly channels: Logger[]) {}\n\n log(level: LogLevel, message: string, context?: Record<string, unknown>): void {\n for (const channel of this.channels) channel.log(level, message, context)\n }\n emergency(message: string, context?: Record<string, unknown>): void {\n this.log('emergency', message, context)\n }\n alert(message: string, context?: Record<string, unknown>): void {\n this.log('alert', message, context)\n }\n critical(message: string, context?: Record<string, unknown>): void {\n this.log('critical', message, context)\n }\n error(message: string, context?: Record<string, unknown>): void {\n this.log('error', message, context)\n }\n warning(message: string, context?: Record<string, unknown>): void {\n this.log('warning', message, context)\n }\n notice(message: string, context?: Record<string, unknown>): void {\n this.log('notice', message, context)\n }\n info(message: string, context?: Record<string, unknown>): void {\n this.log('info', message, context)\n }\n debug(message: string, context?: Record<string, unknown>): void {\n this.log('debug', message, context)\n }\n\n /** Context is scoped by the container (see context.ts), not per-instance, so this affects every channel. */\n withContext(context: Record<string, unknown>): this {\n mergeLogContext(context)\n return this\n }\n}\n","import { LogManager as LogManagerToken } from '@orieljs/contracts'\nimport { ServiceProvider } from '@orieljs/support'\nimport { LogManager } from './LogManager'\n\n/** Binds the LogManager and merges Laravel 11's `logging` defaults (stack -> single, LOG_LEVEL=debug). */\nexport class LogServiceProvider extends ServiceProvider {\n override register(): void {\n const level = process.env.LOG_LEVEL ?? 'debug'\n this.mergeConfigFrom(\n {\n default: process.env.LOG_CHANNEL ?? 'stack',\n channels: {\n stack: { driver: 'stack', channels: (process.env.LOG_STACK ?? 'single').split(',') },\n single: { driver: 'single', path: this.app.storagePath('logs/oriel.log'), level },\n daily: { driver: 'daily', path: this.app.storagePath('logs/oriel.log'), level, days: 14 },\n stderr: { driver: 'stderr', level },\n null: { driver: 'null' },\n },\n },\n 'logging',\n )\n this.app.singleton(LogManagerToken, (container) => new LogManager(container))\n }\n}\n","import type { OrielError } from '@orieljs/contracts'\n\nexport class UnknownMailerError extends Error implements OrielError {\n readonly kind = 'Server' as const\n readonly status = 500\n override readonly name = 'UnknownMailerError'\n constructor(name: string) {\n super(`Mailer [${name}] is not configured. Add it to config('mail.mailers').`)\n }\n}\n\nexport class UnknownMailTransportError extends Error implements OrielError {\n readonly kind = 'Server' as const\n readonly status = 500\n override readonly name = 'UnknownMailTransportError'\n constructor(transport: string) {\n super(`Mail transport [${transport}] is not supported. Register it first with MailManager.extend().`)\n }\n}\n\nexport class MissingRecipientError extends Error implements OrielError {\n readonly kind = 'Server' as const\n readonly status = 500\n override readonly name = 'MissingRecipientError'\n constructor() {\n super('Cannot send mail: no recipients. Set envelope().to, or call Mail.to(...).send(mailable).')\n }\n}\n\nexport class MailQueueUnavailableError extends Error implements OrielError {\n readonly kind = 'Server' as const\n readonly status = 500\n override readonly name = 'MailQueueUnavailableError'\n constructor() {\n super('Queueing mail requires the Bus component. Register BusDispatcher, or call send() instead of queue()/later().')\n }\n}\n\nexport class ViewFactoryUnavailableError extends Error implements OrielError {\n readonly kind = 'Server' as const\n readonly status = 500\n override readonly name = 'ViewFactoryUnavailableError'\n constructor(view: string) {\n super(`Cannot render the [${view}] mail view: the View component isn't registered (ViewFactory is unbound).`)\n }\n}\n\nexport class AllMailersFailedError extends Error implements OrielError {\n readonly kind = 'Server' as const\n readonly status = 500\n override readonly name = 'AllMailersFailedError'\n constructor(\n readonly mailers: string[],\n readonly causes: unknown[],\n ) {\n super(`All failover mailers failed: ${mailers.join(', ')}. Last error: ${String(causes.at(-1))}`, {\n cause: causes.at(-1),\n })\n }\n}\n","import type { Address, MailRecipient } from '@orieljs/contracts'\n\n/** A MailRecipient is a bare string, an Address, or anything with `email` (+ optional `name`), such as a User model. */\nexport function normalizeAddress(recipient: MailRecipient): Address {\n if (typeof recipient === 'string') return { address: recipient }\n if ('address' in recipient) return { address: recipient.address, name: recipient.name }\n return { address: recipient.email, name: recipient.name }\n}\n\nexport function normalizeAddresses(recipients: MailRecipient | MailRecipient[] | undefined): Address[] {\n if (recipients === undefined) return []\n const list = Array.isArray(recipients) ? recipients : [recipients]\n return list.map(normalizeAddress)\n}\n\nexport function formatAddress(address: Address): string {\n return address.name ? `${address.name} <${address.address}>` : address.address\n}\n","import { randomUUID } from 'node:crypto'\nimport type { MailTransport, OutgoingMessage, SentMessage } from '@orieljs/contracts'\n\n/** In-memory transport backing the `array` mailer: never leaves the process, so tests can inspect `sent`. */\nexport class ArrayTransport implements MailTransport {\n readonly sent: OutgoingMessage[] = []\n\n async send(message: OutgoingMessage): Promise<SentMessage> {\n this.sent.push(message)\n return { messageId: randomUUID(), message }\n }\n\n flush(): void {\n this.sent.length = 0\n }\n}\n","import { randomUUID } from 'node:crypto'\nimport { LogManager as LogManagerToken, type MailTransport, type OutgoingMessage, type SentMessage } from '@orieljs/contracts'\nimport { currentContainer } from '@orieljs/container'\nimport { formatAddress } from '../address'\n\n/** Writes the message through LogManager (a channel from config, or the default channel) when bound, else console.log. */\nexport class LogTransport implements MailTransport {\n constructor(private readonly channel?: string) {}\n\n async send(message: OutgoingMessage): Promise<SentMessage> {\n const dump = formatMessage(message)\n const container = currentContainer()\n if (container?.bound(LogManagerToken)) {\n const manager = container.make(LogManagerToken)\n const logger = this.channel ? manager.channel(this.channel) : manager\n logger.info(dump)\n } else {\n console.log(dump)\n }\n return { messageId: randomUUID(), message }\n }\n}\n\nfunction formatMessage(message: OutgoingMessage): string {\n const lines = [\n `To: ${message.to.map(formatAddress).join(', ')}`,\n message.cc.length > 0 ? `Cc: ${message.cc.map(formatAddress).join(', ')}` : undefined,\n message.bcc.length > 0 ? `Bcc: ${message.bcc.map(formatAddress).join(', ')}` : undefined,\n `From: ${formatAddress(message.from)}`,\n `Subject: ${message.subject}`,\n '',\n message.text ?? stripHtml(message.html ?? ''),\n ]\n return lines.filter((line): line is string => line !== undefined).join('\\n')\n}\n\nfunction stripHtml(html: string): string {\n return html.replace(/<[^>]*>/g, '')\n}\n","import type { MailTransport, OutgoingMessage, SentMessage } from '@orieljs/contracts'\nimport { AllMailersFailedError } from '../errors'\n\n/** Tries each transport in order, returning the first success (Laravel's `failover` mailer). */\nexport class FailoverTransport implements MailTransport {\n constructor(\n private readonly transports: MailTransport[],\n private readonly names: string[],\n ) {}\n\n async send(message: OutgoingMessage): Promise<SentMessage> {\n const causes: unknown[] = []\n for (const transport of this.transports) {\n try {\n return await transport.send(message)\n } catch (error) {\n causes.push(error)\n }\n }\n throw new AllMailersFailedError(this.names, causes)\n }\n}\n","import nodemailer from 'nodemailer'\nimport type { MailTransport, OutgoingMessage, SentMessage } from '@orieljs/contracts'\nimport { formatAddress } from '../address'\n\nexport interface SmtpConfig {\n host: string\n port: number\n encryption?: 'tls' | 'ssl' | null\n username?: string\n password?: string\n}\n\n/** The minimal nodemailer surface this transport needs — lets tests inject a fake without a real Transporter. */\nexport interface MailTransporter {\n sendMail(options: Record<string, unknown>): Promise<{ messageId: string }>\n}\n\nexport type TransporterFactory = (config: SmtpConfig) => MailTransporter\n\nconst defaultFactory: TransporterFactory = (config) =>\n nodemailer.createTransport({\n host: config.host,\n port: config.port,\n secure: config.encryption === 'ssl',\n requireTLS: config.encryption === 'tls',\n auth: config.username ? { user: config.username, pass: config.password } : undefined,\n })\n\nexport class SmtpTransport implements MailTransport {\n private readonly transporter: MailTransporter\n\n constructor(config: SmtpConfig, factory: TransporterFactory = defaultFactory) {\n this.transporter = factory(config)\n }\n\n async send(message: OutgoingMessage): Promise<SentMessage> {\n const info = await this.transporter.sendMail({\n from: formatAddress(message.from),\n to: message.to.map(formatAddress),\n cc: message.cc.length > 0 ? message.cc.map(formatAddress) : undefined,\n bcc: message.bcc.length > 0 ? message.bcc.map(formatAddress) : undefined,\n replyTo: message.replyTo.length > 0 ? message.replyTo.map(formatAddress) : undefined,\n subject: message.subject,\n html: message.html,\n text: message.text,\n headers: message.headers,\n attachments: message.attachments.map((attachment) => ({\n filename: attachment.name,\n path: attachment.path,\n content: attachment.data,\n contentType: attachment.mime,\n })),\n })\n return { messageId: info.messageId, message }\n }\n}\n","import { ViewFactory as ViewFactoryToken, type Content } from '@orieljs/contracts'\nimport { currentContainer } from '@orieljs/container'\nimport { ViewFactoryUnavailableError } from './errors'\n\nexport interface RenderedContent {\n html?: string\n text?: string\n}\n\n/**\n * Renders a Mailable's content() into transport-ready HTML/text. A `view`/`text` name is resolved through\n * ViewFactory (TSX); `htmlString`/`textString` are used as-is, with no View involved at all.\n */\nexport async function renderContent(content: Content): Promise<RenderedContent> {\n const html = content.view !== undefined ? await renderView(content.view, content.with) : content.htmlString\n const text = content.text !== undefined ? await renderView(content.text, content.with) : content.textString\n return { html, text }\n}\n\nasync function renderView(view: string, data: Record<string, unknown> | undefined): Promise<string> {\n const container = currentContainer()\n if (!container?.bound(ViewFactoryToken)) throw new ViewFactoryUnavailableError(view)\n return container.make(ViewFactoryToken).make(view, data).render()\n}\n","import type { Attachment, Content, Envelope, MailRecipient, Mailable as MailableContract } from '@orieljs/contracts'\n\n/**\n * Laravel-style Mailable. New code overrides envelope()/content()/attachments() directly. Legacy (pre-Laravel-9)\n * code overrides build() instead, and calls the fluent subject()/view()/text()/html()/from()/with()/attach()\n * methods, which feed the default envelope()/content()/attachments() below. build() runs at most once.\n */\nexport abstract class Mailable implements MailableContract {\n protected mailSubject?: string\n protected mailView?: string\n protected mailTextView?: string\n protected mailHtml?: string\n protected mailFrom?: MailRecipient\n protected mailData: Record<string, unknown> = {}\n protected mailAttachments: Attachment[] = []\n private built = false\n\n /** Legacy hook: override this and call the fluent methods below instead of envelope()/content()/attachments(). */\n build?(): void | Promise<void>\n\n subject(subject: string): this {\n this.mailSubject = subject\n return this\n }\n\n view(view: string): this {\n this.mailView = view\n return this\n }\n\n text(view: string): this {\n this.mailTextView = view\n return this\n }\n\n html(html: string): this {\n this.mailHtml = html\n return this\n }\n\n from(address: MailRecipient): this {\n this.mailFrom = address\n return this\n }\n\n with(key: string | Record<string, unknown>, value?: unknown): this {\n if (typeof key === 'string') this.mailData[key] = value\n else Object.assign(this.mailData, key)\n return this\n }\n\n attach(attachment: Attachment): this {\n this.mailAttachments.push(attachment)\n return this\n }\n\n private async ensureBuilt(): Promise<void> {\n if (this.built) return\n this.built = true\n await this.build?.()\n }\n\n async envelope(): Promise<Envelope> {\n await this.ensureBuilt()\n return { subject: this.mailSubject, from: this.mailFrom }\n }\n\n async content(): Promise<Content> {\n await this.ensureBuilt()\n return { view: this.mailView, text: this.mailTextView, htmlString: this.mailHtml, with: this.mailData }\n }\n\n async attachments(): Promise<Attachment[]> {\n await this.ensureBuilt()\n return this.mailAttachments\n }\n}\n","/**\n * The Queue/Bus protocol's shared marker (the \"Queue/Bus protocol\" section of the Queue/Bus design notes):\n * `Symbol.for('oriel:bus.shouldQueue')` is a *global* registry key, so `Symbol.for` called here returns the\n * literal same runtime symbol Bus's `Queueable` base class and `isQueueable()` use — genuinely shared state, with\n * no import needed (and none allowed: Mail can't import `@orieljs/bus`).\n */\nexport const SHOULD_QUEUE: unique symbol = Symbol.for('oriel:bus.shouldQueue')\n","import {\n BusDispatcher as BusDispatcherToken,\n type Address,\n type Job,\n type Mailable,\n type MailRecipient,\n type Mailer as MailerContract,\n type MailTransport,\n type OutgoingMessage,\n type PendingMail as PendingMailContract,\n type SentMessage,\n} from '@orieljs/contracts'\nimport { currentContainer } from '@orieljs/container'\nimport { normalizeAddress, normalizeAddresses } from './address'\nimport { MailQueueUnavailableError, MissingRecipientError } from './errors'\nimport { renderContent } from './render'\nimport { SHOULD_QUEUE } from './symbols'\n\nexport interface RecipientOverrides {\n to?: Address[]\n cc?: Address[]\n bcc?: Address[]\n}\n\n/** Builds the queue job for a mailable. Decoupled from the concrete SendQueuedMailable class so this\n * file has no forward reference to it, and so tests can inject a fake job. */\nexport type QueuedMailableFactory = (\n mailerName: string | undefined,\n mailable: Mailable,\n overrides?: RecipientOverrides,\n) => Job\n\n/**\n * Matches the Queue/Bus protocol's `isQueueable()` exactly: true when the mailable carries\n * `SHOULD_QUEUE === true`, or has a defined value for any of ShouldQueue's fields, or declares a\n * `uniqueId()`/`retryUntil()` method. `implements ShouldQueue` itself leaves no trace at runtime. Call\n * queue()/later() explicitly to queue a mailable that declares none of these.\n */\nfunction isQueueableMailable(mailable: Mailable): boolean {\n const record = mailable as unknown as Record<PropertyKey, unknown>\n if (record[SHOULD_QUEUE] === true) return true\n return (\n record.connection !== undefined ||\n record.queue !== undefined ||\n record.delay !== undefined ||\n record.tries !== undefined ||\n record.backoff !== undefined ||\n record.timeout !== undefined ||\n typeof record.uniqueId === 'function' ||\n typeof record.retryUntil === 'function'\n )\n}\n\nexport class MailerImpl implements MailerContract {\n constructor(\n private readonly name: string,\n private readonly transport: MailTransport,\n private readonly defaultFrom: Address | undefined,\n private readonly makeQueuedJob: QueuedMailableFactory,\n ) {}\n\n to(recipients: MailRecipient | MailRecipient[]): PendingMailContract {\n return new PendingMail(this, normalizeAddresses(recipients))\n }\n\n async send(mailable: Mailable, overrides?: RecipientOverrides): Promise<SentMessage | undefined> {\n if (isQueueableMailable(mailable)) {\n await this.queue(mailable, overrides)\n return undefined\n }\n return this.sendNow(mailable, overrides)\n }\n\n async queue(mailable: Mailable, overrides?: RecipientOverrides): Promise<void> {\n await this.dispatch(this.makeQueuedJob(this.name, mailable, overrides))\n }\n\n async later(delaySeconds: number, mailable: Mailable, overrides?: RecipientOverrides): Promise<void> {\n const job = this.makeQueuedJob(this.name, mailable, overrides)\n job.delay = delaySeconds\n await this.dispatch(job)\n }\n\n private async dispatch(job: Job): Promise<void> {\n const container = currentContainer()\n if (!container?.bound(BusDispatcherToken)) throw new MailQueueUnavailableError()\n await container.make(BusDispatcherToken).dispatch(job)\n }\n\n /** Renders and delivers immediately, bypassing the queueable check. Used by send() and by the queued job's\n * handle(), once it's already running on the worker. */\n async sendNow(mailable: Mailable, overrides?: RecipientOverrides): Promise<SentMessage> {\n const envelope = await mailable.envelope()\n const to = overrides?.to && overrides.to.length > 0 ? overrides.to : normalizeAddresses(envelope.to)\n if (to.length === 0) throw new MissingRecipientError()\n const cc = [...normalizeAddresses(envelope.cc), ...(overrides?.cc ?? [])]\n const bcc = [...normalizeAddresses(envelope.bcc), ...(overrides?.bcc ?? [])]\n const replyTo = normalizeAddresses(envelope.replyTo)\n const from = envelope.from ? normalizeAddress(envelope.from) : this.defaultFrom\n if (!from) throw new MissingRecipientError()\n const content = await mailable.content()\n const rendered = await renderContent(content)\n const attachments = (await mailable.attachments?.()) ?? []\n const message: OutgoingMessage = {\n from,\n to,\n cc,\n bcc,\n replyTo,\n subject: envelope.subject ?? '',\n html: rendered.html,\n text: rendered.text,\n attachments,\n headers: {},\n }\n return this.transport.send(message)\n }\n}\n\nclass PendingMail implements PendingMailContract {\n private readonly ccList: Address[] = []\n private readonly bccList: Address[] = []\n\n constructor(\n private readonly mailer: MailerImpl,\n private readonly toList: Address[],\n ) {}\n\n cc(recipients: MailRecipient | MailRecipient[]): this {\n this.ccList.push(...normalizeAddresses(recipients))\n return this\n }\n\n bcc(recipients: MailRecipient | MailRecipient[]): this {\n this.bccList.push(...normalizeAddresses(recipients))\n return this\n }\n\n private overrides(): RecipientOverrides {\n return { to: this.toList, cc: this.ccList, bcc: this.bccList }\n }\n\n async send(mailable: Mailable): Promise<SentMessage | undefined> {\n return this.mailer.send(mailable, this.overrides())\n }\n\n async queue(mailable: Mailable): Promise<void> {\n await this.mailer.queue(mailable, this.overrides())\n }\n\n async later(delaySeconds: number, mailable: Mailable): Promise<void> {\n await this.mailer.later(delaySeconds, mailable, this.overrides())\n }\n}\n","import { token, type Mailable, type SentMessage } from '@orieljs/contracts'\nimport type { RecipientOverrides } from './Mailer'\n\n/**\n * Internal-only token. `SendQueuedMailable.handle()` runs on the worker, where the mailable's ShouldQueue fields\n * are still set — calling the public `Mailer.send()` there would re-detect it as queueable and dispatch it again,\n * forever. `MailServiceProvider` binds this to the *same* MailManager instance as the public `MailManager` token,\n * so `sendNow()` here always delivers immediately.\n */\nexport interface QueuedMailSender {\n sendNow(mailerName: string | undefined, mailable: Mailable, overrides?: RecipientOverrides): Promise<SentMessage>\n}\nexport const QueuedMailSender = token<QueuedMailSender>('Mail.QueuedMailSender')\n","import type { Address, Job, Mailable } from '@orieljs/contracts'\nimport { inject } from '@orieljs/container'\nimport { QueuedMailSender } from '../QueuedMailSender'\nimport { SHOULD_QUEUE } from '../symbols'\n\n/** The ShouldQueue options copied from the mailable onto the wrapper job. */\nconst QUEUE_OPTIONS = [\n 'connection',\n 'queue',\n 'delay',\n 'tries',\n 'backoff',\n 'timeout',\n 'failOnTimeout',\n 'deleteWhenMissingModels',\n] as const\n\n/** The job hooks Queue reads off a job instance, when the wrapped mailable defines them. */\ninterface JobHooks {\n failed?: (error: unknown) => unknown\n retryUntil?: () => unknown\n middleware?: unknown[] | (() => unknown[])\n}\n\n/** Copies the mailable's own ShouldQueue fields onto the wrapper job (when set), so once Queue actually runs the\n * job, its delay/retry/backoff/connection routing reflects what the app developer put on the Mailable. Uses\n * `declare` fields on the class (no runtime auto-initialization to `undefined`), so a field is a genuinely own\n * property only when the mailable actually set it. */\nfunction copyShouldQueueFields(target: Record<PropertyKey, unknown>, source: object): void {\n const fields = source as Record<string, unknown>\n for (const option of QUEUE_OPTIONS) {\n if (fields[option] !== undefined) target[option] = fields[option]\n }\n}\n\n/**\n * Dispatched by MailerImpl.queue()/later()/send() (when queueable). Runs on the worker: renders and delivers the\n * mailable through QueuedMailSender, bypassing the queueable check (it's already on the worker, not the request).\n *\n * Carries `SHOULD_QUEUE` on its own prototype, per the Queue/Bus protocol, so `BusDispatcher.dispatch()` — which\n * re-decides queued-or-now on whatever job it's handed — actually enqueues it instead of running it inline; the\n * mailable's own queueability (checked by MailerImpl) only decides whether to wrap it at all. Like Laravel's\n * SendQueuedMailable, it forwards failed(), retryUntil(), middleware() and displayName() to the mailable.\n */\nexport class SendQueuedMailable implements Job {\n declare connection?: string\n declare queue?: string\n declare delay?: number\n declare tries?: number\n declare backoff?: number | number[]\n declare timeout?: number\n declare failOnTimeout?: boolean\n declare deleteWhenMissingModels?: boolean\n\n constructor(\n readonly mailerName: string | undefined,\n readonly mailable: Mailable,\n readonly to?: Address[],\n readonly cc?: Address[],\n readonly bcc?: Address[],\n ) {\n copyShouldQueueFields(this as unknown as Record<PropertyKey, unknown>, mailable)\n }\n\n async handle(): Promise<void> {\n await inject(QueuedMailSender).sendNow(this.mailerName, this.mailable, { to: this.to, cc: this.cc, bcc: this.bcc })\n }\n\n /** Called by Queue after the final failed attempt. */\n async failed(error: unknown): Promise<void> {\n const hooks = this.mailable as unknown as JobHooks\n if (typeof hooks.failed === 'function') await hooks.failed.call(this.mailable, error)\n }\n\n /** `failed_jobs` and `queue:failed` show the mailable's class, not the wrapper's. */\n displayName(): string {\n return this.mailable.constructor.name\n }\n\n retryUntil(): unknown {\n const hooks = this.mailable as unknown as JobHooks\n return typeof hooks.retryUntil === 'function' ? hooks.retryUntil.call(this.mailable) : undefined\n }\n\n middleware(): unknown[] {\n const declared = (this.mailable as unknown as JobHooks).middleware\n return (typeof declared === 'function' ? declared.call(this.mailable) : declared) ?? []\n }\n}\n;(SendQueuedMailable.prototype as unknown as Record<PropertyKey, unknown>)[SHOULD_QUEUE] = true\n","import {\n ConfigRepository,\n type Address,\n type Container,\n type Mailable,\n type MailManager as MailManagerContract,\n type MailRecipient,\n type MailTransport,\n type PendingMail,\n type SentMessage,\n} from '@orieljs/contracts'\nimport { ArrayTransport } from './transports/ArrayTransport'\nimport { FailoverTransport } from './transports/FailoverTransport'\nimport { LogTransport } from './transports/LogTransport'\nimport { SmtpTransport, type SmtpConfig } from './transports/SmtpTransport'\nimport { UnknownMailerError, UnknownMailTransportError } from './errors'\nimport { MailerImpl, type RecipientOverrides } from './Mailer'\nimport { SendQueuedMailable } from './Jobs/SendQueuedMailable'\nimport type { QueuedMailSender } from './QueuedMailSender'\n\ntype TransportFactory = (config: Record<string, unknown>) => MailTransport\n\nexport class MailManager implements MailManagerContract, QueuedMailSender {\n private readonly mailers = new Map<string, MailerImpl>()\n private readonly drivers = new Map<string, TransportFactory>([\n ['array', () => new ArrayTransport()],\n ['log', (config) => new LogTransport(config.channel as string | undefined)],\n [\n 'smtp',\n (config) =>\n new SmtpTransport({\n host: String(config.host ?? '127.0.0.1'),\n port: Number(config.port ?? 2525),\n encryption: (config.encryption as SmtpConfig['encryption']) ?? null,\n username: config.username as string | undefined,\n password: config.password as string | undefined,\n }),\n ],\n ])\n\n constructor(private readonly container: Container) {}\n\n private config(): ConfigRepository {\n return this.container.make(ConfigRepository)\n }\n\n mailer(name?: string): MailerImpl {\n const mailerName = name ?? this.config().get<string>('mail.default', 'log')\n const cached = this.mailers.get(mailerName)\n if (cached) return cached\n const config = this.config().get<Record<string, unknown> | undefined>(`mail.mailers.${mailerName}`)\n if (!config) throw new UnknownMailerError(mailerName)\n const transport = this.buildTransport(String(config.transport ?? ''), config)\n const from = this.config().get<Address | undefined>('mail.from')\n const impl = new MailerImpl(mailerName, transport, from, (mailerNameArg, mailable, overrides) =>\n new SendQueuedMailable(mailerNameArg, mailable, overrides?.to, overrides?.cc, overrides?.bcc),\n )\n this.mailers.set(mailerName, impl)\n return impl\n }\n\n private buildTransport(transportName: string, config: Record<string, unknown>): MailTransport {\n if (transportName === 'failover') {\n const names = (config.mailers as string[] | undefined) ?? []\n const transports = names.map((mailerName) => {\n const mailerConfig = this.config().get<Record<string, unknown> | undefined>(`mail.mailers.${mailerName}`)\n if (!mailerConfig) throw new UnknownMailerError(mailerName)\n return this.buildTransport(String(mailerConfig.transport ?? ''), mailerConfig)\n })\n return new FailoverTransport(transports, names)\n }\n const factory = this.drivers.get(transportName)\n if (!factory) throw new UnknownMailTransportError(transportName)\n return factory(config)\n }\n\n to(recipients: MailRecipient | MailRecipient[]): PendingMail {\n return this.mailer().to(recipients)\n }\n\n async send(mailable: Mailable): Promise<SentMessage | undefined> {\n return this.mailer().send(mailable)\n }\n\n async queue(mailable: Mailable): Promise<void> {\n await this.mailer().queue(mailable)\n }\n\n /** QueuedMailSender: always delivers immediately (see QueuedMailSender.ts for why this must bypass send()). */\n async sendNow(mailerName: string | undefined, mailable: Mailable, overrides?: RecipientOverrides): Promise<SentMessage> {\n return this.mailer(mailerName).sendNow(mailable, overrides)\n }\n\n extend(transport: string, factory: TransportFactory): void {\n this.drivers.set(transport, factory)\n }\n}\n","import type { MailManager as MailManagerContract } from '@orieljs/contracts'\nimport { MailManager as MailManagerToken } from '@orieljs/contracts'\nimport { facade } from '@orieljs/support'\n\nexport const Mail = facade<MailManagerContract>(MailManagerToken)\n","import { ClassRegistry as ClassRegistryToken, MailManager as MailManagerToken } from '@orieljs/contracts'\nimport { ServiceProvider } from '@orieljs/support'\nimport { SendQueuedMailable } from './Jobs/SendQueuedMailable'\nimport { MailManager } from './MailManager'\nimport { QueuedMailSender } from './QueuedMailSender'\n\nexport class MailServiceProvider extends ServiceProvider {\n override register(): void {\n this.mergeConfigFrom(\n {\n default: 'log',\n mailers: {\n smtp: { transport: 'smtp', host: '127.0.0.1', port: 2525 },\n log: { transport: 'log' },\n array: { transport: 'array' },\n failover: { transport: 'failover', mailers: ['smtp', 'log'] },\n },\n from: { address: 'hello@example.com', name: 'Example' },\n },\n 'mail',\n )\n this.app.singleton(MailManagerToken, (container) => new MailManager(container))\n // Same instance under a second, internal token — see QueuedMailSender.ts for why. The token is typed with the\n // MailManager contract, which has no sendNow(), so narrow it to the concrete class bound just above.\n this.app.singleton(QueuedMailSender, (container) => container.make(MailManagerToken) as MailManager)\n // Namespaced name, registered in register() (not boot()) — the Queue/Bus protocol rule for wrapper classes.\n // ClassRegistry is safe to use here: Application's own constructor binds it before any provider registers.\n this.app.make(ClassRegistryToken).register(SendQueuedMailable, 'Mail.SendQueuedMailable')\n }\n}\n","import type { OrielError } from '@orieljs/contracts'\n\nexport class UnrenderableNotificationMailError extends Error implements OrielError {\n readonly kind = 'Server' as const\n readonly status = 500\n override readonly name = 'UnrenderableNotificationMailError'\n constructor(notification: string) {\n super(\n `[${notification}].toMail() must return a Mailable, a MailMessage, or ` +\n '{ subject?, greeting?, lines, actionText?, actionUrl?, outroLines?, salutation? }.',\n )\n }\n}\n\nexport class MailUnavailableError extends Error implements OrielError {\n readonly kind = 'Server' as const\n readonly status = 500\n override readonly name = 'MailUnavailableError'\n constructor() {\n super(\"Sending a notification's mail requires the Mail component. Register MailManager first.\")\n }\n}\n\nexport class DatabaseUnavailableError extends Error implements OrielError {\n readonly kind = 'Server' as const\n readonly status = 500\n override readonly name = 'DatabaseUnavailableError'\n constructor() {\n super('The database notification channel requires the Database component. Register DatabaseManager first.')\n }\n}\n\nexport class NotDatabaseNotifiableError extends Error implements OrielError {\n readonly kind = 'Server' as const\n readonly status = 500\n override readonly name = 'NotDatabaseNotifiableError'\n constructor(notifiable: string) {\n super(`[${notifiable}] has no getKey() — the database channel and notification-listing methods need a model.`)\n }\n}\n\nexport class UnrenderableNotificationDataError extends Error implements OrielError {\n readonly kind = 'Server' as const\n readonly status = 500\n override readonly name = 'UnrenderableNotificationDataError'\n constructor(notification: string) {\n super(`[${notification}] needs a toDatabase() or toArray() method to use the database channel.`)\n }\n}\n\nexport class UnknownNotificationChannelError extends Error implements OrielError {\n readonly kind = 'Server' as const\n readonly status = 500\n override readonly name = 'UnknownNotificationChannelError'\n constructor(channel: string) {\n super(`Notification channel [${channel}] is not registered. Register it first with NotificationDispatcher.extend().`)\n }\n}\n\nexport class NotificationQueueUnavailableError extends Error implements OrielError {\n readonly kind = 'Server' as const\n readonly status = 500\n override readonly name = 'NotificationQueueUnavailableError'\n constructor() {\n super('Queueing a notification requires the Bus component. Register BusDispatcher, or call sendNow() instead.')\n }\n}\n\nexport class NotificationDispatcherUnavailableError extends Error implements OrielError {\n readonly kind = 'Server' as const\n readonly status = 500\n override readonly name = 'NotificationDispatcherUnavailableError'\n constructor() {\n super('notify()/notifyNow() require the Notifications component. Register NotificationDispatcher first.')\n }\n}\n","import type { MailRecipient } from '@orieljs/contracts'\n\nexport interface MailMessageAction {\n text: string\n url: string\n}\n\n/**\n * Laravel's Illuminate\\Notifications\\Messages\\MailMessage: greeting/line/action/salutation, rendered to a default\n * HTML+text template with no View involved. line() appends to the intro before action() is called, and to the\n * outro afterwards — exactly like Laravel's SimpleMessage.\n */\nexport class MailMessage {\n subjectLine?: string\n greetingLine?: string\n introLines: string[] = []\n actionData?: MailMessageAction\n outroLines: string[] = []\n salutationLine = 'Regards,\\nApplication'\n toAddresses: MailRecipient[] = []\n ccAddresses: MailRecipient[] = []\n bccAddresses: MailRecipient[] = []\n fromAddress?: MailRecipient\n\n subject(subject: string): this {\n this.subjectLine = subject\n return this\n }\n\n greeting(greeting: string): this {\n this.greetingLine = greeting\n return this\n }\n\n /** Before action(), appends to the intro; after action(), to the outro. */\n line(text: string): this {\n ;(this.actionData ? this.outroLines : this.introLines).push(text)\n return this\n }\n\n lines(lines: string[]): this {\n for (const line of lines) this.line(line)\n return this\n }\n\n action(text: string, url: string): this {\n this.actionData = { text, url }\n return this\n }\n\n salutation(salutation: string): this {\n this.salutationLine = salutation\n return this\n }\n\n from(address: MailRecipient): this {\n this.fromAddress = address\n return this\n }\n\n to(recipients: MailRecipient | MailRecipient[]): this {\n this.toAddresses.push(...(Array.isArray(recipients) ? recipients : [recipients]))\n return this\n }\n\n cc(recipients: MailRecipient | MailRecipient[]): this {\n this.ccAddresses.push(...(Array.isArray(recipients) ? recipients : [recipients]))\n return this\n }\n\n bcc(recipients: MailRecipient | MailRecipient[]): this {\n this.bccAddresses.push(...(Array.isArray(recipients) ? recipients : [recipients]))\n return this\n }\n\n /** Renders the default notification mail template. No ViewFactory involved. */\n render(): { html: string; text: string } {\n const greeting = this.greetingLine ?? 'Hello!'\n const html: string[] = [`<p>${escapeHtml(greeting)}</p>`]\n const text: string[] = [greeting]\n\n for (const line of this.introLines) {\n html.push(`<p>${escapeHtml(line)}</p>`)\n text.push(line)\n }\n if (this.actionData) {\n const { text: actionText, url } = this.actionData\n html.push(`<p><a href=\"${escapeHtml(url)}\" class=\"button\" target=\"_blank\">${escapeHtml(actionText)}</a></p>`)\n text.push(`${actionText}: ${url}`)\n }\n for (const line of this.outroLines) {\n html.push(`<p>${escapeHtml(line)}</p>`)\n text.push(line)\n }\n html.push(`<p>${escapeHtml(this.salutationLine).replace(/\\n/g, '<br>')}</p>`)\n text.push(this.salutationLine)\n\n return { html: `<!doctype html><html><body>${html.join('\\n')}</body></html>`, text: text.join('\\n\\n') }\n }\n}\n\nfunction escapeHtml(value: string): string {\n return value.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/\"/g, '"')\n}\n","import {\n MailManager as MailManagerToken,\n type Mailable,\n type MailRecipient,\n type Notifiable,\n type Notification,\n type NotificationChannel,\n} from '@orieljs/contracts'\nimport { currentContainer } from '@orieljs/container'\nimport { MailUnavailableError, UnrenderableNotificationMailError } from '../errors'\nimport { MailMessage } from '../MailMessage'\n\n/**\n * What Auth's default ResetPassword notification's toMail() returns: plain data, since Auth can't import\n * Notifications. `{ subject, lines, actionText, actionUrl, outroLines }` exactly; `greeting`/`salutation` are\n * optional extensions any other notification's plain toMail() may also use.\n */\nexport interface PlainNotificationMail {\n subject?: string\n greeting?: string\n lines: string[]\n actionText?: string\n actionUrl?: string\n outroLines?: string[]\n salutation?: string\n}\n\nfunction isMailable(value: unknown): value is Mailable {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as Mailable).envelope === 'function' &&\n typeof (value as Mailable).content === 'function'\n )\n}\n\nfunction isPlainNotificationMail(value: unknown): value is PlainNotificationMail {\n return typeof value === 'object' && value !== null && Array.isArray((value as PlainNotificationMail).lines)\n}\n\nfunction toMailMessage(result: unknown, notificationName: string): MailMessage {\n if (result instanceof MailMessage) return result\n if (!isPlainNotificationMail(result)) throw new UnrenderableNotificationMailError(notificationName)\n const message = new MailMessage()\n if (result.subject) message.subject(result.subject)\n if (result.greeting) message.greeting(result.greeting)\n message.lines(result.lines)\n if (result.actionText && result.actionUrl) message.action(result.actionText, result.actionUrl)\n for (const line of result.outroLines ?? []) message.line(line)\n if (result.salutation) message.salutation(result.salutation)\n return message\n}\n\n/**\n * Wraps a MailMessage as a Mailable, so it can go through MailManager.send() without a View: the default template's\n * HTML goes in `htmlString` and its plain-text twin in `textString`.\n */\nfunction mailableFromMessage(message: MailMessage, fallbackTo: MailRecipient[]): Mailable {\n return {\n envelope: async () => ({\n subject: message.subjectLine ?? '',\n to: message.toAddresses.length > 0 ? message.toAddresses : fallbackTo,\n cc: message.ccAddresses,\n bcc: message.bccAddresses,\n from: message.fromAddress,\n }),\n content: async () => {\n const rendered = message.render()\n return { htmlString: rendered.html, textString: rendered.text }\n },\n }\n}\n\nfunction normalizeRoute(route: unknown): MailRecipient[] {\n if (route === undefined || route === null) return []\n return Array.isArray(route) ? (route as MailRecipient[]) : [route as MailRecipient]\n}\n\nexport class MailNotificationChannel implements NotificationChannel {\n async send(notifiable: Notifiable, notification: Notification): Promise<void> {\n if (!notification.toMail) throw new UnrenderableNotificationMailError(notification.constructor.name)\n const result = await notification.toMail(notifiable)\n const to = normalizeRoute(notifiable.routeNotificationFor('mail', notification))\n\n // Matches Laravel's MailChannel: with no route and no Mailable to supply its own recipients, there's nothing to send.\n if (to.length === 0 && !isMailable(result)) return\n\n const mailable = isMailable(result) ? result : mailableFromMessage(toMailMessage(result, notification.constructor.name), to)\n const container = currentContainer()\n if (!container?.bound(MailManagerToken)) throw new MailUnavailableError()\n // MailManager.send() is the only send path the contract offers, so a queueable Mailable returned from toMail()\n // is queued again from here (even when this notification is itself running on a queue worker).\n await container.make(MailManagerToken).send(mailable)\n }\n}\n","import { randomUUID } from 'node:crypto'\nimport {\n DatabaseManager as DatabaseManagerToken,\n type DatabaseConnection,\n type ModelInstance,\n type Notifiable,\n type Notification,\n type NotificationChannel,\n type Row,\n} from '@orieljs/contracts'\nimport { currentContainer } from '@orieljs/container'\nimport { DatabaseUnavailableError, NotDatabaseNotifiableError, UnrenderableNotificationDataError } from '../errors'\n\nexport const NOTIFICATIONS_TABLE = 'notifications'\n\nexport interface DatabaseNotificationRecord {\n readonly id: string\n readonly type: string\n readonly data: Record<string, unknown>\n readonly createdAt: Date\n readonly updatedAt: Date\n readAt: Date | undefined\n markAsRead(): Promise<void>\n markAsUnread(): Promise<void>\n}\n\nconst ZONELESS_TIMESTAMP = /^\\d{4}-\\d{2}-\\d{2}[ T]\\d{2}:\\d{2}(:\\d{2}(\\.\\d+)?)?$/\n\n/**\n * Database writes Dates as zoneless UTC (`'2026-09-25 04:30:00'`) and hands them back as strings, so\n * `new Date()` would read such a string as local time; it is parsed as UTC here instead.\n */\nexport function parseStoredDate(value: unknown): Date {\n if (value instanceof Date) return value\n if (typeof value === 'number') return new Date(value)\n const text = String(value)\n return ZONELESS_TIMESTAMP.test(text) ? new Date(`${text.replace(' ', 'T')}Z`) : new Date(text)\n}\n\nfunction wrapRow(row: Row, db: DatabaseConnection): DatabaseNotificationRecord {\n const record: DatabaseNotificationRecord = {\n id: String(row.id),\n type: String(row.type),\n data: JSON.parse(String(row.data)) as Record<string, unknown>,\n createdAt: parseStoredDate(row.created_at),\n updatedAt: parseStoredDate(row.updated_at),\n readAt: row.read_at ? parseStoredDate(row.read_at) : undefined,\n async markAsRead() {\n if (record.readAt) return\n const now = new Date()\n await db.table(NOTIFICATIONS_TABLE).where('id', record.id).update({ read_at: now, updated_at: now })\n record.readAt = now\n },\n async markAsUnread() {\n if (!record.readAt) return\n await db.table(NOTIFICATIONS_TABLE).where('id', record.id).update({ read_at: null, updated_at: new Date() })\n record.readAt = undefined\n },\n }\n return record\n}\n\nfunction requireDatabase(): DatabaseConnection {\n const container = currentContainer()\n if (!container?.bound(DatabaseManagerToken)) throw new DatabaseUnavailableError()\n return container.make(DatabaseManagerToken).connection()\n}\n\n/** notifiable_type + notifiable_id together, never id alone. */\nexport async function fetchNotifications(\n notifiableType: string,\n notifiableId: unknown,\n filter: 'all' | 'read' | 'unread' = 'all',\n): Promise<DatabaseNotificationRecord[]> {\n const db = requireDatabase()\n let query = db\n .table(NOTIFICATIONS_TABLE)\n .where('notifiable_type', notifiableType)\n .where('notifiable_id', notifiableId)\n .orderBy('created_at', 'desc')\n if (filter === 'unread') query = query.whereNull('read_at')\n if (filter === 'read') query = query.whereNotNull('read_at')\n const rows = await query.get()\n return rows.all().map((row) => wrapRow(row, db))\n}\n\nexport class DatabaseNotificationChannel implements NotificationChannel {\n async send(notifiable: Notifiable, notification: Notification): Promise<void> {\n if (!notification.toDatabase && !notification.toArray) {\n throw new UnrenderableNotificationDataError(notification.constructor.name)\n }\n const data = notification.toDatabase ? notification.toDatabase(notifiable) : notification.toArray!(notifiable)\n const model = notifiable as Partial<ModelInstance>\n if (typeof model.getKey !== 'function') throw new NotDatabaseNotifiableError(notifiable.constructor.name)\n\n const db = requireDatabase()\n const now = new Date()\n await db.table(NOTIFICATIONS_TABLE).insert({\n id: notification.id ?? randomUUID(),\n type: notification.constructor.name,\n notifiable_type: notifiable.constructor.name,\n notifiable_id: model.getKey(),\n data: JSON.stringify(data),\n read_at: null,\n created_at: now,\n updated_at: now,\n })\n }\n}\n","export const NOTIFICATIONS_TABLE_MIGRATION = `import { Migration, Schema } from '@orieljs/framework'\n\nexport default class extends Migration {\n async up() {\n await Schema.create('notifications', (t) => {\n t.uuid('id').primary()\n t.string('type')\n t.morphs('notifiable')\n t.text('data')\n t.timestamp('read_at').nullable()\n t.timestamps()\n })\n }\n\n async down() {\n await Schema.dropIfExists('notifications')\n }\n}\n`\n","/**\n * The Queue/Bus protocol's shared marker (the \"Queue/Bus protocol\" section of the Queue/Bus design notes) —\n * identical to Mail's `symbols.ts`. `Symbol.for` is a *global* registry key, so this is the literal same runtime\n * symbol Bus's `Queueable` base class and `isQueueable()` use, with no import needed (and none allowed).\n */\nexport const SHOULD_QUEUE: unique symbol = Symbol.for('oriel:bus.shouldQueue')\n","import { randomUUID } from 'node:crypto'\nimport {\n BusDispatcher as BusDispatcherToken,\n type Container,\n type Notifiable,\n type Notification,\n type NotificationChannel,\n type NotificationDispatcher as NotificationDispatcherContract,\n} from '@orieljs/contracts'\nimport { AnonymousNotifiable } from './AnonymousNotifiable'\nimport { NotificationQueueUnavailableError, UnknownNotificationChannelError } from './errors'\nimport { SendQueuedNotifications } from './Jobs/SendQueuedNotifications'\nimport { SHOULD_QUEUE } from './symbols'\n\n/**\n * Matches the Queue/Bus protocol's `isQueueable()` exactly: true when the notification carries\n * `SHOULD_QUEUE === true`, or has a defined value for any of ShouldQueue's fields, or declares a\n * `uniqueId()`/`retryUntil()` method (same rule as Mail's `isQueueableMailable`). `implements ShouldQueue` itself\n * leaves no runtime trace. Call sendNow() explicitly to bypass this for a notification with none of these.\n */\nfunction isQueueableNotification(notification: Notification): boolean {\n const record = notification as unknown as Record<PropertyKey, unknown>\n if (record[SHOULD_QUEUE] === true) return true\n return (\n record.connection !== undefined ||\n record.queue !== undefined ||\n record.delay !== undefined ||\n record.tries !== undefined ||\n record.backoff !== undefined ||\n record.timeout !== undefined ||\n typeof record.uniqueId === 'function' ||\n typeof record.retryUntil === 'function'\n )\n}\n\n/**\n * The notification one notifiable receives. With no id set, a shallow copy (same prototype, own fields copied)\n * carrying a fresh id, so every notifiable gets its own id (the database channel's primary key) and the caller's\n * instance is left untouched; a caller-preset id is kept as is. The copy keeps its class, so Queue's serializer\n * restores it as that class on the worker.\n */\nfunction forNotifiable(notification: Notification): Notification {\n if (notification.id) return notification\n const copy = Object.assign(Object.create(Object.getPrototypeOf(notification) as object) as Notification, notification)\n copy.id = randomUUID()\n return copy\n}\n\n/**\n * One notifiable, an array, or any other iterable of them (a Database `Collection` from `await User.where(...).get()`,\n * a Set, ...), as Laravel's `Notification::send($users, ...)` accepts. A notifiable is recognised by its\n * routeNotificationFor() method first, so an iterable model is still treated as one notifiable.\n */\nexport function 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/** Resolves channels by name from a factory map — mirrors MailManager's driver resolution. */\nexport class Dispatcher implements NotificationDispatcherContract {\n private readonly factories = new Map<string, () => NotificationChannel>()\n private readonly channels = new Map<string, NotificationChannel>()\n\n constructor(private readonly container: Container) {}\n\n extend(channel: string, factory: () => NotificationChannel): void {\n this.factories.set(channel, factory)\n this.channels.delete(channel)\n }\n\n private resolve(name: string): NotificationChannel {\n const cached = this.channels.get(name)\n if (cached) return cached\n const factory = this.factories.get(name)\n if (!factory) throw new UnknownNotificationChannelError(name)\n const channel = factory()\n this.channels.set(name, channel)\n return channel\n }\n\n async send(notifiables: Notifiable | Iterable<Notifiable>, notification: Notification): Promise<void> {\n const list = toNotifiableList(notifiables)\n if (list.length === 0) return\n if (isQueueableNotification(notification)) {\n if (!this.container.bound(BusDispatcherToken)) throw new NotificationQueueUnavailableError()\n const bus = this.container.make(BusDispatcherToken)\n // One job per notifiable per channel, as Laravel does, so a failing channel or recipient retries alone.\n for (const notifiable of list) {\n const own = forNotifiable(notification)\n for (const channel of notification.via(notifiable)) {\n await bus.dispatch(new SendQueuedNotifications([notifiable], own, [channel]))\n }\n }\n return\n }\n await this.sendNow(list, notification)\n }\n\n async sendNow(notifiables: Notifiable | Iterable<Notifiable>, notification: Notification, channels?: string[]): Promise<void> {\n const list = toNotifiableList(notifiables)\n for (const notifiable of list) {\n const own = forNotifiable(notification)\n const names = channels ?? notification.via(notifiable)\n for (const name of names) {\n // An on-demand notifiable has no model to store a row against, so it skips 'database' as in Laravel.\n if (name === 'database' && notifiable instanceof AnonymousNotifiable) continue\n await this.resolve(name).send(notifiable, own)\n }\n }\n }\n\n /** On-demand: an AnonymousNotifiable, whose notify() goes through the bound NotificationDispatcher. */\n route(channel: string, route: unknown): AnonymousNotifiable {\n return new AnonymousNotifiable().route(channel, route)\n }\n}\n","import {\n NotificationDispatcher as NotificationDispatcherToken,\n type ModelInstance,\n type Notifiable as NotifiableContract,\n type Notification,\n type NotificationDispatcher,\n} from '@orieljs/contracts'\nimport { currentContainer } from '@orieljs/container'\nimport { Str } from '@orieljs/support'\nimport { fetchNotifications, type DatabaseNotificationRecord } from './channels/DatabaseNotificationChannel'\nimport { NotDatabaseNotifiableError, NotificationDispatcherUnavailableError } from './errors'\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type NotifiableConstructor = new (...args: any[]) => object\n\n/** The bound NotificationDispatcher, or a clear error when the Notifications component isn't registered. */\nexport function resolveDispatcher(): NotificationDispatcher {\n const container = currentContainer()\n if (!container?.bound(NotificationDispatcherToken)) throw new NotificationDispatcherUnavailableError()\n return container.make(NotificationDispatcherToken)\n}\n\nfunction requireKey(instance: object): unknown {\n const model = instance as Partial<ModelInstance>\n if (typeof model.getKey !== 'function') throw new NotDatabaseNotifiableError(instance.constructor.name)\n return model.getKey()\n}\n\n/**\n * Mirrors Laravel's Illuminate\\Notifications\\Notifiable trait: `class User extends Notifiable(Model) {}`. Custom\n * routing per channel follows Laravel's own resolution order: a `routeNotificationFor<Channel>()` method (Studly\n * name) wins if present, else 'mail' reads `email`/`getAttribute('email')`, 'database' returns the instance itself\n * (the database channel derives the table row from it directly), and anything else is unrouted (`undefined`).\n */\nexport function Notifiable<TBase extends NotifiableConstructor>(Base: TBase) {\n return class NotifiableMixin extends Base implements NotifiableContract {\n routeNotificationFor(channel: string, notification: Notification): unknown {\n const custom = (this as unknown as Record<string, unknown>)[`routeNotificationFor${Str.studly(channel)}`]\n if (typeof custom === 'function') return (custom as (n: Notification) => unknown).call(this, notification)\n if (channel === 'mail') {\n const withAttrs = this as unknown as { email?: string; getAttribute?: (key: string) => unknown }\n return typeof withAttrs.getAttribute === 'function' ? withAttrs.getAttribute('email') : withAttrs.email\n }\n if (channel === 'database') return this\n return undefined\n }\n\n async notify(notification: Notification): Promise<void> {\n await resolveDispatcher().send(this as unknown as NotifiableContract, notification)\n }\n\n async notifyNow(notification: Notification, channels?: string[]): Promise<void> {\n await resolveDispatcher().sendNow(this as unknown as NotifiableContract, notification, channels)\n }\n\n notifications(): Promise<DatabaseNotificationRecord[]> {\n return fetchNotifications(this.constructor.name, requireKey(this))\n }\n\n unreadNotifications(): Promise<DatabaseNotificationRecord[]> {\n return fetchNotifications(this.constructor.name, requireKey(this), 'unread')\n }\n\n readNotifications(): Promise<DatabaseNotificationRecord[]> {\n return fetchNotifications(this.constructor.name, requireKey(this), 'read')\n }\n }\n}\n","import type { Notifiable, Notification } from '@orieljs/contracts'\nimport { resolveDispatcher } from './Notifiable'\n\n/**\n * Returned by `Notification.route(channel, address)` for sending to an address with no model behind it. The\n * routes are an own plain record and every method sits on the prototype, so a queued on-demand notification\n * survives Queue's serializer (which rejects functions in own fields) and is restored on the worker as this class\n * (registered as `'Notifications.AnonymousNotifiable'` in ClassRegistry).\n */\nexport class AnonymousNotifiable implements Notifiable {\n routes: Record<string, unknown> = {}\n\n /** Adds a route; chains, so one on-demand notifiable can go to several channels. */\n route(channel: string, route: unknown): this {\n this.routes[channel] = route\n return this\n }\n\n routeNotificationFor(channel: string): unknown {\n return this.routes[channel]\n }\n\n async notify(notification: Notification): Promise<void> {\n await resolveDispatcher().send(this, notification)\n }\n\n async notifyNow(notification: Notification, channels?: string[]): Promise<void> {\n await resolveDispatcher().sendNow(this, notification, channels)\n }\n}\n","import { NotificationDispatcher as NotificationDispatcherToken, type Job, type Notifiable, type Notification } from '@orieljs/contracts'\nimport { inject } from '@orieljs/container'\nimport { SHOULD_QUEUE } from '../symbols'\n\n/** The ShouldQueue options copied from the notification onto the wrapper job. */\nconst QUEUE_OPTIONS = [\n 'connection',\n 'queue',\n 'delay',\n 'tries',\n 'backoff',\n 'timeout',\n 'failOnTimeout',\n 'deleteWhenMissingModels',\n] as const\n\n/** The job hooks Queue reads off a job instance, when the wrapped notification defines them. */\ninterface JobHooks {\n failed?: (error: unknown) => unknown\n retryUntil?: () => unknown\n middleware?: unknown[] | (() => unknown[])\n}\n\n/**\n * Copies the notification's own ShouldQueue fields onto the wrapper job (when set) — same reasoning as Mail's\n * SendQueuedMailable. Uses `declare` fields on the class (no runtime auto-initialization to `undefined`), so a\n * field is a genuinely own property only when the notification actually set it.\n */\nfunction copyShouldQueueFields(target: Record<PropertyKey, unknown>, source: object): void {\n const fields = source as Record<string, unknown>\n for (const option of QUEUE_OPTIONS) {\n if (fields[option] !== undefined) target[option] = fields[option]\n }\n}\n\n/**\n * Dispatched by Dispatcher.send() when the notification is queueable. Runs on the worker: calls sendNow()\n * directly (never send()), so it can't re-detect itself as queueable and loop.\n *\n * Carries `SHOULD_QUEUE` on its own prototype, per the Queue/Bus protocol, so `BusDispatcher.dispatch()` — which\n * re-decides queued-or-now on whatever job it's handed — actually enqueues it instead of running it inline; the\n * notification's own queueability (checked by Dispatcher, above) only decides whether to wrap it at all. Like\n * Laravel's SendQueuedNotifications, it forwards failed(), retryUntil(), middleware() and displayName() to the\n * notification.\n */\nexport class SendQueuedNotifications implements Job {\n declare connection?: string\n declare queue?: string\n declare delay?: number\n declare tries?: number\n declare backoff?: number | number[]\n declare timeout?: number\n declare failOnTimeout?: boolean\n declare deleteWhenMissingModels?: boolean\n\n constructor(\n readonly notifiables: Notifiable[],\n readonly notification: Notification,\n readonly channels?: string[],\n ) {\n copyShouldQueueFields(this as unknown as Record<PropertyKey, unknown>, notification)\n }\n\n async handle(): Promise<void> {\n await inject(NotificationDispatcherToken).sendNow(this.notifiables, this.notification, this.channels)\n }\n\n /** Called by Queue after the final failed attempt. */\n async failed(error: unknown): Promise<void> {\n const hooks = this.notification as unknown as JobHooks\n if (typeof hooks.failed === 'function') await hooks.failed.call(this.notification, error)\n }\n\n /** `failed_jobs` and `queue:failed` show the notification's class, not the wrapper's. */\n displayName(): string {\n return this.notification.constructor.name\n }\n\n retryUntil(): unknown {\n const hooks = this.notification as unknown as JobHooks\n return typeof hooks.retryUntil === 'function' ? hooks.retryUntil.call(this.notification) : undefined\n }\n\n middleware(): unknown[] {\n const declared = (this.notification as unknown as JobHooks).middleware\n return (typeof declared === 'function' ? declared.call(this.notification) : declared) ?? []\n }\n}\n;(SendQueuedNotifications.prototype as unknown as Record<PropertyKey, unknown>)[SHOULD_QUEUE] = true\n","import {\n NotificationDispatcher as NotificationDispatcherToken,\n type Notifiable,\n type Notification as NotificationContract,\n type NotificationChannel,\n type NotificationDispatcher,\n} from '@orieljs/contracts'\nimport { facade } from '@orieljs/support'\nimport { toNotifiableList } from './Dispatcher'\nimport { resolveDispatcher } from './Notifiable'\n\n/**\n * Mirrors Laravel's Illuminate\\Notifications\\Notification: override via(), and whichever toXxx() the channels\n * need.\n *\n * The statics are the `Notification` facade, so one export serves both `class InvoicePaid extends Notification`\n * and `Notification.send(users, new InvoicePaid())`.\n */\nexport abstract class Notification implements NotificationContract {\n id?: string\n abstract via(notifiable: Notifiable): string[]\n\n /** Queues it when the notification is queueable, otherwise sends now. Accepts one notifiable, an array or any iterable. */\n static send(notifiables: Notifiable | Iterable<Notifiable>, notification: NotificationContract): Promise<void> {\n return resolveDispatcher().send(toNotifiableList(notifiables), notification)\n }\n\n static sendNow(\n notifiables: Notifiable | Iterable<Notifiable>,\n notification: NotificationContract,\n channels?: string[],\n ): Promise<void> {\n return resolveDispatcher().sendNow(toNotifiableList(notifiables), notification, channels)\n }\n\n /** On-demand: `Notification.route('mail', 'a@b.c').notify(new InvoicePaid())`. */\n static route(channel: string, route: unknown): Notifiable & { notify(notification: NotificationContract): Promise<void> } {\n return resolveDispatcher().route(channel, route)\n }\n\n static extend(channel: string, factory: () => NotificationChannel): void {\n resolveDispatcher().extend(channel, factory)\n }\n\n /** Replace the dispatcher in the current container (what a NotificationFake uses). */\n static swap(fake: NotificationDispatcher): void {\n facade<NotificationDispatcher>(NotificationDispatcherToken).swap(fake)\n }\n}\n","import type { NotificationDispatcher } from '@orieljs/contracts'\nimport { NotificationDispatcher as NotificationDispatcherToken } from '@orieljs/contracts'\nimport { facade } from '@orieljs/support'\n\n/**\n * The plain facade over NotificationDispatcher. App code normally uses the `Notification` base class's statics\n * instead (one `Notification` export is both the base class and the facade); this stays exported for code that\n * wants the contract-typed proxy (getFacadeRoot(), swap()).\n */\nexport const NotificationFacade = facade<NotificationDispatcher>(NotificationDispatcherToken)\n","import { ClassRegistry as ClassRegistryToken, NotificationDispatcher as NotificationDispatcherToken } from '@orieljs/contracts'\nimport { ServiceProvider } from '@orieljs/support'\nimport { AnonymousNotifiable } from './AnonymousNotifiable'\nimport { DatabaseNotificationChannel } from './channels/DatabaseNotificationChannel'\nimport { MailNotificationChannel } from './channels/MailNotificationChannel'\nimport { Dispatcher } from './Dispatcher'\nimport { SendQueuedNotifications } from './Jobs/SendQueuedNotifications'\n\nexport class NotificationsServiceProvider extends ServiceProvider {\n override register(): void {\n this.app.singleton(NotificationDispatcherToken, (container) => new Dispatcher(container))\n // Namespaced names, registered in register() (not boot()) — the Queue/Bus protocol rule for wrapper classes.\n // ClassRegistry is safe to use here: Application's own constructor binds it before any provider registers.\n const registry = this.app.make(ClassRegistryToken)\n registry.register(SendQueuedNotifications, 'Notifications.SendQueuedNotifications')\n registry.register(AnonymousNotifiable, 'Notifications.AnonymousNotifiable')\n }\n\n override boot(): void {\n const dispatcher = this.app.make(NotificationDispatcherToken)\n dispatcher.extend('mail', () => new MailNotificationChannel())\n dispatcher.extend('database', () => new DatabaseNotificationChannel())\n }\n}\n","import type { Class, Container, OrielError, Pipe, PipeClosure, PipeNext, Pipeline } from '@orieljs/contracts'\nimport { currentContainer } from '@orieljs/container'\n\n/** Turns a string pipe ('throttle:60,1' → name 'throttle', parameters ['60', '1']) into a class, closure or object. */\nexport type StringPipeResolver<T> = (name: string, parameters: string[]) => Class<object> | PipeClosure<T> | object\n\n/** Thrown for pipeline setup/resolution failures (unresolvable string pipes, pipes missing their `via` method). */\nexport class PipelineError extends Error implements OrielError {\n readonly kind = 'Server' as const\n readonly status = 500\n override readonly name = 'PipelineError'\n}\n\n// Duplicated in Routing's dispatch.ts on purpose: Http, Routing and Pipeline may not import each other.\nconst isClass = (value: unknown): value is Class<object> =>\n typeof value === 'function' && /^class[\\s{]/.test(Function.prototype.toString.call(value))\n\n/** 'name:a,b' → ['name', ['a', 'b']] (Laravel's parsePipeString). */\nfunction parsePipeString(pipe: string): [string, string[]] {\n const index = pipe.indexOf(':')\n if (index === -1) return [pipe, []]\n return [pipe.slice(0, index), pipe.slice(index + 1).split(',')]\n}\n\n/** Laravel's Illuminate\\Pipeline\\Pipeline. */\nexport class BasePipeline<T = unknown> implements Pipeline<T> {\n #passable: T | undefined\n #pipes: Array<Pipe<T>> = []\n #method = 'handle'\n #resolveString: StringPipeResolver<T> | undefined\n\n constructor(\n private readonly container?: Container,\n resolveString?: StringPipeResolver<T>,\n ) {\n this.#resolveString = resolveString\n }\n\n send(passable: T): this {\n this.#passable = passable\n return this\n }\n\n through(pipes: ReadonlyArray<Pipe<T>>): this {\n this.#pipes = [...pipes]\n return this\n }\n\n pipe(...pipes: Array<Pipe<T>>): this {\n this.#pipes.push(...pipes)\n return this\n }\n\n via(method: string): this {\n this.#method = method\n return this\n }\n\n resolveStringsUsing(resolver: StringPipeResolver<T>): this {\n this.#resolveString = resolver\n return this\n }\n\n async then<R>(destination: (passable: T) => R | Promise<R>): Promise<R> {\n const core: PipeNext<T> = async (passable) => destination(passable)\n const stack = this.#pipes.reduceRight<PipeNext<T>>(\n (next, pipe) => async (passable) => this.#carry(pipe, passable, next),\n core,\n )\n return (await stack(this.#passable as T)) as R\n }\n\n thenReturn(): Promise<T> {\n return this.then((passable) => passable)\n }\n\n #carry(pipe: Pipe<T>, passable: T, next: PipeNext<T>): unknown {\n if (typeof pipe === 'function' && !isClass(pipe)) return (pipe as PipeClosure<T>)(passable, next)\n\n let target: unknown = pipe\n let parameters: string[] = []\n const label = typeof pipe === 'string' ? pipe : pipe.name\n if (typeof pipe === 'string') {\n if (this.#resolveString === undefined) {\n throw new PipelineError(\n `Cannot resolve the pipe [${pipe}]: string pipes need a resolver. ` +\n 'Pass one to new BasePipeline(container, resolver) or call resolveStringsUsing().',\n )\n }\n const [name, pipeParameters] = parsePipeString(pipe)\n parameters = pipeParameters\n target = this.#resolveString(name, parameters)\n if (typeof target === 'function' && !isClass(target)) return (target as PipeClosure<T>)(passable, next)\n }\n\n const instance = isClass(target) ? this.#build(target) : target\n const method = (instance as Record<string, unknown> | null | undefined)?.[this.#method]\n if (typeof method !== 'function') throw new PipelineError(`Pipe [${label}] has no [${this.#method}] method.`)\n return (method as (...args: unknown[]) => unknown).call(instance, passable, next, ...parameters)\n }\n\n /** Class pipes come from the current container (the request scope), so their inject() fields see this request. */\n #build(cls: Class<object>): object {\n const container = currentContainer() ?? this.container\n if (container === undefined) throw new PipelineError(`Cannot resolve the pipe [${cls.name}]: no container is available.`)\n return container.make(cls)\n }\n}\n","import type { Container, Pipeline, PipelineFactory } from '@orieljs/contracts'\nimport { BasePipeline } from './BasePipeline'\n\n/** Laravel's Pipeline\\Hub: hands out fresh pipelines. */\nexport class Hub implements PipelineFactory {\n constructor(private readonly container?: Container) {}\n\n make<T>(): Pipeline<T> {\n return new BasePipeline<T>(this.container)\n }\n}\n","import { PipelineFactory, type Application, type ServiceProvider } from '@orieljs/contracts'\nimport { Hub } from './Hub'\n\n/**\n * Implements the ServiceProvider contract directly: Pipeline depends only on contracts and container\n * (no @orieljs/support), so it can't extend the support base class.\n */\nexport class PipelineServiceProvider implements ServiceProvider {\n constructor(protected readonly app: Application) {}\n\n register(): void {\n this.app.singleton(PipelineFactory, (container) => new Hub(container))\n }\n}\n","import type { ModelNotFoundError, OrielError } from '@orieljs/contracts'\n\n/** Base for queue errors: internal failures, reported and rendered as a 500 (kind 'Server'). */\nexport class QueueError extends Error implements OrielError {\n readonly kind = 'Server' as const\n readonly status = 500\n override readonly name: string = 'QueueError'\n}\n\n/** A job (or a value inside it) can't be turned into a payload. Thrown at dispatch time. */\nexport class JobSerializationError extends QueueError {\n override readonly name = 'JobSerializationError'\n}\n\nexport class JobClassNotFoundError extends QueueError {\n override readonly name = 'JobClassNotFoundError'\n constructor(readonly className: string) {\n super(\n `Job class [${className}] is not registered in the ClassRegistry. Register it in a service provider ` +\n `(app.make(ClassRegistry).register(${className})), or put it in app/Jobs so queue:work discovers it.`,\n )\n }\n}\n\n/** A model stored in a payload no longer exists. Implements the ModelNotFoundError contract. */\nexport class MissingModelError extends Error implements ModelNotFoundError {\n readonly kind = 'ModelNotFound' as const\n readonly status = 404\n override readonly name = 'MissingModelError'\n constructor(\n readonly model: string,\n readonly ids: unknown[],\n ) {\n super(`No query results for model [${model}] ${ids.join(', ')}`)\n }\n}\n\nexport class MaxAttemptsExceededError extends QueueError {\n override readonly name = 'MaxAttemptsExceededError'\n constructor(readonly job: string) {\n super(`${job} has been attempted too many times.`)\n }\n}\n\nexport class TimeoutExceededError extends QueueError {\n override readonly name = 'TimeoutExceededError'\n constructor(readonly job: string) {\n super(`${job} has timed out.`)\n }\n}\n\n/** Used when fail() is called without an error. */\nexport class ManuallyFailedError extends QueueError {\n override readonly name = 'ManuallyFailedError'\n constructor() {\n super('The job was manually marked as failed.')\n }\n}\n\nexport class UnknownQueueConnectionError extends QueueError {\n override readonly name = 'UnknownQueueConnectionError'\n constructor(readonly connection: string) {\n super(`The [${connection}] queue connection has not been configured.`)\n }\n}\n\nexport class UnknownQueueDriverError extends QueueError {\n override readonly name = 'UnknownQueueDriverError'\n constructor(readonly driver: string) {\n super(`No connector for [${driver}].`)\n }\n}\n","import type { Job } from '@orieljs/contracts'\n\n/**\n * Symbol.for keys shared with @orieljs/bus (which declares the same keys; the two packages never import each other).\n * Symbol-keyed properties are never serialized into a payload's data.\n */\n\n/** The running QueueJob, set on the restored job instance by CallQueuedHandler. */\nexport const QUEUE_JOB = Symbol.for('oriel:queue.job')\n/** A ChainSpec, set on the first job of a chain by Bus. createPayload() turns it into payload.chain & co. */\nexport const CHAIN = Symbol.for('oriel:queue.chain')\n/** A UniqueLockSpec, set by Bus after acquiring a unique-job lock. createPayload() copies it to payload.uniqueLock. */\nexport const UNIQUE_LOCK = Symbol.for('oriel:queue.uniqueLock')\n/** Set on a batch's then/catch/finally callback job when it's dispatched. createPayload() turns it into\n * payload.batchCallback, so the callback keeps its batchId without being counted as one of the batch's jobs. */\nexport const BATCH_CALLBACK = Symbol.for('oriel:queue.batchCallback')\n\nexport interface ChainSpec {\n jobs: Job[]\n connection?: string\n queue?: string\n catch: Job[]\n}\n\nexport interface UniqueLockSpec {\n key: string\n /** Cache store name (undefined = the default store). */\n store?: string\n untilProcessing: boolean\n}\n\n/** Sets a symbol-keyed property on any object. */\nexport function setSymbolValue(target: object, key: symbol, value: unknown): void {\n ;(target as Record<symbol, unknown>)[key] = value\n}\n\n/** Reads a symbol-keyed property from any object. */\nexport function symbolValue<T>(target: object, key: symbol): T | undefined {\n return (target as Record<symbol, unknown>)[key] as T | undefined\n}\n","import { Buffer } from 'node:buffer'\nimport type { Class, ClassRegistry, ModelInstance, ModelStatic } from '@orieljs/contracts'\nimport { JobClassNotFoundError, JobSerializationError, MissingModelError } from './errors'\n\n/** JSON-safe encoded value. Tagged objects carry `__oriel`. */\nexport type Encoded = null | boolean | number | string | Encoded[] | { [key: string]: Encoded }\n\nconst TAG = '__oriel'\n\n/** Database's Model has a static withoutGlobalScopes() (not on the ModelStatic contract), hence the structural check. */\ninterface ScopedModelStatic {\n withoutGlobalScopes?(): { find(id: unknown): Promise<unknown> }\n}\n\n/** Structural model check: 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\n/**\n * The registry name of a class, registering it under its own name the first time. A name collision (two different\n * classes sharing `constructor.name`) is reported as a JobSerializationError naming the class, so the caller can\n * register it explicitly under a namespaced name.\n */\nexport function classNameOf(registry: ClassRegistry, cls: Class<unknown>): string {\n const existing = registry.nameOf(cls)\n if (existing !== undefined) return existing\n try {\n return registry.register(cls)\n } catch (error) {\n const name = (cls as { name?: string }).name || 'AnonymousClass'\n throw new JobSerializationError(\n `Cannot register [${name}] in the ClassRegistry: another class is already registered under that name. ` +\n `Register this one explicitly under a namespaced name, e.g. ` +\n `app.make(ClassRegistry).register(${name}, 'Mail.${name}').`,\n { cause: error },\n )\n }\n}\n\nexport function resolveClass<T = unknown>(registry: ClassRegistry, name: string): Class<T> {\n if (!registry.has(name)) throw new JobClassNotFoundError(name)\n return registry.resolve<T>(name)\n}\n\nfunction isPlainObject(value: object): boolean {\n const proto: unknown = Object.getPrototypeOf(value)\n return proto === Object.prototype || proto === null\n}\n\n/** Own enumerable string-keyed fields, encoded. `undefined` fields are dropped (JSON would drop them anyway). */\nexport function serializeFields(target: object, registry: ClassRegistry, path: string, seen: Set<object> = new Set()): Record<string, Encoded> {\n const out: Record<string, Encoded> = {}\n for (const [key, field] of Object.entries(target)) {\n const encoded = serializeValue(field, registry, `${path}.${key}`, seen)\n if (encoded !== undefined) out[key] = encoded\n }\n return out\n}\n\n/**\n * Encodes a value for a payload. Models become `{ __oriel: 'model', class, key }`; other class instances keep their\n * class name and fields; Date, Map, Set and byte arrays (any ArrayBuffer view, as base64) are tagged. Functions,\n * symbols, bigints, unsaved models and cycles throw.\n */\nexport function serializeValue(value: unknown, registry: ClassRegistry, path = 'data', seen: Set<object> = new Set()): Encoded | undefined {\n switch (typeof value) {\n case 'undefined':\n return undefined\n case 'string':\n case 'number':\n case 'boolean':\n return value\n case 'bigint':\n case 'symbol':\n case 'function':\n throw new JobSerializationError(`Cannot serialize [${path}]: a ${typeof value} can't be queued. Store plain data instead.`)\n }\n if (value === null) return null\n const object = value as object\n if (seen.has(object)) throw new JobSerializationError(`Cannot serialize [${path}]: it contains a circular reference.`)\n seen.add(object)\n try {\n if (object instanceof Date) return { [TAG]: 'date', value: object.toISOString() }\n if (ArrayBuffer.isView(object)) {\n return { [TAG]: 'bytes', value: Buffer.from(object.buffer, object.byteOffset, object.byteLength).toString('base64') }\n }\n if (Array.isArray(object)) return object.map((item, i) => serializeValue(item, registry, `${path}[${i}]`, seen) ?? null)\n if (object instanceof Map) {\n return {\n [TAG]: 'map',\n entries: [...object.entries()].map(([k, v], i) => [\n serializeValue(k, registry, `${path}<key ${i}>`, seen) ?? null,\n serializeValue(v, registry, `${path}<value ${i}>`, seen) ?? null,\n ]),\n }\n }\n if (object instanceof Set) {\n return { [TAG]: 'set', values: [...object].map((v, i) => serializeValue(v, registry, `${path}<${i}>`, seen) ?? null) }\n }\n if (isModel(object)) {\n const name = classNameOf(registry, object.constructor as Class<unknown>)\n if (!object.exists) {\n throw new JobSerializationError(`Cannot serialize [${path}]: the [${name}] model hasn't been saved, so it has no key to store.`)\n }\n return { [TAG]: 'model', class: name, key: serializeValue(object.getKey(), registry, `${path}.key`, seen) ?? null }\n }\n if (isPlainObject(object)) {\n const fields = serializeFields(object, registry, path, seen)\n return Object.hasOwn(fields, TAG) ? { [TAG]: 'object', value: fields } : fields\n }\n const name = classNameOf(registry, object.constructor as Class<unknown>)\n return { [TAG]: 'instance', class: name, data: serializeFields(object, registry, path, seen) }\n } finally {\n seen.delete(object)\n }\n}\n\n/** Restores fields onto a fresh object created from `prototype` (the constructor is never called). */\nexport async function restoreInstance<T>(prototype: object, fields: Record<string, Encoded>, registry: ClassRegistry): Promise<T> {\n const target = Object.create(prototype) as Record<string, unknown>\n for (const [key, value] of Object.entries(await restoreFields(fields, registry))) {\n Object.defineProperty(target, key, { value, enumerable: true, writable: true, configurable: true })\n }\n return target as T\n}\n\nasync function restoreFields(fields: Record<string, Encoded>, registry: ClassRegistry): Promise<Record<string, unknown>> {\n const out: Record<string, unknown> = {}\n for (const [key, field] of Object.entries(fields)) {\n // JSON.parse makes `__proto__` an own key; assigning it would swap the prototype. Define it as plain data instead.\n Object.defineProperty(out, key, { value: await restoreValue(field, registry), enumerable: true, writable: true, configurable: true })\n }\n return out\n}\n\n/**\n * The inverse of serializeValue(). Byte arrays come back as Uint8Array. Models are re-fetched by key without global\n * scopes (Laravel's newQueryForRestoration), so a soft-deleted model still reaches the job; a missing one throws\n * MissingModelError.\n */\nexport async function restoreValue(value: Encoded, registry: ClassRegistry): Promise<unknown> {\n if (value === null || typeof value !== 'object') return value\n if (Array.isArray(value)) {\n const out: unknown[] = []\n for (const item of value) out.push(await restoreValue(item, registry))\n return out\n }\n switch (value[TAG]) {\n case undefined:\n return restoreFields(value, registry)\n case 'object':\n return restoreFields(value.value as Record<string, Encoded>, registry)\n case 'date':\n return new Date(value.value as string)\n case 'bytes':\n return new Uint8Array(Buffer.from(value.value as string, 'base64'))\n case 'map': {\n const map = new Map<unknown, unknown>()\n for (const [k, v] of value.entries as Array<[Encoded, Encoded]>) map.set(await restoreValue(k, registry), await restoreValue(v, registry))\n return map\n }\n case 'set': {\n const set = new Set<unknown>()\n for (const v of value.values as Encoded[]) set.add(await restoreValue(v, registry))\n return set\n }\n case 'model': {\n const name = value.class as string\n const model = resolveClass(registry, name) as unknown as ModelStatic & ScopedModelStatic\n const key = await restoreValue(value.key as Encoded, registry)\n const query = typeof model.withoutGlobalScopes === 'function' ? model.withoutGlobalScopes() : model\n const found = await query.find(key)\n if (found === undefined || found === null) throw new MissingModelError(name, [key])\n return found\n }\n case 'instance': {\n const cls = resolveClass(registry, value.class as string)\n return restoreInstance(cls.prototype as object, value.data as Record<string, Encoded>, registry)\n }\n default:\n throw new JobSerializationError(`Unknown encoded value type [${String(value[TAG])}] in a queue payload.`)\n }\n}\n","import { randomUUID } from 'node:crypto'\nimport type { Class, ClassRegistry, Job, QueuePayload } from '@orieljs/contracts'\nimport { JobSerializationError } from './errors'\nimport { classNameOf, resolveClass, restoreInstance, serializeFields, type Encoded } from './serialization'\nimport { BATCH_CALLBACK, CHAIN, symbolValue, UNIQUE_LOCK, type ChainSpec, type UniqueLockSpec } from './symbols'\n\n/**\n * The payload Oriel stores: the QueuePayload contract (which carries retryUntil and failOnTimeout) plus the\n * missing-model flag and the chain / unique-lock bookkeeping. `data` holds the job's encoded own fields.\n */\nexport interface QueueJobPayload extends QueuePayload {\n data: Record<string, Encoded>\n deleteWhenMissingModels?: boolean\n chain?: QueueJobPayload[]\n chainConnection?: string\n chainQueue?: string\n chainCatch?: QueueJobPayload[]\n uniqueLock?: UniqueLockSpec\n /** A batch's then/catch/finally callback: it carries the batchId but isn't one of the batch's jobs. */\n batchCallback?: boolean\n}\n\n/** The job members the queue reads (all optional; see the ShouldQueue contract). */\ninterface JobOptions {\n tries?: unknown\n backoff?: unknown\n timeout?: unknown\n failOnTimeout?: unknown\n deleteWhenMissingModels?: unknown\n batchId?: unknown\n retryUntil?: unknown\n displayName?: unknown\n}\n\nexport function normalizeBackoff(backoff: unknown): number[] | undefined {\n if (typeof backoff === 'number') return [backoff]\n if (typeof backoff === 'string' && backoff !== '') return backoff.split(',').map((part) => Number(part.trim()))\n if (Array.isArray(backoff)) return backoff.map(Number)\n return undefined\n}\n\nfunction toUnixMs(value: unknown): number | undefined {\n if (value instanceof Date) return value.getTime()\n if (typeof value === 'number') return value\n return undefined\n}\n\n/** `value` if it's a string, else `undefined`. Internal; later Queue/Bus tasks import this to read string options. */\nexport function optionalString(value: unknown): string | undefined {\n return typeof value === 'string' ? value : undefined\n}\n\nconst call = (target: object, value: unknown): unknown => (typeof value === 'function' ? (value as () => unknown).call(target) : value)\n\n/** Builds the payload for a job instance. Registers the job's class (and nested classes) in the ClassRegistry. */\nexport function createPayload(job: Job, registry: ClassRegistry): QueueJobPayload {\n const cls = job.constructor as Class<unknown> | undefined\n if (typeof job !== 'object' || job === null || cls === undefined || cls === Object) {\n throw new JobSerializationError('Only class instances with a handle() method can be queued, not plain objects.')\n }\n const name = classNameOf(registry, cls)\n const options = job as JobOptions\n const displayName = call(job, options.displayName)\n\n const payload: QueueJobPayload = {\n uuid: randomUUID(),\n job: name,\n displayName: optionalString(displayName) || name,\n data: serializeFields(job, registry, name),\n attempts: 0,\n pushedAt: Date.now(),\n }\n const tries = call(job, options.tries)\n if (typeof tries === 'number') payload.maxTries = tries\n const backoff = normalizeBackoff(call(job, options.backoff))\n if (backoff) payload.backoff = backoff\n if (typeof options.timeout === 'number') payload.timeout = options.timeout\n const retryUntil = typeof options.retryUntil === 'function' ? toUnixMs(call(job, options.retryUntil)) : undefined\n if (retryUntil !== undefined) payload.retryUntil = retryUntil\n if (options.failOnTimeout === true) payload.failOnTimeout = true\n if (options.deleteWhenMissingModels === true || (cls as unknown as JobOptions).deleteWhenMissingModels === true) {\n payload.deleteWhenMissingModels = true\n }\n const batchId = optionalString(options.batchId)\n if (batchId !== undefined) payload.batchId = batchId\n if (symbolValue<boolean>(job, BATCH_CALLBACK) === true) payload.batchCallback = true\n\n const chain = symbolValue<ChainSpec>(job, CHAIN)\n if (chain && chain.jobs.length > 0) payload.chain = chain.jobs.map((next) => createPayload(next, registry))\n if (chain?.connection !== undefined) payload.chainConnection = chain.connection\n if (chain?.queue !== undefined) payload.chainQueue = chain.queue\n if (chain && chain.catch.length > 0) payload.chainCatch = chain.catch.map((callback) => createPayload(callback, registry))\n\n const uniqueLock = symbolValue<UniqueLockSpec>(job, UNIQUE_LOCK)\n if (uniqueLock) payload.uniqueLock = uniqueLock\n return payload\n}\n\n/** Restores the job instance from a payload, without calling its constructor. Models are re-fetched. */\nexport async function restoreJob<T extends Job = Job>(payload: QueuePayload, registry: ClassRegistry): Promise<T> {\n const cls = resolveClass(registry, payload.job)\n return restoreInstance<T>(cls.prototype as object, payload.data as Record<string, Encoded>, registry)\n}\n\n/** JSON with `attempts` as the first key, so the redis Lua scripts can bump it without re-encoding the payload. */\nexport function encodePayload(payload: QueuePayload): string {\n const { attempts, ...rest } = payload\n return JSON.stringify({ attempts, ...rest })\n}\n\nexport function decodePayload(raw: string): QueueJobPayload {\n let decoded: unknown\n try {\n decoded = JSON.parse(raw)\n } catch {\n throw new JobSerializationError('Invalid queue payload: not JSON.')\n }\n const payload = decoded as Partial<QueueJobPayload> | null\n if (!payload || typeof payload.job !== 'string' || typeof payload.uuid !== 'string') {\n throw new JobSerializationError('Invalid queue payload: missing \"job\" or \"uuid\".')\n }\n return { ...payload, attempts: Number(payload.attempts ?? 0), data: payload.data ?? {} } as QueueJobPayload\n}\n","import { FailedJobProvider, type Container, type QueueJob } from '@orieljs/contracts'\nimport type { CallQueuedHandler } from '../CallQueuedHandler'\nimport { ManuallyFailedError } from '../errors'\nimport type { QueueJobPayload } from '../payload'\n\n/** What every queue job needs from its driver. */\nexport interface JobContext {\n /** The container the driver was built with (the application). Used for FailedJobProvider and the handler. */\n container: Container\n handler: CallQueuedHandler\n connectionName: string\n}\n\n/** Laravel's Illuminate\\Queue\\Jobs\\Job: state flags, fire(), fail(), and payload accessors. */\nexport abstract class BaseJob implements QueueJob {\n protected deleted = false\n protected released = false\n protected failedFlag = false\n\n constructor(\n protected readonly context: JobContext,\n protected readonly queue: string,\n ) {}\n\n abstract getJobId(): string\n abstract payload(): QueueJobPayload\n\n attempts(): number {\n return this.payload().attempts\n }\n\n getQueue(): string {\n return this.queue\n }\n\n getConnectionName(): string {\n return this.context.connectionName\n }\n\n uuid(): string {\n return this.payload().uuid\n }\n\n /** The job's display name (its class name unless it defines displayName()). */\n resolveName(): string {\n return this.payload().displayName\n }\n\n maxTries(): number | undefined {\n return this.payload().maxTries\n }\n\n backoff(): number[] | undefined {\n return this.payload().backoff\n }\n\n timeout(): number | undefined {\n return this.payload().timeout\n }\n\n retryUntil(): number | undefined {\n return this.payload().retryUntil\n }\n\n shouldFailOnTimeout(): boolean {\n return this.payload().failOnTimeout === true\n }\n\n async delete(): Promise<void> {\n this.deleted = true\n }\n\n async release(_delaySeconds = 0): Promise<void> {\n this.released = true\n }\n\n isDeleted(): boolean {\n return this.deleted\n }\n\n isReleased(): boolean {\n return this.released\n }\n\n isDeletedOrReleased(): boolean {\n return this.deleted || this.released\n }\n\n hasFailed(): boolean {\n return this.failedFlag\n }\n\n markAsFailed(): void {\n this.failedFlag = true\n }\n\n /** Runs the job through CallQueuedHandler. */\n async fire(): Promise<void> {\n await this.context.handler.call(this)\n }\n\n /**\n * Marks the job as failed, deletes it, runs the handler's failure bookkeeping (unique lock, batch, chain catch,\n * the job's failed() hook) and stores it with the FailedJobProvider. A job that was already deleted is ignored.\n */\n async fail(error?: unknown): Promise<void> {\n this.markAsFailed()\n if (this.deleted) return\n const reason = error ?? new ManuallyFailedError()\n try {\n await this.delete()\n await this.context.handler.failed(this, reason)\n } finally {\n const { container } = this.context\n if (container.bound(FailedJobProvider)) {\n await container.make(FailedJobProvider).log(this.getConnectionName(), this.getQueue(), this.payload(), reason)\n }\n }\n }\n}\n","import type { QueueJobPayload } from '../payload'\nimport { BaseJob, type JobContext } from './BaseJob'\n\n/** The sync driver's job: runs once, in the dispatching process. release() only marks it (nothing to requeue). */\nexport class SyncJob extends BaseJob {\n constructor(\n context: JobContext,\n private readonly raw: QueueJobPayload,\n queue: string,\n ) {\n super(context, queue)\n }\n\n getJobId(): string {\n return this.raw.uuid\n }\n\n payload(): QueueJobPayload {\n return this.raw\n }\n\n override attempts(): number {\n return 1\n }\n}\n","import {\n BatchRepository,\n BusDispatcher,\n CacheManager,\n ClassRegistry,\n QueueManager,\n type Container,\n type Job,\n} from '@orieljs/contracts'\nimport { MissingModelError } from './errors'\nimport type { BaseJob } from './jobs/BaseJob'\nimport { optionalString, restoreJob, type QueueJobPayload } from './payload'\nimport { QUEUE_JOB } from './symbols'\n\ntype Next = (job: Job) => Promise<unknown>\n/** Job middleware: a function or an object with handle(job, next), like Laravel's job middleware classes. */\nexport type JobMiddleware = ((job: Job, next: Next) => unknown) | { handle(job: Job, next: Next): unknown }\n\ninterface WithMiddleware {\n middleware?: (() => JobMiddleware[]) | JobMiddleware[]\n}\n\n/**\n * Laravel's CallQueuedHandler: restores the job from its payload and runs it through its middleware, then does the\n * chain / batch / unique-lock bookkeeping. failed() is the other half, called by BaseJob.fail().\n */\nexport class CallQueuedHandler {\n constructor(private readonly container: Container) {}\n\n async call(job: BaseJob): Promise<void> {\n const payload = job.payload()\n let instance: Job\n try {\n instance = await restoreJob(payload, this.container.make(ClassRegistry))\n } catch (error) {\n if (error instanceof MissingModelError) return this.handleModelNotFound(job, payload, error)\n throw error\n }\n ;(instance as unknown as Record<symbol, unknown>)[QUEUE_JOB] = job\n\n const untilProcessing = payload.uniqueLock?.untilProcessing === true\n if (untilProcessing) await this.releaseUniqueLock(payload)\n\n await this.dispatchThroughMiddleware(instance)\n\n // A job that failed itself (this.fail() in handle()) had its lock released by failed() already.\n if (!job.isReleased() && !job.hasFailed() && !untilProcessing) await this.releaseUniqueLock(payload)\n try {\n if (!job.hasFailed() && !job.isReleased()) {\n await this.dispatchNextJobInChain(payload)\n await this.recordSuccessfulBatchJob(payload)\n }\n } catch (error) {\n // This job succeeded; what threw is the next link or a batch callback (on the sync queue they run inline).\n // Delete the job first, so the caller's fail() doesn't record a success as a failure.\n if (!job.isDeletedOrReleased()) await job.delete()\n throw error\n }\n if (!job.isDeletedOrReleased()) await job.delete()\n }\n\n /** Called by BaseJob.fail() after the job was deleted. */\n async failed(job: BaseJob, error: unknown): Promise<void> {\n const payload = job.payload()\n let instance: Job | undefined\n try {\n instance = await restoreJob(payload, this.container.make(ClassRegistry))\n } catch {\n instance = undefined\n }\n if (payload.uniqueLock?.untilProcessing !== true) await this.releaseUniqueLock(payload)\n if (payload.batchId !== undefined && payload.batchCallback !== true && this.container.bound(BatchRepository)) {\n await this.container.make(BatchRepository).recordFailedJob(payload.batchId, payload.uuid, error)\n }\n for (const callback of payload.chainCatch ?? []) {\n await this.dispatchCallback(await restoreJob(callback, this.container.make(ClassRegistry)))\n }\n if (instance && typeof instance.failed === 'function') await instance.failed(error)\n }\n\n /** Dispatches a callback job (chain catch, batch then/catch/finally) through the Bus, or runs it inline. */\n async dispatchCallback(callback: Job): Promise<void> {\n if (this.container.bound(BusDispatcher)) await this.container.make(BusDispatcher).dispatch(callback)\n else await callback.handle()\n }\n\n private async handleModelNotFound(job: BaseJob, payload: QueueJobPayload, error: MissingModelError): Promise<void> {\n if (payload.deleteWhenMissingModels === true) return job.delete()\n return job.fail(error)\n }\n\n private async dispatchThroughMiddleware(instance: Job): Promise<void> {\n const declared = (instance as WithMiddleware).middleware\n const middleware = (typeof declared === 'function' ? declared.call(instance) : declared) ?? []\n const run = async (index: number, current: Job): Promise<unknown> => {\n const layer = middleware[index]\n if (layer === undefined) return current.handle()\n const next: Next = (passed) => run(index + 1, passed ?? current)\n return typeof layer === 'function' ? layer(current, next) : layer.handle(current, next)\n }\n await run(0, instance)\n }\n\n private async dispatchNextJobInChain(payload: QueueJobPayload): Promise<void> {\n const [next, ...rest] = payload.chain ?? []\n if (next === undefined) return\n const nextPayload: QueueJobPayload = { ...next, attempts: 0, pushedAt: Date.now() }\n if (rest.length > 0) nextPayload.chain = rest\n else delete nextPayload.chain\n if (payload.chainConnection !== undefined) nextPayload.chainConnection = payload.chainConnection\n if (payload.chainQueue !== undefined) nextPayload.chainQueue = payload.chainQueue\n if (payload.chainCatch !== undefined) nextPayload.chainCatch = payload.chainCatch\n\n // '' counts as unset, as it does in the Dispatcher.\n const connection = optionalString(next.data.connection) || payload.chainConnection || undefined\n const queue = optionalString(next.data.queue) || payload.chainQueue || undefined\n const delay = typeof next.data.delay === 'number' ? next.data.delay : 0\n await this.container.make(QueueManager).connection(connection).pushRaw(nextPayload, queue, delay)\n }\n\n private async recordSuccessfulBatchJob(payload: QueueJobPayload): Promise<void> {\n if (payload.batchId === undefined || payload.batchCallback === true || !this.container.bound(BatchRepository)) return\n await this.container.make(BatchRepository).recordSuccessfulJob(payload.batchId, payload.uuid)\n }\n\n private async releaseUniqueLock(payload: QueueJobPayload): Promise<void> {\n const lock = payload.uniqueLock\n if (!lock || !this.container.bound(CacheManager)) return\n const cache = this.container.make(CacheManager)\n const store = lock.store !== undefined ? cache.store(lock.store) : cache\n await store.lock(lock.key).forceRelease()\n }\n}\n","import { CacheManager, type Job, type QueueJob } from '@orieljs/contracts'\nimport { inject } from '@orieljs/container'\nimport { QUEUE_JOB, symbolValue } from '../symbols'\n\n/**\n * Laravel's WithoutOverlapping job middleware: only one job with the same key runs at a time (a cache lock).\n * A job that finds the lock taken is released back onto the queue after `releaseAfter` seconds (default 0), or\n * dropped after dontRelease().\n */\nexport class WithoutOverlapping {\n releaseAfter: number | undefined\n expiresAfter: number\n prefix = 'oriel-queue-overlap:'\n shareKey = false\n\n constructor(\n public key: string | number = '',\n releaseAfter: number | undefined = 0,\n expiresAfter = 0,\n ) {\n this.releaseAfter = releaseAfter\n this.expiresAfter = expiresAfter\n }\n\n releaseAfterSeconds(seconds: number): this {\n this.releaseAfter = seconds\n return this\n }\n\n dontRelease(): this {\n this.releaseAfter = undefined\n return this\n }\n\n /** Lock expiry in seconds, so a crashed worker can't hold the lock forever. 0 (the default) = no expiry. */\n expireAfter(seconds: number): this {\n this.expiresAfter = seconds\n return this\n }\n\n withPrefix(prefix: string): this {\n this.prefix = prefix\n return this\n }\n\n /** Share the lock across job classes that use the same key. */\n shared(): this {\n this.shareKey = true\n return this\n }\n\n getLockKey(job: Job): string {\n return this.shareKey ? `${this.prefix}${this.key}` : `${this.prefix}${job.constructor.name}:${this.key}`\n }\n\n async handle(job: Job, next: (job: Job) => Promise<unknown>): Promise<unknown> {\n const lock = inject(CacheManager).lock(this.getLockKey(job), this.expiresAfter > 0 ? this.expiresAfter : undefined)\n if (await lock.get()) {\n try {\n return await next(job)\n } finally {\n await lock.release()\n }\n }\n if (this.releaseAfter !== undefined) await symbolValue<QueueJob>(job, QUEUE_JOB)?.release(this.releaseAfter)\n return undefined\n }\n}\n","import { randomUUID } from 'node:crypto'\nimport { ClassRegistry, ExceptionHandler, FailedJobProvider, type Container, type Job, type Queue, type QueueJob, type QueuePayload } from '@orieljs/contracts'\nimport { CallQueuedHandler } from '../CallQueuedHandler'\nimport type { JobContext } from '../jobs/BaseJob'\nimport { createPayload, optionalString, type QueueJobPayload } from '../payload'\n\n/** Shared driver behaviour (Laravel's Illuminate\\Queue\\Queue): payload creation, queue names, the job context. */\nexport abstract class QueueBase implements Queue {\n protected connectionName = 'default'\n protected readonly handler: CallQueuedHandler\n\n constructor(\n protected readonly container: Container,\n protected readonly defaultQueue = 'default',\n ) {\n this.handler = new CallQueuedHandler(container)\n }\n\n setConnectionName(name: string): this {\n this.connectionName = name\n return this\n }\n\n getConnectionName(): string {\n return this.connectionName\n }\n\n /** The queue name to use: the given one, else the connection's default. */\n getQueue(queue?: string): string {\n return optionalString(queue) || this.defaultQueue\n }\n\n createPayload(job: Job): QueueJobPayload {\n return createPayload(job, this.container.make(ClassRegistry))\n }\n\n push(job: Job, queue?: string): Promise<string> {\n return this.pushRaw(this.createPayload(job), queue ?? (optionalString(job.queue) || undefined))\n }\n\n later(delaySeconds: number, job: Job, queue?: string): Promise<string> {\n return this.pushRaw(this.createPayload(job), queue ?? (optionalString(job.queue) || undefined), delaySeconds)\n }\n\n abstract pushRaw(payload: QueuePayload, queue?: string, delaySeconds?: number): Promise<string>\n abstract pop(queue?: string): Promise<QueueJob | undefined>\n abstract size(queue?: string): Promise<number>\n abstract clear(queue?: string): Promise<number>\n\n /** Closes network connections (redis). No-op by default. */\n async disconnect(): Promise<void> {}\n\n /**\n * A row whose payload can't be decoded can never run: record it as failed (with a minimal payload holding the raw\n * text) and report the original error. If the failed-job provider throws, that error propagates so the caller\n * keeps the row (it is retried after retry_after) instead of losing the payload. With no provider bound the row\n * is only reported, like Laravel. A reporter failure never blocks the move.\n */\n protected async failCorrupt(queue: string, raw: string, error: unknown): Promise<void> {\n const payload = { uuid: randomUUID(), displayName: 'CorruptPayload', job: 'CorruptPayload', data: { raw } } as unknown as QueuePayload\n try {\n if (this.container.bound(FailedJobProvider)) await this.container.make(FailedJobProvider).log(this.connectionName, queue, payload, error)\n } finally {\n try {\n if (this.container.bound(ExceptionHandler)) await this.container.make(ExceptionHandler).report(error)\n } catch (reportingError) {\n console.error(reportingError)\n }\n }\n }\n\n protected jobContext(): JobContext {\n return { container: this.container, handler: this.handler, connectionName: this.connectionName }\n }\n\n /** Unix seconds, like Laravel's availableAt()/currentTime(). */\n protected currentTime(): number {\n return Math.floor(Date.now() / 1000)\n }\n}\n","import type { QueueJob, QueuePayload } from '@orieljs/contracts'\nimport { SyncJob } from '../jobs/SyncJob'\nimport type { QueueJobPayload } from '../payload'\nimport { QueueBase } from './QueueBase'\n\n/**\n * Runs jobs immediately, in the dispatching process (delays are ignored). The payload is still built and the job\n * restored from it, so sync behaves like a real worker. A failure is stored with the FailedJobProvider and rethrown.\n */\nexport class SyncQueue extends QueueBase {\n async pushRaw(payload: QueuePayload, queue?: string): Promise<string> {\n const job = new SyncJob(this.jobContext(), payload as QueueJobPayload, this.getQueue(queue))\n try {\n await job.fire()\n } catch (error) {\n if (!job.hasFailed()) await job.fail(error)\n throw error\n }\n return payload.uuid\n }\n\n async pop(): Promise<QueueJob | undefined> {\n return undefined\n }\n\n async size(): Promise<number> {\n return 0\n }\n\n async clear(): Promise<number> {\n return 0\n }\n}\n","import type { Job, QueueJob } from '@orieljs/contracts'\nimport { QueueBase } from './QueueBase'\n\n/** Discards every job (Laravel's `null` driver). */\nexport class NullQueue extends QueueBase {\n override async push(_job: Job): Promise<string> {\n return ''\n }\n\n override async later(_delaySeconds: number, _job: Job): Promise<string> {\n return ''\n }\n\n async pushRaw(): Promise<string> {\n return ''\n }\n\n async pop(): Promise<QueueJob | undefined> {\n return undefined\n }\n\n async size(): Promise<number> {\n return 0\n }\n\n async clear(): Promise<number> {\n return 0\n }\n}\n","import {\n ConfigRepository,\n DatabaseManager,\n type Container,\n type Job,\n type Queue,\n type QueueJob,\n type QueueManager as QueueManagerContract,\n type QueuePayload,\n} from '@orieljs/contracts'\nimport { UnknownQueueConnectionError, UnknownQueueDriverError } from './errors'\nimport { optionalString } from './payload'\nimport { DatabaseQueue } from './queues/DatabaseQueue'\nimport { NullQueue } from './queues/NullQueue'\nimport { makeRedisClient, RedisQueue, resolveRedisConfig, type RedisConnectionConfig } from './queues/RedisQueue'\nimport { SyncQueue } from './queues/SyncQueue'\n\nexport type ConnectionConfig = Record<string, unknown>\ntype Driver = (config: ConnectionConfig, name: string) => Queue\n\nconst number = (value: unknown, fallback: number): number => (typeof value === 'number' && Number.isFinite(value) ? value : fallback)\n\ninterface Named {\n setConnectionName?(name: string): unknown\n disconnect?(): Promise<void>\n}\n\n/** Laravel's QueueManager: builds connections from `queue.connections`, caches them, delegates to the default. */\nexport class QueueManager implements QueueManagerContract {\n private readonly connections = new Map<string, Queue>()\n private readonly drivers = new Map<string, Driver>()\n\n constructor(private readonly container: Container) {\n this.drivers.set('sync', (config) => new SyncQueue(container, optionalString(config.queue) || 'default'))\n this.drivers.set('null', (config) => new NullQueue(container, optionalString(config.queue) || 'default'))\n this.drivers.set(\n 'database',\n (config) =>\n new DatabaseQueue(container, () => container.make(DatabaseManager).connection(optionalString(config.connection) || undefined), {\n table: optionalString(config.table) || 'jobs',\n queue: optionalString(config.queue) || 'default',\n retryAfter: number(config.retry_after, 90),\n }),\n )\n this.drivers.set(\n 'redis',\n (config) =>\n new RedisQueue(container, () => makeRedisClient(resolveRedisConfig(config as RedisConnectionConfig, this.config())), {\n queue: optionalString(config.queue) || 'default',\n retryAfter: number(config.retry_after, 90),\n }),\n )\n }\n\n connection(name?: string): Queue {\n const connectionName = name ?? this.getDefaultDriver()\n let queue = this.connections.get(connectionName)\n if (!queue) {\n queue = this.resolve(connectionName)\n this.connections.set(connectionName, queue)\n }\n return queue\n }\n\n /**\n * Registers a custom driver (`queue.connections.<name>.driver`). The driver's `pop()` must return instances of the\n * exported `BaseJob` subclasses (or subclasses of `BaseJob`): the Worker relies on their methods.\n */\n extend(driver: string, factory: (config: ConnectionConfig) => Queue): void {\n this.drivers.set(driver, factory)\n }\n\n getDefaultDriver(): string {\n return optionalString(this.config().get('queue.default')) || 'sync'\n }\n\n setDefaultDriver(name: string): void {\n this.config().set('queue.default', name)\n }\n\n getConnectionConfig(name: string): ConnectionConfig | undefined {\n return this.config().get<ConnectionConfig | undefined>(`queue.connections.${name}`)\n }\n\n /** Whether the connection has been built already. */\n connected(name?: string): boolean {\n return this.connections.has(name ?? this.getDefaultDriver())\n }\n\n /** Disconnects and forgets one connection (default: the default one). */\n async disconnect(name?: string): Promise<void> {\n const connectionName = name ?? this.getDefaultDriver()\n const queue = this.connections.get(connectionName) as (Queue & Named) | undefined\n this.connections.delete(connectionName)\n await queue?.disconnect?.()\n }\n\n /** Disconnects every built connection. */\n async disconnectAll(): Promise<void> {\n for (const name of [...this.connections.keys()]) await this.disconnect(name)\n }\n\n push(job: Job, queue?: string): Promise<string> {\n return this.connection().push(job, queue)\n }\n\n later(delaySeconds: number, job: Job, queue?: string): Promise<string> {\n return this.connection().later(delaySeconds, job, queue)\n }\n\n pushRaw(payload: QueuePayload, queue?: string, delaySeconds?: number): Promise<string> {\n return this.connection().pushRaw(payload, queue, delaySeconds)\n }\n\n pop(queue?: string): Promise<QueueJob | undefined> {\n return this.connection().pop(queue)\n }\n\n size(queue?: string): Promise<number> {\n return this.connection().size(queue)\n }\n\n clear(queue?: string): Promise<number> {\n return this.connection().clear(queue)\n }\n\n private resolve(name: string): Queue {\n const config = this.getConnectionConfig(name)\n if (!config) throw new UnknownQueueConnectionError(name)\n const driverName = optionalString(config.driver) || ''\n const driver = this.drivers.get(driverName)\n if (!driver) throw new UnknownQueueDriverError(driverName)\n const queue = driver(config, name) as Queue & Named\n queue.setConnectionName?.(name)\n return queue\n }\n\n private config(): ConfigRepository {\n return this.container.make(ConfigRepository)\n }\n}\n","import { decodePayload, type QueueJobPayload } from '../payload'\nimport type { DatabaseQueue } from '../queues/DatabaseQueue'\nimport { BaseJob, type JobContext } from './BaseJob'\n\n/** A row of the `jobs` table (Laravel 11 schema). Times are Unix seconds. */\nexport interface DatabaseJobRecord {\n id: number | string\n queue: string\n payload: string\n attempts: number\n reserved_at: number | null\n available_at: number\n created_at: number\n}\n\n/** A reserved row. attempts() comes from the row, not the payload. */\nexport class DatabaseJob extends BaseJob {\n private readonly decoded: QueueJobPayload\n\n constructor(\n context: JobContext,\n private readonly database: DatabaseQueue,\n private readonly record: DatabaseJobRecord,\n queue: string,\n ) {\n super(context, queue)\n this.decoded = { ...decodePayload(record.payload), attempts: Number(record.attempts) }\n }\n\n getJobId(): string {\n return String(this.record.id)\n }\n\n payload(): QueueJobPayload {\n return this.decoded\n }\n\n override attempts(): number {\n return Number(this.record.attempts)\n }\n\n getJobRecord(): DatabaseJobRecord {\n return this.record\n }\n\n /** Deletes the reserved row and inserts a fresh one, keeping the attempt count (Laravel's deleteAndRelease). */\n override async release(delaySeconds = 0): Promise<void> {\n await super.release(delaySeconds)\n await this.database.deleteAndRelease(this.queue, this, delaySeconds)\n }\n\n override async delete(): Promise<void> {\n await super.delete()\n await this.database.deleteReserved(this.getJobId())\n }\n}\n","import type { Container, DatabaseConnection, QueueJob, QueuePayload } from '@orieljs/contracts'\nimport { DatabaseJob, type DatabaseJobRecord } from '../jobs/DatabaseJob'\nimport { encodePayload } from '../payload'\nimport { QueueBase } from './QueueBase'\n\nexport interface DatabaseQueueOptions {\n table?: string\n queue?: string\n /** Seconds before a reserved job is considered lost and handed out again (Laravel's retry_after, default 90). */\n retryAfter?: number\n}\n\n/** How many times pop() retries when another worker reserved the row it found first. */\nconst RESERVE_ATTEMPTS = 3\n\n/**\n * Laravel's DatabaseQueue on the `jobs` table. Reservation is a `SELECT … FOR UPDATE` plus a conditional UPDATE on\n * the row's attempts and reserved_at, so a row can never be reserved twice, even on SQLite.\n */\nexport class DatabaseQueue extends QueueBase {\n private readonly table: string\n private readonly retryAfter: number\n\n constructor(\n container: Container,\n private readonly database: () => DatabaseConnection,\n options: DatabaseQueueOptions = {},\n ) {\n super(container, options.queue ?? 'default')\n this.table = options.table ?? 'jobs'\n this.retryAfter = options.retryAfter ?? 90\n }\n\n async pushRaw(payload: QueuePayload, queue?: string, delaySeconds = 0): Promise<string> {\n return this.pushToDatabase(this.getQueue(queue), payload, delaySeconds, 0)\n }\n\n async pop(queue?: string): Promise<QueueJob | undefined> {\n const name = this.getQueue(queue)\n let attempt = 0\n while (attempt < RESERVE_ATTEMPTS) {\n const outcome = await this.database().transaction(async (db) => {\n const record = await this.getNextAvailableJob(db, name)\n if (!record) return 'empty' as const\n return (await this.markJobAsReserved(db, record)) ? record : ('taken' as const)\n })\n if (outcome === 'empty') return undefined\n if (outcome === 'taken') {\n attempt++\n continue\n }\n try {\n return new DatabaseJob(this.jobContext(), this, outcome, name)\n } catch (error) {\n // A corrupt row isn't a lost reservation race: record it, remove it, and look at the next row.\n await this.failCorrupt(name, outcome.payload, error)\n await this.deleteReserved(String(outcome.id))\n }\n }\n return undefined\n }\n\n async size(queue?: string): Promise<number> {\n return this.database().table(this.table).where('queue', this.getQueue(queue)).count()\n }\n\n async clear(queue?: string): Promise<number> {\n return this.database().table(this.table).where('queue', this.getQueue(queue)).delete()\n }\n\n async deleteReserved(id: string): Promise<void> {\n await this.database().table(this.table).where('id', this.key(id)).delete()\n }\n\n async deleteAndRelease(queue: string, job: DatabaseJob, delaySeconds: number): Promise<void> {\n await this.database().transaction(async (db) => {\n await db.table(this.table).where('id', this.key(job.getJobId())).delete()\n await this.pushToDatabase(queue, job.payload(), delaySeconds, job.attempts(), db)\n })\n }\n\n private async pushToDatabase(queue: string, payload: QueuePayload, delaySeconds: number, attempts: number, db = this.database()): Promise<string> {\n const now = this.currentTime()\n const id = await db.table(this.table).insertGetId({\n queue,\n payload: encodePayload({ ...payload, attempts: 0 }),\n attempts,\n reserved_at: null,\n available_at: now + Math.max(0, Math.round(delaySeconds)),\n created_at: now,\n })\n return String(id)\n }\n\n /** The oldest available row, or the oldest reservation older than retry_after, whichever has the lower id. */\n private async getNextAvailableJob(db: DatabaseConnection, queue: string): Promise<DatabaseJobRecord | undefined> {\n const now = this.currentTime()\n const available = await db\n .table<DatabaseJobRecord>(this.table)\n .where('queue', queue)\n .whereNull('reserved_at')\n .where('available_at', '<=', now)\n .orderBy('id', 'asc')\n .lockForUpdate()\n .first()\n const expired = await db\n .table<DatabaseJobRecord>(this.table)\n .where('queue', queue)\n .whereNotNull('reserved_at')\n .where('reserved_at', '<=', now - this.retryAfter)\n .orderBy('id', 'asc')\n .lockForUpdate()\n .first()\n if (!available || !expired) return available ?? expired\n return Number(available.id) <= Number(expired.id) ? available : expired\n }\n\n /** Reserves the row only if nobody else changed it since we read it. */\n private async markJobAsReserved(db: DatabaseConnection, record: DatabaseJobRecord): Promise<boolean> {\n const now = this.currentTime()\n const query = db.table(this.table).where('id', record.id).where('attempts', record.attempts)\n if (record.reserved_at === null) query.whereNull('reserved_at')\n else query.where('reserved_at', record.reserved_at)\n const affected = await query.update({ reserved_at: now, attempts: Number(record.attempts) + 1 })\n if (affected === 0) return false\n record.reserved_at = now\n record.attempts = Number(record.attempts) + 1\n return true\n }\n\n /** Job ids are stored as numbers; getJobId() hands them out as strings. */\n private key(id: string): number | string {\n return /^\\d+$/.test(id) ? Number(id) : id\n }\n}\n","import { Redis, type RedisOptions } from 'ioredis'\nimport type { ConfigRepository, Container, QueueJob, QueuePayload } from '@orieljs/contracts'\nimport { RedisJob } from '../jobs/RedisJob'\nimport { encodePayload } from '../payload'\nimport { QueueBase } from './QueueBase'\nimport { CLEAR, MIGRATE_EXPIRED_JOBS, POP, PUSH, RELEASE, SIZE } from './redisScripts'\n\nexport interface RedisQueueOptions {\n queue?: string\n /** Seconds before a reserved job is handed out again (Laravel's retry_after, default 90). */\n retryAfter?: number\n}\n\n/**\n * Client config for the redis driver: a prebuilt client, a URL, or ioredis options (`host`, `port`, `password`,\n * `db`, …). Either inline on the queue connection or a `database.redis.<name>` entry (see resolveRedisConfig()).\n */\nexport interface RedisConnectionConfig {\n client?: Redis\n url?: string\n [option: string]: unknown\n}\n\nconst QUEUE_KEYS = ['driver', 'connection', 'queue', 'retry_after', 'block_for', 'after_commit', 'client', 'url']\n\n/** An ioredis client. With a URL, the other options (such as `db`) apply where the URL doesn't set them. */\nexport function makeRedisClient(config: RedisConnectionConfig): Redis {\n if (config.client) return config.client\n const options = Object.fromEntries(\n Object.entries(config).filter(([key, value]) => value !== undefined && !QUEUE_KEYS.includes(key)),\n ) as RedisOptions\n if (typeof config.url === 'string' && config.url !== '') return new Redis(config.url, options)\n return new Redis(options)\n}\n\n/**\n * The client config for a redis queue connection. An inline `client` or `url` wins; otherwise, as in Laravel, the\n * `database.redis.<connection ?? 'default'>` entry (merged by Database). The connection's own inline ioredis\n * options are used only when that entry doesn't exist.\n */\nexport function resolveRedisConfig(config: RedisConnectionConfig, appConfig: ConfigRepository): RedisConnectionConfig {\n if (config.client !== undefined || (typeof config.url === 'string' && config.url !== '')) return config\n const name = typeof config.connection === 'string' && config.connection !== '' ? config.connection : 'default'\n return appConfig.get<RedisConnectionConfig | undefined>(`database.redis.${name}`) ?? config\n}\n\n/** Laravel's RedisQueue: a list per queue plus `:delayed`/`:reserved` sorted sets, moved around with Lua. */\nexport class RedisQueue extends QueueBase {\n private client: Redis | undefined\n private readonly retryAfter: number\n\n constructor(\n container: Container,\n private readonly connect: () => Redis,\n options: RedisQueueOptions = {},\n ) {\n super(container, options.queue ?? 'default')\n this.retryAfter = options.retryAfter ?? 90\n }\n\n redis(): Redis {\n return (this.client ??= this.connect())\n }\n\n /** The list key for a queue name: `queues:<name>`. */\n key(queue?: string): string {\n return `queues:${this.getQueue(queue)}`\n }\n\n async pushRaw(payload: QueuePayload, queue?: string, delaySeconds = 0): Promise<string> {\n const key = this.key(queue)\n const body = encodePayload({ ...payload, attempts: payload.attempts ?? 0 })\n if (delaySeconds > 0) await this.redis().zadd(`${key}:delayed`, this.now() + delaySeconds, body)\n else await this.redis().eval(PUSH, 2, key, `${key}:notify`, body)\n return payload.uuid\n }\n\n async pop(queue?: string): Promise<QueueJob | undefined> {\n const key = this.key(queue)\n const now = this.now()\n await this.redis().eval(MIGRATE_EXPIRED_JOBS, 3, `${key}:delayed`, key, `${key}:notify`, now)\n await this.redis().eval(MIGRATE_EXPIRED_JOBS, 3, `${key}:reserved`, key, `${key}:notify`, now)\n for (;;) {\n const [job, reserved] = (await this.redis().eval(POP, 3, key, `${key}:reserved`, `${key}:notify`, now + this.retryAfter)) as [\n string | null,\n string | null,\n ]\n if (!job || !reserved) return undefined\n try {\n return new RedisJob(this.jobContext(), this, job, reserved, this.getQueue(queue))\n } catch (error) {\n await this.failCorrupt(this.getQueue(queue), job, error)\n await this.redis().zrem(`${key}:reserved`, reserved)\n }\n }\n }\n\n async size(queue?: string): Promise<number> {\n const key = this.key(queue)\n return Number(await this.redis().eval(SIZE, 3, key, `${key}:delayed`, `${key}:reserved`))\n }\n\n async clear(queue?: string): Promise<number> {\n const key = this.key(queue)\n return Number(await this.redis().eval(CLEAR, 4, key, `${key}:delayed`, `${key}:reserved`, `${key}:notify`))\n }\n\n async deleteReserved(queue: string, job: RedisJob): Promise<void> {\n await this.redis().zrem(`${this.key(queue)}:reserved`, job.getReservedJob())\n }\n\n async deleteAndRelease(queue: string, job: RedisJob, delaySeconds: number): Promise<void> {\n const key = this.key(queue)\n await this.redis().eval(RELEASE, 2, `${key}:delayed`, `${key}:reserved`, job.getReservedJob(), this.now() + Math.max(0, delaySeconds))\n }\n\n override async disconnect(): Promise<void> {\n const client = this.client\n this.client = undefined\n if (client && client.status !== 'end') await client.quit()\n }\n\n /** Unix seconds, with milliseconds as the fraction (sorted-set scores). */\n private now(): number {\n return Date.now() / 1000\n }\n}\n","import { decodePayload, type QueueJobPayload } from '../payload'\nimport type { RedisQueue } from '../queues/RedisQueue'\nimport { BaseJob, type JobContext } from './BaseJob'\n\n/** A job popped from redis. `reserved` is the exact member stored in the `:reserved` set (attempts already bumped). */\nexport class RedisJob extends BaseJob {\n private readonly decoded: QueueJobPayload\n\n constructor(\n context: JobContext,\n private readonly redis: RedisQueue,\n private readonly job: string,\n private readonly reserved: string,\n queue: string,\n ) {\n super(context, queue)\n this.decoded = decodePayload(reserved)\n }\n\n getJobId(): string {\n return this.decoded.uuid\n }\n\n payload(): QueueJobPayload {\n return this.decoded\n }\n\n /** The payload as it was pushed (before the attempt was counted). */\n getRawBody(): string {\n return this.job\n }\n\n getReservedJob(): string {\n return this.reserved\n }\n\n override async delete(): Promise<void> {\n await super.delete()\n await this.redis.deleteReserved(this.queue, this)\n }\n\n override async release(delaySeconds = 0): Promise<void> {\n await super.release(delaySeconds)\n await this.redis.deleteAndRelease(this.queue, this, delaySeconds)\n }\n}\n","/**\n * Lua scripts for the redis driver, adapted from Laravel's Illuminate\\Queue\\LuaScripts. Keys: `queues:<name>` (list),\n * `:delayed` and `:reserved` (sorted sets scored by Unix seconds), `:notify` (list, one entry per ready job).\n */\n\n/** KEYS: queue, notify. ARGV: payload. */\nexport const PUSH = `\nredis.call('rpush', KEYS[1], ARGV[1])\nredis.call('rpush', KEYS[2], 1)\nreturn 1\n`\n\n/**\n * Pops a job and reserves it until ARGV[1], bumping attempts. Laravel re-encodes the payload with cjson, which turns\n * `[]` into `{}`; Oriel payloads always start with `{\"attempts\":N,`, so the count is replaced as text instead.\n * KEYS: queue, reserved, notify. ARGV: reserved-until. Returns {job, reserved}.\n */\nexport const POP = `\nlocal job = redis.call('lpop', KEYS[1])\nlocal reserved = false\nif (job ~= false) then\n local attempts = string.match(job, '^{\"attempts\":(%d+),')\n if attempts then\n reserved = '{\"attempts\":' .. (tonumber(attempts) + 1) .. ',' .. string.sub(job, string.len(attempts) + 14)\n else\n reserved = job\n end\n redis.call('zadd', KEYS[2], ARGV[1], reserved)\n redis.call('lpop', KEYS[3])\nend\nreturn {job, reserved}\n`\n\n/** Moves a reserved job to the delayed set. KEYS: delayed, reserved. ARGV: reserved payload, available-at. */\nexport const RELEASE = `\nredis.call('zrem', KEYS[2], ARGV[1])\nredis.call('zadd', KEYS[1], ARGV[2], ARGV[1])\nreturn 1\n`\n\n/** Moves jobs whose score is due from a sorted set onto the queue. KEYS: from, queue, notify. ARGV: now. */\nexport const MIGRATE_EXPIRED_JOBS = `\nlocal val = redis.call('zrangebyscore', KEYS[1], '-inf', ARGV[1])\nif (next(val) ~= nil) then\n redis.call('zremrangebyrank', KEYS[1], 0, #val - 1)\n for i = 1, #val, 100 do\n redis.call('rpush', KEYS[2], unpack(val, i, math.min(i + 99, #val)))\n for j = i, math.min(i + 99, #val) do\n redis.call('rpush', KEYS[3], 1)\n end\n end\nend\nreturn #val\n`\n\n/** KEYS: queue, delayed, reserved. */\nexport const SIZE = `\nreturn redis.call('llen', KEYS[1]) + redis.call('zcard', KEYS[2]) + redis.call('zcard', KEYS[3])\n`\n\n/** KEYS: queue, delayed, reserved, notify. Returns how many jobs were removed. */\nexport const CLEAR = `\nlocal size = redis.call('llen', KEYS[1]) + redis.call('zcard', KEYS[2]) + redis.call('zcard', KEYS[3])\nredis.call('del', KEYS[1], KEYS[2], KEYS[3], KEYS[4])\nreturn size\n`\n","import type { FailedJob, FailedJobProvider } from '@orieljs/contracts'\n\n/** Forgets failed jobs (queue.failed.driver = 'null'). */\nexport class NullFailedJobProvider implements FailedJobProvider {\n async log(): Promise<string> {\n return ''\n }\n async all(): Promise<FailedJob[]> {\n return []\n }\n async find(): Promise<FailedJob | undefined> {\n return undefined\n }\n async forget(): Promise<boolean> {\n return false\n }\n async flush(): Promise<void> {}\n}\n","import type { DatabaseConnection, FailedJob, FailedJobProvider, QueuePayload } from '@orieljs/contracts'\nimport { decodePayload, encodePayload } from '../payload'\n\ninterface FailedJobRow {\n id: number | string\n uuid: string\n connection: string\n queue: string\n payload: string\n exception: string\n failed_at: string | Date\n}\n\n/** `YYYY-MM-DD HH:MM:SS` in UTC: a value every driver accepts for a timestamp column. */\nexport function formatTimestamp(date: Date): string {\n return date.toISOString().slice(0, 19).replace('T', ' ')\n}\n\nfunction parseTimestamp(value: string | Date): Date {\n if (value instanceof Date) return value\n return new Date(/[zZ]|[+-]\\d\\d:?\\d\\d$/.test(value) ? value : `${value.replace(' ', 'T')}Z`)\n}\n\n/** Like PHP's (string) $exception: the stack when there is one. */\nexport function describeError(error: unknown): string {\n if (error instanceof Error) return error.stack ?? `${error.name}: ${error.message}`\n return String(error)\n}\n\n/** Laravel's DatabaseUuidFailedJobProvider (`database-uuids`): failed jobs are identified by the payload uuid. */\nexport class DatabaseFailedJobProvider implements FailedJobProvider {\n constructor(\n private readonly database: () => DatabaseConnection,\n private readonly table = 'failed_jobs',\n ) {}\n\n async log(connection: string, queue: string, payload: QueuePayload, error: unknown): Promise<string> {\n await this.database().table(this.table).insert({\n uuid: payload.uuid,\n connection,\n queue,\n payload: encodePayload(payload),\n exception: describeError(error),\n failed_at: formatTimestamp(new Date(Date.now())),\n })\n return payload.uuid\n }\n\n async all(): Promise<FailedJob[]> {\n const rows = await this.database().table<FailedJobRow>(this.table).orderBy('id', 'desc').get()\n return rows.all().map((row) => this.toFailedJob(row))\n }\n\n async find(id: string): Promise<FailedJob | undefined> {\n const row = await this.database().table<FailedJobRow>(this.table).where('uuid', id).first()\n return row ? this.toFailedJob(row) : undefined\n }\n\n async forget(id: string): Promise<boolean> {\n return (await this.database().table(this.table).where('uuid', id).delete()) > 0\n }\n\n async flush(): Promise<void> {\n await this.database().table(this.table).delete()\n }\n\n private toFailedJob(row: FailedJobRow): FailedJob {\n return {\n id: row.uuid,\n connection: row.connection,\n queue: row.queue,\n payload: decodePayload(row.payload),\n exception: row.exception,\n failedAt: parseTimestamp(row.failed_at),\n }\n }\n}\n","/**\n * Text of Laravel 11's `0001_01_01_000002_create_jobs_table` migration, for the skeleton's\n * `database/migrations/0001_01_01_000002_create_jobs_table.ts`. Database owns migrations, so Queue ships the text\n * (the C2 skeleton step writes it); it is not compiled here.\n */\nexport const JOBS_TABLE_MIGRATION = `import { Migration, Schema } from '@orieljs/framework'\n\nexport default class extends Migration {\n async up() {\n await Schema.create('jobs', (t) => {\n t.id()\n t.string('queue').index()\n t.longText('payload')\n t.unsignedTinyInteger('attempts')\n t.unsignedInteger('reserved_at').nullable()\n t.unsignedInteger('available_at')\n t.unsignedInteger('created_at')\n })\n\n await Schema.create('job_batches', (t) => {\n t.string('id').primary()\n t.string('name')\n t.integer('total_jobs')\n t.integer('pending_jobs')\n t.integer('failed_jobs')\n t.longText('failed_job_ids')\n t.mediumText('options').nullable()\n t.integer('cancelled_at').nullable()\n t.integer('created_at')\n t.integer('finished_at').nullable()\n })\n\n await Schema.create('failed_jobs', (t) => {\n t.id()\n t.string('uuid').unique()\n t.text('connection')\n t.text('queue')\n t.longText('payload')\n t.longText('exception')\n t.timestamp('failed_at').useCurrent()\n })\n }\n\n async down() {\n await Schema.dropIfExists('jobs')\n await Schema.dropIfExists('job_batches')\n await Schema.dropIfExists('failed_jobs')\n }\n}\n`\n","import type { Batch as BatchContract, BatchRepository } from '@orieljs/contracts'\nimport type { QueueJobPayload } from '../payload'\n\n/** The `options` column: callbacks are stored as payloads. */\nexport interface StoredBatchOptions {\n allowFailures: boolean\n connection?: string\n queue?: string\n then: QueueJobPayload[]\n catch: QueueJobPayload[]\n finally: QueueJobPayload[]\n}\n\nexport interface BatchAttributes {\n id: string\n name: string\n totalJobs: number\n pendingJobs: number\n failedJobs: number\n failedJobIds: string[]\n options: StoredBatchOptions\n createdAt: Date\n cancelledAt?: Date\n finishedAt?: Date\n}\n\n/** A snapshot of a batch row (Laravel's Illuminate\\Bus\\Batch). Call fresh() for current numbers. */\nexport class Batch implements BatchContract {\n readonly id: string\n readonly name: string\n readonly totalJobs: number\n readonly pendingJobs: number\n readonly failedJobs: number\n readonly failedJobIds: string[]\n readonly options: StoredBatchOptions\n readonly createdAt: Date\n readonly cancelledAt: Date | undefined\n readonly finishedAt: Date | undefined\n\n constructor(\n private readonly repository: BatchRepository,\n attributes: BatchAttributes,\n ) {\n this.id = attributes.id\n this.name = attributes.name\n this.totalJobs = attributes.totalJobs\n this.pendingJobs = attributes.pendingJobs\n this.failedJobs = attributes.failedJobs\n this.failedJobIds = attributes.failedJobIds\n this.options = attributes.options\n this.createdAt = attributes.createdAt\n this.cancelledAt = attributes.cancelledAt\n this.finishedAt = attributes.finishedAt\n }\n\n processedJobs(): number {\n return this.totalJobs - this.pendingJobs\n }\n\n /** Percentage of processed jobs, 0–100. */\n progress(): number {\n return this.totalJobs > 0 ? Math.round((this.processedJobs() / this.totalJobs) * 100) : 0\n }\n\n finished(): boolean {\n return this.finishedAt !== undefined\n }\n\n cancelled(): boolean {\n return this.cancelledAt !== undefined\n }\n\n hasFailures(): boolean {\n return this.failedJobs > 0\n }\n\n allowsFailures(): boolean {\n return this.options.allowFailures\n }\n\n cancel(): Promise<void> {\n return this.repository.cancel(this.id)\n }\n\n delete(): Promise<void> {\n return this.repository.delete(this.id)\n }\n\n fresh(): Promise<BatchContract | undefined> {\n return this.repository.find(this.id)\n }\n\n toJSON(): Record<string, unknown> {\n return {\n id: this.id,\n name: this.name,\n totalJobs: this.totalJobs,\n pendingJobs: this.pendingJobs,\n processedJobs: this.processedJobs(),\n progress: this.progress(),\n failedJobs: this.failedJobs,\n createdAt: this.createdAt,\n cancelledAt: this.cancelledAt,\n finishedAt: this.finishedAt,\n }\n }\n}\n","import { randomUUID } from 'node:crypto'\nimport {\n ClassRegistry,\n type BatchRepository,\n type Container,\n type DatabaseConnection,\n type Job,\n type PendingBatchOptions,\n} from '@orieljs/contracts'\nimport { CallQueuedHandler } from '../CallQueuedHandler'\nimport { createPayload, restoreJob, type QueueJobPayload } from '../payload'\nimport { BATCH_CALLBACK, setSymbolValue } from '../symbols'\nimport { Batch, type StoredBatchOptions } from './Batch'\n\n/** A row of `job_batches` (Laravel 11 schema). Times are Unix seconds. */\ninterface BatchRow {\n id: string\n name: string\n total_jobs: number\n pending_jobs: number\n failed_jobs: number\n failed_job_ids: string\n options: string | null\n created_at: number\n cancelled_at: number | null\n finished_at: number | null\n}\n\ninterface Counts {\n pendingJobs: number\n failedJobs: number\n}\n\nconst toDate = (seconds: number | null): Date | undefined => (seconds === null || seconds === undefined ? undefined : new Date(Number(seconds) * 1000))\n\n/** Laravel's DatabaseBatchRepository plus Batch::recordSuccessfulJob/recordFailedJob. */\nexport class DatabaseBatchRepository implements BatchRepository {\n private readonly handler: CallQueuedHandler\n\n constructor(\n private readonly container: Container,\n private readonly database: () => DatabaseConnection,\n private readonly table = 'job_batches',\n ) {\n this.handler = new CallQueuedHandler(container)\n }\n\n async store(options: PendingBatchOptions): Promise<Batch> {\n const id = randomUUID()\n const registry = this.container.make(ClassRegistry)\n const payloads = (jobs: Job[]): QueueJobPayload[] => jobs.map((job) => createPayload(job, registry))\n const stored: StoredBatchOptions = {\n allowFailures: options.allowFailures,\n then: payloads(options.then),\n catch: payloads(options.catch),\n finally: payloads(options.finally),\n }\n if (options.connection !== undefined) stored.connection = options.connection\n if (options.queue !== undefined) stored.queue = options.queue\n await this.database().table(this.table).insert({\n id,\n name: options.name,\n total_jobs: 0,\n pending_jobs: 0,\n failed_jobs: 0,\n failed_job_ids: '[]',\n options: JSON.stringify(stored),\n created_at: this.now(),\n cancelled_at: null,\n finished_at: null,\n })\n return (await this.find(id))!\n }\n\n async find(id: string): Promise<Batch | undefined> {\n const row = await this.database().table<BatchRow>(this.table).where('id', id).first()\n return row ? this.toBatch(row) : undefined\n }\n\n async incrementTotalJobs(id: string, amount: number): Promise<void> {\n await this.database().transaction(async (db) => {\n await db.table(this.table).where('id', id).increment('total_jobs', amount, { finished_at: null })\n await db.table(this.table).where('id', id).increment('pending_jobs', amount)\n })\n }\n\n async recordSuccessfulJob(id: string, jobUuid: string): Promise<void> {\n const counts = await this.updateAtomicValues(id, (row, failedIds) => ({\n pending_jobs: Number(row.pending_jobs) - 1,\n failed_jobs: Number(row.failed_jobs),\n failed_job_ids: failedIds.filter((failed) => failed !== jobUuid),\n }))\n if (!counts) return\n if (counts.pendingJobs === 0) await this.markAsFinished(id)\n const batch = await this.find(id)\n if (!batch) return\n if (counts.pendingJobs === 0) await this.invoke(batch, batch.options.then)\n if (counts.pendingJobs - counts.failedJobs === 0) await this.invoke(batch, batch.options.finally)\n }\n\n async recordFailedJob(id: string, jobUuid: string, _error: unknown): Promise<void> {\n const counts = await this.updateAtomicValues(id, (row, failedIds) => ({\n pending_jobs: Number(row.pending_jobs),\n failed_jobs: Number(row.failed_jobs) + 1,\n failed_job_ids: [...new Set([...failedIds, jobUuid])],\n }))\n if (!counts) return\n const before = await this.find(id)\n if (!before) return\n if (counts.failedJobs === 1 && !before.allowsFailures()) await this.cancel(id)\n const batch = (await this.find(id))!\n if (counts.failedJobs === 1) await this.invoke(batch, batch.options.catch)\n if (counts.pendingJobs - counts.failedJobs === 0) await this.invoke(batch, batch.options.finally)\n }\n\n async markAsFinished(id: string): Promise<void> {\n await this.database().table(this.table).where('id', id).update({ finished_at: this.now() })\n }\n\n async cancel(id: string): Promise<void> {\n const now = this.now()\n await this.database().table(this.table).where('id', id).update({ cancelled_at: now, finished_at: now })\n }\n\n async delete(id: string): Promise<void> {\n await this.database().table(this.table).where('id', id).delete()\n }\n\n /** Read-modify-write of the counters under a row lock (Laravel's updateAtomicValues). */\n private async updateAtomicValues(\n id: string,\n change: (row: BatchRow, failedIds: string[]) => { pending_jobs: number; failed_jobs: number; failed_job_ids: string[] },\n ): Promise<Counts | undefined> {\n return this.database().transaction(async (db) => {\n const row = await db.table<BatchRow>(this.table).where('id', id).lockForUpdate().first()\n if (!row) return undefined\n const values = change(row, JSON.parse(row.failed_job_ids || '[]') as string[])\n await db.table(this.table).where('id', id).update({ ...values, failed_job_ids: JSON.stringify(values.failed_job_ids) })\n return { pendingJobs: values.pending_jobs, failedJobs: values.failed_jobs }\n })\n }\n\n /** Restores each callback job, gives it the batch id, marks it as a callback (so it isn't counted) and dispatches it. */\n private async invoke(batch: Batch, callbacks: QueueJobPayload[]): Promise<void> {\n const registry = this.container.make(ClassRegistry)\n for (const payload of callbacks) {\n const job = await restoreJob(payload, registry)\n ;(job as { batchId?: string }).batchId = batch.id\n setSymbolValue(job, BATCH_CALLBACK, true)\n await this.handler.dispatchCallback(job)\n }\n }\n\n private toBatch(row: BatchRow): Batch {\n const options = (row.options ? JSON.parse(row.options) : {}) as Partial<StoredBatchOptions>\n return new Batch(this, {\n id: row.id,\n name: row.name,\n totalJobs: Number(row.total_jobs),\n pendingJobs: Number(row.pending_jobs),\n failedJobs: Number(row.failed_jobs),\n failedJobIds: JSON.parse(row.failed_job_ids || '[]') as string[],\n options: { allowFailures: false, then: [], catch: [], finally: [], ...options },\n createdAt: toDate(row.created_at)!,\n cancelledAt: toDate(row.cancelled_at),\n finishedAt: toDate(row.finished_at),\n })\n }\n\n private now(): number {\n return Math.floor(Date.now() / 1000)\n }\n}\n","import { setTimeout as sleep } from 'node:timers/promises'\nimport {\n BusDispatcher,\n CacheManager,\n ExceptionHandler,\n type Container,\n type QueueJob,\n type QueueManager,\n} from '@orieljs/contracts'\nimport { MaxAttemptsExceededError, TimeoutExceededError } from './errors'\nimport type { BaseJob } from './jobs/BaseJob'\nimport { normalizeBackoff } from './payload'\n\n/** `queue:work` options (Laravel's WorkerOptions). Seconds unless noted. */\nexport interface WorkerOptions {\n name: string\n /** Seconds to wait before retrying a failed job: one number or a per-attempt list. */\n backoff: number | number[] | string\n /** MB of V8 heap after which the worker stops (exit 12). 0 disables the check. */\n memory: number\n /** Max seconds a job may run. 0 disables it. A job's own `timeout` wins. */\n timeout: number\n /** Seconds to sleep when no job is available. */\n sleep: number\n /** Attempts before a job fails, unless the job sets `tries`. 0 = unlimited. */\n maxTries: number\n stopWhenEmpty: boolean\n /** Stop after this many jobs. 0 = no limit. */\n maxJobs: number\n /** Stop after this many seconds. 0 = no limit. */\n maxTime: number\n /** Seconds to rest between jobs. */\n rest: number\n}\n\nexport const defaultWorkerOptions = (): WorkerOptions => ({\n name: 'default',\n backoff: 0,\n memory: 128,\n timeout: 60,\n sleep: 3,\n maxTries: 1,\n stopWhenEmpty: false,\n maxJobs: 0,\n maxTime: 0,\n rest: 0,\n})\n\n/** Hooks for output (the queue:work command prints RUNNING / DONE / FAIL lines with them). */\nexport interface WorkerListener {\n processing?(job: QueueJob): void\n processed?(job: QueueJob, milliseconds: number): void\n failed?(job: QueueJob, error: unknown): void\n exception?(error: unknown, job?: QueueJob): void\n}\n\n/** What the worker needs from a popped job: drivers return BaseJob subclasses. */\ntype WorkableJob = QueueJob & Pick<BaseJob, 'fire' | 'hasFailed' | 'maxTries' | 'retryUntil' | 'backoff' | 'timeout' | 'shouldFailOnTimeout' | 'resolveName'>\n\ninterface FlushesAfterResponse {\n flushAfterResponse?(): Promise<void>\n}\n\nexport const RESTART_CACHE_KEY = 'oriel:queue:restart'\n\n/**\n * Laravel's Illuminate\\Queue\\Worker: pops jobs, runs each in a fresh container scope, applies tries / backoff /\n * retryUntil / timeout, and stops on a signal, a restart broadcast, memory, --max-jobs, --max-time or an empty queue.\n * A job's error never crashes the loop (spec §7): it's reported and the job is released or failed. Nor does an\n * unhandled rejection leaked from a job's handle(): it's reported the same way, and the job (if not already failed)\n * is failed with it.\n */\nexport class Worker {\n static readonly EXIT_SUCCESS = 0\n static readonly EXIT_ERROR = 1\n static readonly EXIT_MEMORY_LIMIT = 12\n\n shouldQuit = false\n private timedOut = false\n private sleeping: AbortController | undefined\n private currentJob: QueueJob | undefined\n /** F2: the promise handling the most recently leaked unhandled rejection, awaited by process() before it decides\n * whether the job succeeded, so failing it is never racing the \"processed\" event. */\n private pendingRejection: Promise<void> | undefined\n\n constructor(\n private readonly manager: QueueManager,\n private readonly container: Container,\n private readonly listener: WorkerListener = {},\n ) {}\n\n /** Runs until a stop condition; returns the exit code. `queue` may be a comma-separated priority list. */\n async daemon(connectionName: string, queue: string, options: WorkerOptions): Promise<number> {\n const stopListening = this.listenForSignals()\n try {\n const startTime = Date.now()\n const lastRestart = await this.getTimestampOfLastQueueRestart()\n let jobsProcessed = 0\n for (;;) {\n const job = await this.getNextJob(connectionName, queue)\n if (job) {\n jobsProcessed++\n await this.runJob(job, connectionName, options)\n if (options.rest > 0) await this.sleep(options.rest)\n } else if (!options.stopWhenEmpty) {\n await this.sleep(options.sleep)\n }\n const status = await this.stopIfNecessary(options, lastRestart, startTime, jobsProcessed, job)\n if (status !== undefined) return status\n }\n } finally {\n stopListening()\n }\n }\n\n /**\n * `--once`: processes the next job, or sleeps when there is none. Laravel's runNextJob doesn't listen for stop\n * signals, but spec §7 still binds here: the unhandled-rejection guard (F2) is installed for the duration of the\n * single run, through the same helper listenForSignals() uses, so a leaked rejection fails the job instead of\n * crashing the process. Returns EXIT_ERROR when the job timed out, EXIT_SUCCESS otherwise.\n */\n async runNextJob(connectionName: string, queue: string, options: WorkerOptions): Promise<number> {\n const stopGuarding = this.guardUnhandledRejections()\n try {\n const job = await this.getNextJob(connectionName, queue)\n if (job) await this.runJob(job, connectionName, options)\n else await this.sleep(options.sleep)\n return this.timedOut ? Worker.EXIT_ERROR : Worker.EXIT_SUCCESS\n } finally {\n stopGuarding()\n }\n }\n\n /** Stops after the current job (SIGTERM/SIGINT/SIGQUIT call this). */\n stop(): void {\n this.shouldQuit = true\n this.sleeping?.abort()\n }\n\n /** Registers graceful-stop signal handlers and the unhandled-rejection guard; returns a function that removes them. */\n listenForSignals(): () => void {\n const signals: NodeJS.Signals[] = ['SIGTERM', 'SIGINT', 'SIGQUIT']\n const handler = () => this.stop()\n for (const signal of signals) process.on(signal, handler)\n const stopGuarding = this.guardUnhandledRejections()\n return () => {\n for (const signal of signals) process.off(signal, handler)\n stopGuarding()\n }\n }\n\n /** F2: installs the process-wide unhandledRejection guard; returns a function that removes it. */\n private guardUnhandledRejections(): () => void {\n const onUnhandledRejection = (error: unknown) => {\n this.pendingRejection = this.handleUnhandledRejection(error)\n }\n process.on('unhandledRejection', onUnhandledRejection)\n return () => process.off('unhandledRejection', onUnhandledRejection)\n }\n\n /** Processes one job: max-attempts check, fire (with timeout), and failure handling. `_connectionName` is unused (kept for Laravel's signature). */\n async process(_connectionName: string, job: QueueJob, options: WorkerOptions): Promise<void> {\n const workable = job as WorkableJob\n const started = Date.now()\n try {\n this.listener.processing?.(job)\n await this.markJobAsFailedIfAlreadyExceedsMaxAttempts(workable, options.maxTries)\n if (job.isDeleted()) return\n await this.fireWithTimeout(workable, options)\n // A leaked unhandled rejection (F2) may have fired while fire() was running; wait for it to finish failing\n // the job before deciding whether it actually succeeded, so \"processed\" never races \"failed\" for the same job.\n if (this.pendingRejection) {\n const pending = this.pendingRejection\n this.pendingRejection = undefined\n await pending\n }\n if (!workable.hasFailed()) this.listener.processed?.(job, Date.now() - started)\n } catch (error) {\n await this.handleJobException(workable, options, error)\n }\n }\n\n async sleep(seconds: number): Promise<void> {\n if (seconds <= 0 || this.shouldQuit) return\n this.sleeping = new AbortController()\n try {\n await sleep(seconds * 1000, undefined, { signal: this.sleeping.signal })\n } catch {\n // aborted by stop()\n } finally {\n this.sleeping = undefined\n }\n }\n\n /** Runs one job in its own scope. Nothing it throws escapes: an error from the failure handling itself (a failed()\n * hook, the failed-job provider, a release) is reported like any other, as Laravel's Worker::runJob does. */\n private async runJob(job: QueueJob, connectionName: string, options: WorkerOptions): Promise<void> {\n const scope = this.container.createScope()\n await scope.run(async () => {\n this.currentJob = job\n try {\n await this.process(connectionName, job, options)\n } catch (error) {\n await this.report(error, job)\n } finally {\n this.currentJob = undefined\n }\n try {\n if (scope.bound(BusDispatcher)) await (scope.make(BusDispatcher) as FlushesAfterResponse).flushAfterResponse?.()\n } catch (error) {\n await this.report(error)\n }\n })\n }\n\n private async getNextJob(connectionName: string, queue: string): Promise<QueueJob | undefined> {\n try {\n const connection = this.manager.connection(connectionName)\n for (const name of queue.split(',')) {\n const job = await connection.pop(name.trim())\n if (job) return job\n }\n } catch (error) {\n await this.report(error)\n await this.sleep(1)\n }\n return undefined\n }\n\n private async fireWithTimeout(job: WorkableJob, options: WorkerOptions): Promise<void> {\n const timeout = job.timeout() ?? options.timeout\n if (!timeout || timeout <= 0) return job.fire()\n let timer: NodeJS.Timeout | undefined\n const expired = new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(new TimeoutExceededError(job.resolveName())), timeout * 1000)\n })\n try {\n await Promise.race([job.fire(), expired])\n } finally {\n clearTimeout(timer)\n }\n }\n\n /** Releases or fails the job. The job's error is reported even when handling it throws (runJob reports that too). */\n private async handleJobException(job: WorkableJob, options: WorkerOptions, error: unknown): Promise<void> {\n try {\n if (error instanceof TimeoutExceededError) {\n // Like Laravel's timeout handler: the job stays reserved (retry_after hands it out again), and the worker\n // stops, because the timed-out promise can't be cancelled.\n this.timedOut = true\n await this.markJobAsFailedIfWillExceedMaxAttempts(job, options.maxTries, error)\n if (!job.hasFailed() && job.shouldFailOnTimeout()) await this.failJob(job, error)\n } else {\n try {\n if (!job.hasFailed()) await this.markJobAsFailedIfWillExceedMaxAttempts(job, options.maxTries, error)\n } finally {\n if (!job.isDeleted() && !job.isReleased() && !job.hasFailed()) await job.release(this.calculateBackoff(job, options))\n }\n }\n } finally {\n await this.report(error, job)\n }\n }\n\n private async markJobAsFailedIfAlreadyExceedsMaxAttempts(job: WorkableJob, maxTries: number): Promise<void> {\n const max = job.maxTries() ?? maxTries\n const retryUntil = job.retryUntil()\n if (retryUntil !== undefined && Date.now() <= retryUntil) return\n if (retryUntil === undefined && (max === 0 || job.attempts() <= max)) return\n const error = new MaxAttemptsExceededError(job.resolveName())\n await this.failJob(job, error)\n throw error\n }\n\n private async markJobAsFailedIfWillExceedMaxAttempts(job: WorkableJob, maxTries: number, error: unknown): Promise<void> {\n const max = job.maxTries() ?? maxTries\n const retryUntil = job.retryUntil()\n if (retryUntil !== undefined && retryUntil <= Date.now()) return this.failJob(job, error)\n if (retryUntil === undefined && max > 0 && job.attempts() >= max) return this.failJob(job, error)\n }\n\n private async failJob(job: WorkableJob, error: unknown): Promise<void> {\n if (job.hasFailed()) return\n try {\n await job.fail(error)\n } finally {\n this.listener.failed?.(job, error)\n }\n }\n\n private calculateBackoff(job: WorkableJob, options: WorkerOptions): number {\n const backoff = job.backoff() ?? normalizeBackoff(options.backoff) ?? [0]\n return backoff[job.attempts() - 1] ?? backoff.at(-1) ?? 0\n }\n\n private async stopIfNecessary(\n options: WorkerOptions,\n lastRestart: unknown,\n startTime: number,\n jobsProcessed: number,\n job: QueueJob | undefined,\n ): Promise<number | undefined> {\n if (this.shouldQuit) return Worker.EXIT_SUCCESS\n if (this.timedOut) return Worker.EXIT_ERROR\n if (this.memoryExceeded(options.memory)) return Worker.EXIT_MEMORY_LIMIT\n if (await this.queueShouldRestart(lastRestart)) return Worker.EXIT_SUCCESS\n if (options.stopWhenEmpty && !job) return Worker.EXIT_SUCCESS\n if (options.maxTime > 0 && Date.now() - startTime >= options.maxTime * 1000) return Worker.EXIT_SUCCESS\n if (options.maxJobs > 0 && jobsProcessed >= options.maxJobs) return Worker.EXIT_SUCCESS\n return undefined\n }\n\n memoryExceeded(limitMb: number): boolean {\n return limitMb > 0 && process.memoryUsage().heapUsed / 1024 / 1024 >= limitMb\n }\n\n private async queueShouldRestart(lastRestart: unknown): Promise<boolean> {\n return (await this.getTimestampOfLastQueueRestart()) !== lastRestart\n }\n\n private async getTimestampOfLastQueueRestart(): Promise<unknown> {\n if (!this.container.bound(CacheManager)) return undefined\n return this.container.make(CacheManager).get(RESTART_CACHE_KEY)\n }\n\n /** Reports through the ExceptionHandler when bound, and tells the listener. Never throws. */\n private async report(error: unknown, job?: QueueJob): Promise<void> {\n this.listener.exception?.(error, job)\n try {\n if (this.container.bound(ExceptionHandler)) await this.container.make(ExceptionHandler).report(error)\n else if (!this.listener.exception) console.error(error)\n } catch (reportingError) {\n console.error(reportingError)\n }\n }\n\n /**\n * Spec §7: an unhandled rejection leaked from a job's handle() must not crash the worker. It's reported through\n * the same path as any other job error, and the job currently running — if there is one, and it hasn't already\n * failed — is failed with it, exactly as handleJobException fails a job.\n */\n private async handleUnhandledRejection(error: unknown): Promise<void> {\n const job = this.currentJob as WorkableJob | undefined\n await this.report(error, job)\n try {\n if (job && !job.hasFailed()) await this.failJob(job, error)\n } catch (failingError) {\n await this.report(failingError, job)\n }\n }\n}\n","import { existsSync, readdirSync, statSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport type { Class, ClassRegistry } from '@orieljs/contracts'\nimport { classNameOf } from '../serialization'\n\nconst EXTENSIONS = ['.ts', '.js', '.mts', '.mjs']\n\nfunction files(directory: string): string[] {\n const found: string[] = []\n for (const entry of readdirSync(directory).sort()) {\n const path = join(directory, entry)\n if (statSync(path).isDirectory()) found.push(...files(path))\n else if (EXTENSIONS.some((extension) => entry.endsWith(extension)) && !entry.endsWith('.d.ts')) found.push(path)\n }\n return found\n}\n\n/** The app directories whose classes travel inside wrapper jobs (queued listeners, mailables, notifications). */\nexport const WORKER_DISCOVERY_DIRECTORIES = ['Events', 'Listeners', 'Mail', 'Notifications'] as const\n\nconst isClass = (value: unknown): value is Class<unknown> =>\n typeof value === 'function' && /^class[\\s{]/.test(Function.prototype.toString.call(value))\n\nconst isJobClass = (value: Class<unknown>): boolean => typeof (value.prototype as { handle?: unknown }).handle === 'function'\n\n/**\n * Imports every module under `directory` (recursively) and registers each exported class that passes `filter`\n * (every class by default) under its own name, so a worker process can restore objects it never created itself.\n * Returns the registered names. A missing directory registers nothing. A name already taken by a different class\n * (classNameOf) rejects with a JobSerializationError naming the class and suggesting an explicit namespaced\n * registration, instead of surfacing the ClassRegistry's bare collision error.\n */\nexport async function discoverClasses(\n directory: string,\n registry: ClassRegistry,\n filter: (cls: Class<unknown>) => boolean = () => true,\n): Promise<string[]> {\n if (!existsSync(directory)) return []\n const names: string[] = []\n for (const file of files(directory)) {\n const module = (await import(pathToFileURL(file).href)) as Record<string, unknown>\n for (const exported of Object.values(module)) {\n if (isClass(exported) && filter(exported)) names.push(classNameOf(registry, exported))\n }\n }\n return names\n}\n\n/** Registers the exported classes under `directory` that have a handle() method (app/Jobs). */\nexport function discoverJobs(directory: string, registry: ClassRegistry): Promise<string[]> {\n return discoverClasses(directory, registry, isJobClass)\n}\n","import {\n CacheManager,\n ClassRegistry,\n ConfigRepository,\n FailedJobProvider,\n QueueManager,\n type Application,\n type CommandContext,\n type ConsoleKernel,\n type Container,\n type FailedJob,\n type QueueJob,\n} from '@orieljs/contracts'\nimport { Str } from '@orieljs/support'\nimport { formatTimestamp } from '../failed/DatabaseFailedJobProvider'\nimport { optionalString, restoreJob, type QueueJobPayload } from '../payload'\nimport { defaultWorkerOptions, RESTART_CACHE_KEY, Worker, type WorkerOptions } from '../Worker'\nimport { discoverClasses, discoverJobs, WORKER_DISCOVERY_DIRECTORIES } from './discoverJobs'\n\nexport interface QueueCommandContext {\n app: Pick<Application, 'isProduction' | 'appPath'>\n container: Container\n}\n\nconst text = (value: unknown): string | undefined => optionalString(value) || undefined\nconst list = (value: unknown): string[] => (Array.isArray(value) ? value.map(String) : text(value) ? [String(value)] : [])\nconst number = (value: unknown, fallback: number): number => {\n const parsed = Number(value)\n return value === undefined || value === null || value === '' || Number.isNaN(parsed) ? fallback : parsed\n}\n\n/** The class of a thrown value (never its message): `TimeoutExceededError`, or `string` for a thrown string. */\nconst errorClass = (error: unknown): string =>\n error instanceof Error ? error.constructor.name || error.name : error === null ? 'null' : typeof error === 'object' ? error.constructor?.name || 'object' : typeof error\n\nfunction localTimestamp(date = new Date()): string {\n const pad = (n: number) => String(n).padStart(2, '0')\n return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`\n}\n\n/** Laravel's queue:work options from the parsed command options. */\nexport function workerOptionsFrom(option: (name: string) => unknown): WorkerOptions {\n const defaults = defaultWorkerOptions()\n return {\n name: text(option('name')) ?? defaults.name,\n backoff: text(option('backoff')) ?? defaults.backoff,\n memory: number(option('memory'), defaults.memory),\n timeout: number(option('timeout'), defaults.timeout),\n sleep: number(option('sleep'), defaults.sleep),\n maxTries: number(option('tries'), defaults.maxTries),\n stopWhenEmpty: option('stop-when-empty') === true,\n maxJobs: number(option('max-jobs'), defaults.maxJobs),\n maxTime: number(option('max-time'), defaults.maxTime),\n rest: number(option('rest'), defaults.rest),\n }\n}\n\n/** The queue:* commands, registered as closure commands (PC1). */\nexport function registerQueueCommands(kernel: ConsoleKernel, context: QueueCommandContext): void {\n const { container } = context\n const define = (signature: string, description: string, handler: (out: CommandContext) => Promise<number>) =>\n kernel\n .command(signature, async function (this: CommandContext) {\n return handler(this)\n })\n .purpose(description)\n const config = () => container.make(ConfigRepository)\n const defaultConnection = () => String(config().get('queue.default', 'sync'))\n const defaultQueue = (connection: string) => String(config().get(`queue.connections.${connection}.queue`, 'default'))\n const failer = () => container.make(FailedJobProvider)\n const confirmToProceed = (out: CommandContext): boolean => {\n if (!context.app.isProduction() || out.option('force') === true) return true\n out.error('Application in production. Use --force to run this command.')\n return false\n }\n\n define(\n 'queue:work {connection? : The name of the queue connection to work} {--name=default : The name of the worker} ' +\n '{--queue= : The names of the queues to work} {--once : Only process the next job on the queue} ' +\n '{--stop-when-empty : Stop when the queue is empty} {--backoff=0 : Seconds to wait before retrying a job that failed} ' +\n '{--max-jobs=0 : The number of jobs to process before stopping} {--max-time=0 : The maximum number of seconds the worker should run} ' +\n '{--memory=128 : The memory limit in megabytes} {--sleep=3 : Seconds to sleep when no job is available} ' +\n '{--rest=0 : Seconds to rest between jobs} {--timeout=60 : The number of seconds a child process can run} ' +\n '{--tries=1 : Number of times to attempt a job before logging it failed}',\n 'Start processing jobs on the queue as a daemon',\n async (out) => {\n const connection = text(out.argument('connection')) ?? defaultConnection()\n const queue = text(out.option('queue')) ?? defaultQueue(connection)\n const registry = container.make(ClassRegistry)\n await discoverJobs(context.app.appPath('Jobs'), registry)\n for (const directory of WORKER_DISCOVERY_DIRECTORIES) await discoverClasses(context.app.appPath(directory), registry)\n const name = (job: QueueJob) => job.payload().displayName\n const worker = new Worker(container.make(QueueManager), container, {\n processing: (job) => out.line(` ${localTimestamp()} ${name(job)} RUNNING`),\n processed: (job, ms) => out.line(` ${localTimestamp()} ${name(job)} ${ms}ms DONE`),\n failed: (job) => out.line(` ${localTimestamp()} ${name(job)} FAIL`),\n // Only the error's class: its message may carry payload data, and the ExceptionHandler reports it in full.\n exception: (error, job) => out.error(`${job ? `${name(job)}: ` : ''}${errorClass(error)}`),\n })\n const options = workerOptionsFrom((option) => out.option(option))\n out.info(`Processing jobs from the [${queue}] ${Str.plural('queue', queue.split(',').length)}.`)\n if (out.option('once') === true) {\n return worker.runNextJob(connection, queue, options)\n }\n return worker.daemon(connection, queue, options)\n },\n )\n\n define('queue:restart', 'Restart queue worker daemons after their current job', async (out) => {\n if (!container.bound(CacheManager)) {\n out.error('queue:restart needs a cache store. Register the CacheServiceProvider.')\n return 1\n }\n await container.make(CacheManager).forever(RESTART_CACHE_KEY, Date.now())\n out.info('Broadcasting queue restart signal.')\n return 0\n })\n\n define('queue:failed', 'List all of the failed queue jobs', async (out) => {\n const jobs = await failer().all()\n if (jobs.length === 0) {\n out.info('No failed jobs found.')\n return 0\n }\n for (const job of jobs) {\n out.line(` ${formatTimestamp(job.failedAt)} ${job.id} ${job.connection}@${job.queue} ${job.payload.displayName}`)\n }\n return 0\n })\n\n define(\n 'queue:retry {id?* : The ID of the failed job or \"all\" to retry all jobs} {--queue= : Retry all of the failed jobs for the specified queue}',\n 'Retry a failed queue job',\n async (out) => {\n const ids = await retryableIds(list(out.argument('id')), text(out.option('queue')))\n if (ids.length === 0) {\n out.info('No retryable jobs found.')\n return 0\n }\n out.info('Pushing failed queue jobs back onto the queue.')\n let status = 0\n for (const id of ids) {\n const job = await failer().find(id)\n if (!job) {\n out.error(`Unable to find failed job with ID [${id}].`)\n status = 1\n continue\n }\n await retryJob(job)\n out.line(` ${id} DONE`)\n await failer().forget(id)\n }\n return status\n },\n )\n\n define('queue:forget {id : The ID of the failed job}', 'Delete a failed queue job', async (out) => {\n if (await failer().forget(String(out.argument('id')))) {\n out.info('Failed job deleted successfully.')\n return 0\n }\n out.error('No failed job matches the given ID.')\n return 1\n })\n\n define('queue:flush', 'Flush all of the failed queue jobs', async (out) => {\n await failer().flush()\n out.info('All failed jobs deleted successfully.')\n return 0\n })\n\n define(\n 'queue:clear {connection? : The name of the queue connection to clear} {--queue= : The name of the queue to clear} {--force : Force the operation to run when in production}',\n 'Delete all of the jobs from the specified queue',\n async (out) => {\n if (!confirmToProceed(out)) return 1\n const connection = text(out.argument('connection')) ?? defaultConnection()\n const queue = text(out.option('queue')) ?? defaultQueue(connection)\n const count = await container.make(QueueManager).connection(connection).clear(queue)\n out.info(`Cleared ${count} ${Str.plural('job', count)} from the [${queue}] queue`)\n return 0\n },\n )\n\n async function retryableIds(ids: string[], queue: string | undefined): Promise<string[]> {\n if (ids.length === 1 && ids[0] === 'all') return (await failer().all()).map((job) => job.id)\n if (queue !== undefined) return (await failer().all()).filter((job) => job.queue === queue).map((job) => job.id)\n return [...new Set(ids)]\n }\n\n /**\n * Pushes the payload back with attempts reset and retryUntil recomputed (Laravel's RetryCommand unserializes the\n * command with its data before recomputing retryUntil, rather than a bare instance). The stored value is kept\n * when the job can't be restored (a missing model or a class no longer in the ClassRegistry).\n */\n async function retryJob(job: FailedJob): Promise<void> {\n const payload: QueueJobPayload = { ...(job.payload as QueueJobPayload), attempts: 0 }\n if (payload.retryUntil !== undefined) {\n try {\n const restored = (await restoreJob(payload, container.make(ClassRegistry))) as unknown as { retryUntil?: () => unknown }\n const retryUntil = restored.retryUntil?.()\n if (retryUntil instanceof Date) payload.retryUntil = retryUntil.getTime()\n else if (typeof retryUntil === 'number') payload.retryUntil = retryUntil\n } catch {\n // keep the stored value when the job can't be restored\n }\n }\n await container.make(QueueManager).connection(job.connection).pushRaw(payload, job.queue)\n }\n}\n","/**\n * Laravel 11's config/queue.php defaults (without env() lookups, which belong in the app's config/queue.ts).\n * `connection`/`database` left undefined mean \"the default database connection\".\n */\nexport function queueConfigDefaults(): Record<string, unknown> {\n return {\n default: 'database',\n connections: {\n sync: { driver: 'sync' },\n database: { driver: 'database', connection: undefined, table: 'jobs', queue: 'default', retry_after: 90, after_commit: false },\n redis: { driver: 'redis', connection: 'default', queue: 'default', retry_after: 90, block_for: null, after_commit: false },\n },\n batching: { database: undefined, table: 'job_batches' },\n failed: { driver: 'database-uuids', database: undefined, table: 'failed_jobs' },\n }\n}\n","import { QueueManager } from '@orieljs/contracts'\nimport { facade } from '@orieljs/support'\n\n/** `Queue.push(job)`, `Queue.connection('redis').size()`, … on the bound QueueManager. */\nexport const Queue = facade(QueueManager)\n","import {\n BatchRepository,\n ConfigRepository,\n ConsoleKernel,\n DatabaseManager,\n FailedJobProvider,\n QueueManager as QueueManagerToken,\n type Container,\n type FailedJobProvider as FailedJobProviderContract,\n} from '@orieljs/contracts'\nimport { ServiceProvider } from '@orieljs/support'\nimport { DatabaseBatchRepository } from './batching/DatabaseBatchRepository'\nimport { registerQueueCommands } from './console/commands'\nimport { queueConfigDefaults } from './config'\nimport { UnknownQueueDriverError } from './errors'\nimport { DatabaseFailedJobProvider } from './failed/DatabaseFailedJobProvider'\nimport { NullFailedJobProvider } from './failed/NullFailedJobProvider'\nimport { optionalString } from './payload'\nimport { QueueManager } from './QueueManager'\n\n/** Builds the provider for `queue.failed.driver`: database-uuids / database (needs DatabaseManager) or null. */\nexport function makeFailedJobProvider(container: Container): FailedJobProviderContract {\n const config = container.make(ConfigRepository)\n const driver = String(config.get('queue.failed.driver', 'database-uuids'))\n if (driver === 'null') return new NullFailedJobProvider()\n if (driver !== 'database-uuids' && driver !== 'database') throw new UnknownQueueDriverError(driver)\n if (!container.bound(DatabaseManager)) return new NullFailedJobProvider()\n const database = optionalString(config.get('queue.failed.database')) || undefined\n const table = String(config.get('queue.failed.table', 'failed_jobs'))\n return new DatabaseFailedJobProvider(() => container.make(DatabaseManager).connection(database), table)\n}\n\nexport class QueueServiceProvider extends ServiceProvider {\n override register(): void {\n this.mergeConfigFrom(queueConfigDefaults(), 'queue')\n this.app.singleton(QueueManagerToken, (container) => new QueueManager(container))\n // inject(QueueManager) with the concrete class gets the same singleton, not a second manager.\n this.app.singleton(QueueManager, (container) => container.make(QueueManagerToken) as QueueManager)\n this.app.singleton(FailedJobProvider, (container) => makeFailedJobProvider(container))\n // Application providers register Database before Queue; without it, leave BatchRepository unbound so Bus\n // throws its own BatchingUnavailableError later.\n if (this.app.bound(DatabaseManager)) {\n this.app.singleton(BatchRepository, (container) => {\n const config = container.make(ConfigRepository)\n const database = optionalString(config.get('queue.batching.database')) || undefined\n const table = String(config.get('queue.batching.table', 'job_batches'))\n return new DatabaseBatchRepository(container, () => container.make(DatabaseManager).connection(database), table)\n })\n }\n }\n\n override boot(): void {\n if (this.app.bound(ConsoleKernel)) registerQueueCommands(this.app.make(ConsoleKernel), { app: this.app, container: this.app })\n }\n}\n","import {\n CurrentRoute,\n UrlGenerator,\n ViewFactory,\n type Class,\n type Container,\n type ControllerAction,\n type HttpRequest,\n type MiddlewareClass,\n type MiddlewareReference,\n type ResourceOptions,\n type RouteAction,\n type RouteClosure,\n type Router,\n} from '@orieljs/contracts'\nimport { currentContainer } from '@orieljs/container'\nimport { dispatchRoute } from './dispatch'\nimport { RoutingError } from './errors'\nimport { ALL_VERBS, GroupRegistrar, mergeGroup, type GroupAttributes } from './GroupRegistrar'\nimport { resourceRoutes } from './resource'\nimport { compareRoutes, RouteDefinition, type RouteHandler } from './RouteDefinition'\n\nexport type RouteBinder = (value: string) => unknown | Promise<unknown>\n\n/** Laravel's Illuminate\\Routing\\Router: registration, groups, patterns, bindings, middleware aliases/groups and dispatch. */\nexport class BaseRouter implements Router {\n readonly #routes: RouteDefinition[] = []\n #sorted: RouteDefinition[] | undefined\n readonly #groupStack: GroupAttributes[] = []\n readonly #patterns: Record<string, string> = {}\n #patternVersion = 0\n readonly #aliases: Record<string, MiddlewareClass> = {}\n readonly #groups: Record<string, MiddlewareReference[]> = { web: [], api: [] }\n readonly #binders = new Map<string, RouteBinder>()\n readonly #models = new Map<string, Class<unknown>>()\n\n /** `container` is the application; request-time lookups use the current (request) container first. */\n constructor(protected readonly container?: Container) {}\n\n get<C>(uri: string, action: ControllerAction<C> | RouteClosure | string): RouteDefinition {\n return this.addRoute(['GET', 'HEAD'], uri, action)\n }\n\n post<C>(uri: string, action: ControllerAction<C> | RouteClosure | string): RouteDefinition {\n return this.addRoute(['POST'], uri, action)\n }\n\n put<C>(uri: string, action: ControllerAction<C> | RouteClosure | string): RouteDefinition {\n return this.addRoute(['PUT'], uri, action)\n }\n\n patch<C>(uri: string, action: ControllerAction<C> | RouteClosure | string): RouteDefinition {\n return this.addRoute(['PATCH'], uri, action)\n }\n\n delete<C>(uri: string, action: ControllerAction<C> | RouteClosure | string): RouteDefinition {\n return this.addRoute(['DELETE'], uri, action)\n }\n\n options<C>(uri: string, action: ControllerAction<C> | RouteClosure | string): RouteDefinition {\n return this.addRoute(['OPTIONS'], uri, action)\n }\n\n any<C>(uri: string, action: ControllerAction<C> | RouteClosure | string): RouteDefinition {\n return this.addRoute(ALL_VERBS, uri, action)\n }\n\n match<C>(methods: string[], uri: string, action: ControllerAction<C> | RouteClosure | string): RouteDefinition {\n return this.addRoute(methods, uri, action)\n }\n\n /** Registers a route with the current group's prefix, name prefix, middleware and controller. GET implies HEAD. */\n addRoute(methods: readonly string[], uri: string, action: RouteHandler, options: { fallback?: boolean } = {}): RouteDefinition {\n const group = this.#groupStack.at(-1) ?? {}\n const verbs = methods.map((method) => method.toUpperCase())\n if (verbs.includes('GET') && !verbs.includes('HEAD')) verbs.push('HEAD')\n if (typeof action === 'string' && group.controller === undefined) {\n throw new RoutingError(\n `Route action [${action}] needs a controller. Use Route.controller(X).group(...) or pass [Controller, '${action}'].`,\n )\n }\n const prefix = (group.prefix ?? '').replace(/^\\/+|\\/+$/g, '')\n const path = uri.replace(/^\\/+|\\/+$/g, '')\n const route = new RouteDefinition(verbs, [prefix, path].filter((part) => part !== '').join('/'), action, {\n ...(group.as !== undefined && { namePrefix: group.as }),\n ...(group.middleware !== undefined && { middleware: group.middleware }),\n ...(group.controller !== undefined && { controller: group.controller }),\n ...(options.fallback === true && { fallback: true }),\n })\n this.#routes.push(route)\n this.#sorted = undefined\n return route\n }\n\n /** Route.redirect('/here', '/there'): any verb, 302 by default; '{param}' in the target is filled from the URI. */\n redirect(from: string, to: string, status = 302): RouteDefinition {\n const holder: { route?: RouteDefinition } = {}\n const action = (...values: unknown[]) => {\n const parameters = new Map(holder.route!.parameters.map((parameter, index) => [parameter.name, values[index]]))\n const target = to.replace(/\\{(\\w+)\\??\\}/g, (_match, name: string) => {\n const value = parameters.get(name)\n return value === undefined || value === null ? '' : encodeURIComponent(String(value))\n })\n const container = currentContainer() ?? this.container\n const location = container?.bound(UrlGenerator) ? container.make(UrlGenerator).to(target) : target\n return new Response(null, { status, headers: { Location: location } })\n }\n holder.route = this.any(from, action)\n return holder.route\n }\n\n permanentRedirect(from: string, to: string): RouteDefinition {\n return this.redirect(from, to, 301)\n }\n\n /** Route.view('/about', 'pages.about', data): GET/HEAD; route parameters are merged into the view data. */\n view(uri: string, view: string, data: Record<string, unknown> = {}): RouteDefinition {\n const holder: { route?: RouteDefinition } = {}\n const action = (...values: unknown[]) => {\n const parameters = Object.fromEntries(holder.route!.parameters.map((parameter, index) => [parameter.name, values[index]]))\n const container = currentContainer() ?? this.container\n if (container === undefined) throw new RoutingError(`Cannot render view [${view}]: no container is available.`)\n return container.make(ViewFactory).make(view, { ...data, ...parameters })\n }\n holder.route = this.addRoute(['GET', 'HEAD'], uri, action)\n return holder.route\n }\n\n resource(name: string, controller: Class<unknown>, options: ResourceOptions = {}): void {\n this.#registerResource(name, controller, options, false)\n }\n\n apiResource(name: string, controller: Class<unknown>, options: ResourceOptions = {}): void {\n this.#registerResource(name, controller, options, true)\n }\n\n /** Matches any GET path no other route matches. Always tried last. */\n fallback(action: RouteAction): RouteDefinition {\n return this.addRoute(['GET', 'HEAD'], '{fallbackPlaceholder}', action, { fallback: true })\n }\n\n prefix(prefix: string): GroupRegistrar {\n return new GroupRegistrar(this).prefix(prefix)\n }\n\n name(prefix: string): GroupRegistrar {\n return new GroupRegistrar(this).name(prefix)\n }\n\n middleware(...middleware: MiddlewareReference[]): GroupRegistrar {\n return new GroupRegistrar(this).middleware(...middleware)\n }\n\n controller(controller: Class<unknown>): GroupRegistrar {\n return new GroupRegistrar(this).controller(controller)\n }\n\n /**\n * Laravel's Route::group(attributes, callback). A synchronous callback's attributes are popped before this\n * returns, so an unawaited group never leaks into later routes; an async callback keeps them until it settles.\n */\n group(attributes: GroupAttributes, routes: () => void | Promise<void>): Promise<void> {\n const entry = mergeGroup(this.#groupStack.at(-1) ?? {}, attributes)\n this.#groupStack.push(entry)\n const pop = () => {\n const index = this.#groupStack.lastIndexOf(entry)\n if (index !== -1) this.#groupStack.splice(index, 1)\n }\n let result: void | Promise<void>\n try {\n result = routes()\n } catch (error) {\n pop()\n throw error\n }\n if (result instanceof Promise) return result.finally(pop)\n pop()\n return Promise.resolve()\n }\n\n model(parameter: string, model: Class<unknown>): void {\n this.#models.set(parameter, model)\n }\n\n bind(parameter: string, resolver: RouteBinder): void {\n this.#binders.set(parameter, resolver)\n }\n\n pattern(parameter: string, pattern: string): void {\n this.#patterns[parameter] = pattern\n this.#patternVersion++\n }\n\n patterns(patterns: Record<string, string>): void {\n for (const [parameter, pattern] of Object.entries(patterns)) this.pattern(parameter, pattern)\n }\n\n getPatterns(): Readonly<Record<string, string>> {\n return { ...this.#patterns }\n }\n\n /** Bumped by pattern(); routes recompile their matcher when it changes. */\n getPatternVersion(): number {\n return this.#patternVersion\n }\n\n getBinder(parameter: string): RouteBinder | undefined {\n return this.#binders.get(parameter)\n }\n\n getModel(parameter: string): Class<unknown> | undefined {\n return this.#models.get(parameter)\n }\n\n aliasMiddleware(name: string, middleware: MiddlewareClass): this {\n this.#aliases[name] = middleware\n return this\n }\n\n /** The middleware aliases (Laravel's Router::getMiddleware()). */\n getMiddleware(): Record<string, MiddlewareClass> {\n return { ...this.#aliases }\n }\n\n middlewareGroup(name: string, middleware: MiddlewareReference[]): this {\n this.#groups[name] = [...middleware]\n return this\n }\n\n pushMiddlewareToGroup(group: string, middleware: MiddlewareReference): this {\n const list = (this.#groups[group] ??= [])\n if (!list.includes(middleware)) list.push(middleware)\n return this\n }\n\n prependMiddlewareToGroup(group: string, middleware: MiddlewareReference): this {\n const list = (this.#groups[group] ??= [])\n if (!list.includes(middleware)) list.unshift(middleware)\n return this\n }\n\n hasMiddlewareGroup(name: string): boolean {\n return Object.hasOwn(this.#groups, name)\n }\n\n getMiddlewareGroups(): Record<string, MiddlewareReference[]> {\n return Object.fromEntries(Object.entries(this.#groups).map(([name, list]) => [name, [...list]]))\n }\n\n /** Every route, in registration order. */\n getRoutes(): readonly RouteDefinition[] {\n return [...this.#routes]\n }\n\n /** Routes in matching order: static segments first, fallbacks last (cached until a route is added). */\n getRoutesByMatchOrder(): readonly RouteDefinition[] {\n return (this.#sorted ??= [...this.#routes].sort(compareRoutes))\n }\n\n /** The last route registered with this name wins, as in Laravel. */\n getByName(name: string): RouteDefinition | undefined {\n return this.#routes.findLast((route) => route.getName() === name)\n }\n\n has(...names: string[]): boolean {\n return names.every((name) => this.getByName(name) !== undefined)\n }\n\n /** The route matched for the current request (read from the request scope). */\n current(): RouteDefinition | undefined {\n const container = currentContainer()\n if (container === undefined || !container.bound(CurrentRoute)) return undefined\n return container.make(CurrentRoute).route as RouteDefinition\n }\n\n currentRouteName(): string | undefined {\n return this.current()?.getName()\n }\n\n /** Match, bind and run the route middleware and action (Router.dispatch; called by the Http kernel). */\n dispatch(request: HttpRequest): Promise<Response> {\n return dispatchRoute(this, request, this.container)\n }\n\n #registerResource(name: string, controller: Class<unknown>, options: ResourceOptions, api: boolean): void {\n for (const entry of resourceRoutes(name, options, api)) {\n this.addRoute(entry.verbs, entry.uri, [controller, entry.method] as RouteAction).name(entry.name)\n }\n }\n}\n","import { CurrentRoute, type Class, type Container, type HttpRequest, type OrielError } from '@orieljs/contracts'\nimport { currentContainer } from '@orieljs/container'\nimport type { BaseRouter } from './BaseRouter'\nimport { orderForBindings, substituteBindings } from './bindings'\nimport { MethodNotAllowedHttpError, NotFoundHttpError, RoutingError } from './errors'\nimport { resolveMiddleware, runMiddleware } from './middleware'\nimport { normalizePath, type RouteDefinition } from './RouteDefinition'\n\n/** [Controller, 'missing'] (Laravel's BadMethodCallException). */\nexport class ControllerMethodNotFoundError extends Error implements OrielError {\n readonly kind = 'Server' as const\n readonly status = 500\n override readonly name = 'ControllerMethodNotFoundError'\n constructor(controller: string, method: string) {\n super(`Method ${controller}::${method} does not exist.`)\n }\n}\n\n// Duplicated in Pipeline's BasePipeline.ts on purpose: Http, Routing and Pipeline may not import each other.\nconst isClass = (value: unknown): value is Class<object> =>\n typeof value === 'function' && /^class[\\s{]/.test(Function.prototype.toString.call(value))\n\ntype Match = { route: RouteDefinition; values: Record<string, string | undefined> } | { response: Response }\n\nfunction findRoute(router: BaseRouter, request: HttpRequest): Match {\n const method = request.method().toUpperCase()\n const path = normalizePath(new URL(request.raw.url).pathname)\n const patterns = router.getPatterns()\n const version = router.getPatternVersion()\n const allowed = new Set<string>()\n for (const route of router.getRoutesByMatchOrder()) {\n const values = route.match(path, patterns, version)\n if (values === undefined) continue\n if (route.methods.includes(method)) return { route, values }\n // A fallback never turns an unknown POST into a 405.\n if (!route.isFallback) for (const verb of route.methods) allowed.add(verb)\n }\n if (allowed.size > 0) {\n // Laravel's automatic OPTIONS response.\n if (method === 'OPTIONS') return { response: new Response(null, { status: 200, headers: { Allow: [...allowed].join(', ') } }) }\n throw new MethodNotAllowedHttpError(method, request.path(), [...allowed])\n }\n throw new NotFoundHttpError(request.path())\n}\n\n/** Calls the route action with the parameters in URI order. Controllers are built by the request scope. */\nasync function runAction(scope: Container, route: RouteDefinition, parameters: Record<string, unknown>): Promise<unknown> {\n const args = route.parameters.map((parameter) => parameters[parameter.name])\n const action = route.action\n if (typeof action === 'function' && !isClass(action)) return (action as (...values: unknown[]) => unknown)(...args)\n const [cls, method] =\n typeof action === 'string'\n ? [route.controller as Class<object>, action]\n : isClass(action)\n ? [action, '__invoke']\n : [action[0] as Class<object>, String(action[1])]\n const controller = scope.make(cls) as Record<string, unknown>\n const handler = controller[method]\n if (typeof handler !== 'function') throw new ControllerMethodNotFoundError(cls.name, method)\n return (handler as (...values: unknown[]) => unknown).apply(controller, args)\n}\n\n/**\n * Router::dispatch: match, record the current route in the request scope, then run the route middleware and the\n * action. Matching errors (404/405) are thrown for the kernel's stage to render.\n */\nexport async function dispatchRoute(router: BaseRouter, request: HttpRequest, container?: Container): Promise<Response> {\n const scope = currentContainer() ?? container\n if (scope === undefined) throw new RoutingError('Cannot dispatch a request: no container is available.')\n const match = findRoute(router, request)\n if ('response' in match) return match.response\n const { route, values } = match\n\n const state: CurrentRoute = { route, parameters: { ...values }, middleware: [] }\n scope.instance(CurrentRoute, state)\n\n const middleware = resolveMiddleware(\n route.gatherMiddleware(),\n route.excludedMiddleware(),\n router.getMiddleware(),\n router.getMiddlewareGroups(),\n )\n const ordered = orderForBindings(router, middleware)\n return runMiddleware(scope, request, ordered.middleware, state.middleware, () => runAction(scope, route, state.parameters), {\n at: ordered.at,\n run: async () => void Object.assign(state.parameters, await substituteBindings(router, route, values, scope)),\n })\n}\n","import { RouteModelResolver, type Container, type MiddlewareClass } from '@orieljs/contracts'\nimport { BindingResolutionError } from '@orieljs/container'\nimport { Str } from '@orieljs/support'\nimport type { BaseRouter } from './BaseRouter'\nimport { RouteModelNotFoundError } from './errors'\nimport { resolveMiddleware, type ResolvedMiddleware } from './middleware'\nimport type { RouteDefinition } from './RouteDefinition'\n\n/**\n * Laravel's $middlewarePriority around SubstituteBindings: the `web`/`api` group middleware and the `auth`/`guest`\n * aliases run before binding, every other route middleware after it (so `can:` sees the models, and a guest is\n * redirected before any lookup). Returns the middleware in that order (stable within each part) and the index\n * where the binding stage runs.\n */\nexport function orderForBindings(\n router: BaseRouter,\n middleware: readonly ResolvedMiddleware[],\n): { middleware: ResolvedMiddleware[]; at: number } {\n const aliases = router.getMiddleware()\n const groups = router.getMiddlewareGroups()\n const early = new Set<MiddlewareClass>()\n for (const name of ['auth', 'guest']) if (Object.hasOwn(aliases, name)) early.add(aliases[name]!)\n for (const group of ['web', 'api']) {\n try {\n for (const entry of resolveMiddleware([group], [], aliases, groups)) early.add(entry.cls)\n } catch {\n // A group naming an unknown alias fails the routes that use it, when they resolve their middleware.\n }\n }\n const before = middleware.filter((entry) => early.has(entry.cls))\n const after = middleware.filter((entry) => !early.has(entry.cls))\n return { middleware: [...before, ...after], at: before.length }\n}\n\n/**\n * Laravel's SubstituteBindings, run as a route stage (see orderForBindings), in URI order:\n * 1. Route.bind(name, fn): the callback's result, whatever it is\n * 2. Route.model(name, Model): RouteModelResolver.resolveExplicit(); nothing found → 404\n * 3. implicit: RouteModelResolver.resolve(name, value, field); undefined keeps the string, null → 404\n * Missing optional parameters stay undefined. Without a resolver, implicit binding is skipped.\n */\nexport async function substituteBindings(\n router: BaseRouter,\n route: RouteDefinition,\n values: Readonly<Record<string, string | undefined>>,\n container: Container,\n): Promise<Record<string, unknown>> {\n const resolver = container.bound(RouteModelResolver) ? container.make(RouteModelResolver) : undefined\n const bound: Record<string, unknown> = {}\n for (const { name, field } of route.parameters) {\n const value = values[name]\n if (value === undefined) {\n bound[name] = undefined\n continue\n }\n const binder = router.getBinder(name)\n if (binder !== undefined) {\n bound[name] = await binder(value)\n continue\n }\n const model = router.getModel(name)\n if (model !== undefined) {\n if (resolver === undefined) {\n throw new BindingResolutionError(\n `Route.model('${name}', ${model.name}) needs a RouteModelResolver. Is the Database service provider registered?`,\n )\n }\n const found = await resolver.resolveExplicit(model, value, field)\n if (found === null || found === undefined) throw new RouteModelNotFoundError(model.name, value)\n bound[name] = found\n continue\n }\n if (resolver !== undefined) {\n const found = await resolver.resolve(name, value, field)\n if (found === null) throw new RouteModelNotFoundError(Str.studly(name), value)\n bound[name] = found === undefined ? value : found\n continue\n }\n bound[name] = value\n }\n return bound\n}\n","import type { ModelNotFoundError, OrielError } from '@orieljs/contracts'\n\n/** No route matches the path (Symfony's NotFoundHttpException). */\nexport class NotFoundHttpError extends Error implements OrielError {\n readonly kind = 'Http' as const\n readonly status = 404\n override readonly name = 'NotFoundHttpError'\n constructor(path: string) {\n super(`The route ${path} could not be found.`)\n }\n}\n\n/** The path exists, but not for this method. */\nexport class MethodNotAllowedHttpError extends Error implements OrielError {\n readonly kind = 'Http' as const\n readonly status = 405\n readonly headers: Record<string, string>\n override readonly name = 'MethodNotAllowedHttpError'\n constructor(method: string, path: string, allowed: string[]) {\n super(`The ${method} method is not supported for route ${path}. Supported methods: ${allowed.join(', ')}.`)\n this.headers = { Allow: allowed.join(', ') }\n }\n}\n\n/** route('x') for a name no route has (Symfony's RouteNotFoundException). */\nexport class RouteNotDefinedError extends Error implements OrielError {\n readonly kind = 'Server' as const\n readonly status = 500\n override readonly name = 'RouteNotDefinedError'\n constructor(readonly routeName: string) {\n super(`Route [${routeName}] not defined.`)\n }\n}\n\n/** route('posts.show') without a required parameter. */\nexport class UrlGenerationError extends Error implements OrielError {\n readonly kind = 'Server' as const\n readonly status = 500\n override readonly name = 'UrlGenerationError'\n constructor(routeName: string, uri: string, missing: string[]) {\n super(`Missing required parameter for [Route: ${routeName}] [URI: ${uri}] [Missing parameter: ${missing.join(', ')}].`)\n }\n}\n\n/** Thrown by the router when a binding finds no row, so a missing model is always a 404. */\nexport class RouteModelNotFoundError extends Error implements ModelNotFoundError {\n readonly kind = 'ModelNotFound' as const\n readonly status = 404\n readonly ids: unknown[]\n override readonly name = 'RouteModelNotFoundError'\n constructor(readonly model: string, value: unknown) {\n super(`No query results for model [${model}] ${String(value)}`)\n this.ids = [value]\n }\n}\n\n/** Internal routing failures (a string action with no controller, a view route with no container, etc). */\nexport class RoutingError extends Error implements OrielError {\n readonly kind = 'Server' as const\n readonly status = 500\n override readonly name = 'RoutingError'\n}\n","import {\n ExceptionHandler,\n PipelineFactory,\n type Container,\n type HttpRequest,\n type Middleware,\n type MiddlewareClass,\n type MiddlewareReference,\n type OrielError,\n} from '@orieljs/contracts'\nimport { RoutingError } from './errors'\nimport { toResponse } from './toResponse'\n\n/** A middleware reference after alias and group expansion: 'throttle:60,1' → { cls: Throttle, parameters: ['60', '1'] }. */\nexport interface ResolvedMiddleware {\n readonly cls: MiddlewareClass\n readonly parameters: readonly string[]\n}\n\n/** A string middleware that is neither an alias nor a group. */\nexport class MiddlewareNotFoundError extends Error implements OrielError {\n readonly kind = 'Server' as const\n readonly status = 500\n override readonly name = 'MiddlewareNotFoundError'\n constructor(readonly middleware: string) {\n super(\n `Middleware [${middleware}] is not defined. Register it with Route.aliasMiddleware() or ` +\n `withMiddleware((m) => m.alias({ ... })).`,\n )\n }\n}\n\nfunction expand(\n references: readonly MiddlewareReference[],\n aliases: Readonly<Record<string, MiddlewareClass>>,\n groups: Readonly<Record<string, readonly MiddlewareReference[]>>,\n visiting: Set<string>,\n out: ResolvedMiddleware[],\n): void {\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 const parameters = index === -1 ? [] : reference.slice(index + 1).split(',')\n if (index === -1 && Object.hasOwn(groups, name)) {\n if (visiting.has(name)) throw new RoutingError(`Middleware group [${name}] includes itself.`)\n visiting.add(name)\n expand(groups[name]!, aliases, groups, visiting, out)\n visiting.delete(name)\n continue\n }\n if (!Object.hasOwn(aliases, name)) throw new MiddlewareNotFoundError(reference)\n out.push({ cls: aliases[name]!, parameters })\n }\n}\n\n/**\n * Expands aliases and groups (recursively), drops anything `excluded` resolves to (withoutMiddleware), and\n * removes duplicates (same class and parameters), keeping the first occurrence like Laravel's uniqueMiddleware.\n */\nexport function resolveMiddleware(\n references: readonly MiddlewareReference[],\n excluded: readonly MiddlewareReference[],\n aliases: Readonly<Record<string, MiddlewareClass>>,\n groups: Readonly<Record<string, readonly MiddlewareReference[]>>,\n): ResolvedMiddleware[] {\n const all: ResolvedMiddleware[] = []\n expand(references, aliases, groups, new Set(), all)\n const skipped: ResolvedMiddleware[] = []\n expand(excluded, aliases, groups, new Set(), skipped)\n const skippedClasses = new Set(skipped.map((entry) => entry.cls))\n const seen = new Set<string>()\n const classIds = new Map<MiddlewareClass, number>()\n return all.filter((entry) => {\n if (skippedClasses.has(entry.cls)) return false\n if (!classIds.has(entry.cls)) classIds.set(entry.cls, classIds.size)\n const key = `${classIds.get(entry.cls)}:${entry.parameters.join(',')}`\n if (seen.has(key)) return false\n seen.add(key)\n return true\n })\n}\n\n/**\n * Renders an error as a Response through the bound ExceptionHandler (reporting it first), like Laravel's\n * Routing\\Pipeline::handleException. Without a handler the error is rethrown.\n */\nexport async function renderError(container: Container, request: HttpRequest, error: unknown): Promise<Response> {\n if (!container.bound(ExceptionHandler)) throw error\n const handler = container.make(ExceptionHandler)\n await handler.report(error)\n return handler.render(request, error)\n}\n\nasync function guard(container: Container, request: HttpRequest, run: () => Promise<unknown>): Promise<Response> {\n try {\n const result = await run()\n return result instanceof Response ? result : await toResponse(request, result)\n } catch (error) {\n return renderError(container, request, error)\n }\n}\n\n/** An extra pipeline stage that runs before `middleware[at]` (route model binding uses it). */\nexport interface RouteStage {\n readonly at: number\n run(request: HttpRequest): Promise<void>\n}\n\ntype RoutePipe = (passable: HttpRequest, next: (passable: HttpRequest) => Promise<unknown>) => Promise<Response>\n\n/**\n * Sends the request through the middleware (built from `container`, the request scope) to `destination`.\n * Every stage converts its own errors into a response, so outer middleware always get a Response back.\n * Built instances are pushed onto `instances` (for terminate()). `stage`, when given, runs at its position.\n */\nexport async function runMiddleware(\n container: Container,\n request: HttpRequest,\n middleware: readonly ResolvedMiddleware[],\n instances: Middleware[],\n destination: (request: HttpRequest) => Promise<unknown>,\n stage?: RouteStage,\n): Promise<Response> {\n const pipes: RoutePipe[] = middleware.map(({ cls, parameters }) => {\n const instance = container.make(cls)\n instances.push(instance)\n return (passable, next) =>\n guard(container, passable, () => instance.handle(passable, next as (r: HttpRequest) => Promise<Response>, ...parameters))\n })\n if (stage !== undefined) {\n pipes.splice(stage.at, 0, (passable, next) =>\n guard(container, passable, async () => {\n await stage.run(passable)\n return next(passable)\n }),\n )\n }\n return container\n .make(PipelineFactory)\n .make<HttpRequest>()\n .send(request)\n .through(pipes)\n .then((passable) => guard(container, passable, () => destination(passable)))\n}\n","/** Laravel's Router::toResponse: turns whatever an action returned into a Response. */\nexport async function toResponse(request: unknown, value: unknown): Promise<Response> {\n if (value instanceof Response) return value\n if (value === null || value === undefined) return new Response(null, { status: 204 })\n if (typeof value === 'string') return html(value)\n if (typeof value !== 'object') return html(String(value))\n\n const candidate = value as Record<string, unknown>\n // Responsable (redirects, Inertia responses, …)\n if (typeof candidate.toResponse === 'function') {\n return toResponse(request, await (candidate.toResponse as (request: unknown) => unknown).call(value, request))\n }\n // Renderable (a View from ViewFactory.make())\n if (typeof candidate.render === 'function') return html(String(await (candidate.render as () => unknown).call(value)))\n // Htmlable\n if (typeof candidate.toHtml === 'function') return html(String((candidate.toHtml as () => unknown).call(value)))\n if (typeof candidate.toJSON !== 'function') {\n // Jsonable, then Arrayable\n if (typeof candidate.toJson === 'function') return json(String((candidate.toJson as () => unknown).call(value)))\n if (typeof candidate.toArray === 'function') return json(JSON.stringify((candidate.toArray as () => unknown).call(value)))\n }\n // Plain objects, arrays, models and collections (via toJSON)\n return json(JSON.stringify(value))\n}\n\nfunction html(body: string): Response {\n return new Response(body, { headers: { 'content-type': 'text/html; charset=utf-8' } })\n}\n\n/** Explicit header: Response.json() says 'application/json' on Node but adds ';charset=utf-8' on Bun. */\nfunction json(body: string): Response {\n return new Response(body, { headers: { 'content-type': 'application/json' } })\n}\n","import type { Class, MiddlewareReference, Route, RouteAction } from '@orieljs/contracts'\n\n/** A closure, a [Controller, 'method'] tuple, or a method name inside Route.controller(X).group(). */\nexport type RouteHandler = RouteAction | string\n\nexport interface RouteAttributes {\n /** The group's name prefix ('admin.'); name() appends to it. */\n namePrefix?: string\n /** Group middleware; the route's own middleware() is appended after it. */\n middleware?: MiddlewareReference[]\n /** The group controller that string actions call. */\n controller?: Class<unknown>\n fallback?: boolean\n}\n\nexport interface UriParameter {\n readonly name: string\n readonly optional: boolean\n /** The binding column from '{post:slug}'. */\n readonly field: string | undefined\n}\n\n/** Exported for the URL generator, which reuses these instead of redeclaring them. */\nexport const PARAMETER = /\\{(\\w+)(?::(\\w+))?(\\?)?\\}/g\nexport const WHOLE_OPTIONAL = /^\\{(\\w+)(?::\\w+)?\\?\\}$/\nconst escapeRegex = (value: string) => value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n\nexport function parseParameters(uri: string): UriParameter[] {\n return [...uri.matchAll(PARAMETER)].map((match) => ({ name: match[1]!, optional: match[3] === '?', field: match[2] }))\n}\n\n/** Laravel stores URIs without surrounding slashes, and '/' for the root. */\nexport function normalizeUri(uri: string): string {\n const trimmed = uri.replace(/^\\/+|\\/+$/g, '')\n return trimmed === '' ? '/' : trimmed\n}\n\n/** The form compiled patterns match against: '/posts/1/' → '/posts/1', '/' → ''. */\nexport function normalizePath(pathname: string): string {\n const trimmed = pathname.replace(/^\\/+|\\/+$/g, '').replace(/\\/{2,}/g, '/')\n return trimmed === '' ? '' : `/${trimmed}`\n}\n\nfunction decode(value: string): string {\n try {\n return decodeURIComponent(value)\n } catch {\n return value\n }\n}\n\n/** The pattern body (no anchors) for a normalised uri; '' for the root. */\nfunction compileBody(uri: string, wheres: Readonly<Record<string, string>>): string {\n if (uri === '/') return ''\n const group = (name: string) => `(?<p_${name}>${wheres[name] ?? '[^/]+'})`\n let body = ''\n for (const segment of uri.split('/')) {\n const whole = WHOLE_OPTIONAL.exec(segment)\n if (whole) {\n body += `(?:/${group(whole[1]!)})?`\n continue\n }\n let piece = ''\n let last = 0\n for (const match of segment.matchAll(PARAMETER)) {\n piece += escapeRegex(segment.slice(last, match.index)) + group(match[1]!) + (match[3] === '?' ? '?' : '')\n last = match.index + match[0].length\n }\n body += `/${piece}${escapeRegex(segment.slice(last))}`\n }\n return body\n}\n\nconst FALLBACK_SEGMENT = '{fallbackPlaceholder}'\n\n/**\n * Laravel's fallback is '{fallbackPlaceholder}' with where('.*') under the group prefix, so it stays scoped to it:\n * 'api/{fallbackPlaceholder}' matches /api and /api/any/depth but not /about; at the root it matches every path.\n */\nfunction compileFallback(uri: string, wheres: Readonly<Record<string, string>>): RegExp {\n const tail = '(?:/(?<p_fallbackPlaceholder>.*))?'\n if (uri === FALLBACK_SEGMENT) return new RegExp(`^${tail}$`, 's')\n if (!uri.endsWith(`/${FALLBACK_SEGMENT}`)) return new RegExp(`^${compileBody(uri, { ...wheres, fallbackPlaceholder: '.*' })}$`, 's')\n return new RegExp(`^${compileBody(uri.slice(0, -FALLBACK_SEGMENT.length - 1), wheres)}${tail}$`, 's')\n}\n\n/** Sort order for matching: fallbacks last, then per-segment specificity; ties keep registration order. */\nexport function compareRoutes(a: RouteDefinition, b: RouteDefinition): number {\n if (a.isFallback !== b.isFallback) return a.isFallback ? 1 : -1\n const left = a.rank()\n const right = b.rank()\n for (let i = 0; i < Math.max(left.length, right.length); i++) {\n const x = left[i] ?? -1\n const y = right[i] ?? -1\n if (x !== y) return x - y\n }\n return 0\n}\n\nexport class RouteDefinition implements Route {\n readonly methods: readonly string[]\n readonly uri: string\n readonly action: RouteHandler\n readonly controller: Class<unknown> | undefined\n readonly isFallback: boolean\n readonly parameters: readonly UriParameter[]\n #name: string | undefined\n readonly #middleware: MiddlewareReference[]\n readonly #excluded: MiddlewareReference[] = []\n readonly #wheres: Record<string, string> = {}\n #compiled: { regex: RegExp; version: number } | undefined\n\n constructor(methods: readonly string[], uri: string, action: RouteHandler, attributes: RouteAttributes = {}) {\n this.methods = [...new Set(methods.map((method) => method.toUpperCase()))]\n this.uri = normalizeUri(uri)\n this.action = action\n this.controller = attributes.controller\n this.isFallback = attributes.fallback ?? false\n this.parameters = parseParameters(this.uri)\n this.#name = attributes.namePrefix === undefined || attributes.namePrefix === '' ? undefined : attributes.namePrefix\n this.#middleware = [...(attributes.middleware ?? [])]\n }\n\n getName(): string | undefined {\n return this.#name\n }\n\n /** Appends, like Laravel's $action['as'] .= $name. */\n name(name: string): this {\n this.#name = (this.#name ?? '') + name\n return this\n }\n\n middleware(...middleware: MiddlewareReference[]): this {\n this.#middleware.push(...middleware.flat())\n return this\n }\n\n withoutMiddleware(...middleware: MiddlewareReference[]): this {\n this.#excluded.push(...middleware.flat())\n return this\n }\n\n where(parameter: string | Record<string, string>, pattern?: string): this {\n if (typeof parameter === 'string') this.#wheres[parameter] = pattern ?? '[^/]+'\n else Object.assign(this.#wheres, parameter)\n this.#compiled = undefined\n return this\n }\n\n gatherMiddleware(): MiddlewareReference[] {\n return [...this.#middleware]\n }\n\n excludedMiddleware(): MiddlewareReference[] {\n return [...this.#excluded]\n }\n\n wheres(): Record<string, string> {\n return { ...this.#wheres }\n }\n\n getActionName(): string {\n if (typeof this.action === 'string') return `${this.controller?.name ?? 'Controller'}@${this.action}`\n if (Array.isArray(this.action)) return `${(this.action[0] as Class<unknown>).name}@${String(this.action[1])}`\n return 'Closure'\n }\n\n /** Decoded parameter values when `path` (normalizePath output) matches, else undefined. */\n match(\n path: string,\n patterns: Readonly<Record<string, string>> = {},\n version = 0,\n ): Record<string, string | undefined> | undefined {\n const found = this.#regex(patterns, version).exec(path)\n if (found === null) return undefined\n const values: Record<string, string | undefined> = {}\n for (const { name } of this.parameters) {\n const raw = found.groups?.[`p_${name}`]\n values[name] = raw === undefined ? undefined : decode(raw)\n }\n return values\n }\n\n /** Per-segment specificity: static 0, parameter 1, optional parameter 2. Lower sorts first. */\n rank(): number[] {\n if (this.uri === '/') return []\n return this.uri.split('/').map((segment) => (WHOLE_OPTIONAL.test(segment) ? 2 : segment.includes('{') ? 1 : 0))\n }\n\n #regex(patterns: Readonly<Record<string, string>>, version: number): RegExp {\n if (this.#compiled !== undefined && this.#compiled.version === version) return this.#compiled.regex\n const wheres = { ...patterns, ...this.#wheres }\n const regex = this.isFallback ? compileFallback(this.uri, wheres) : new RegExp(`^${compileBody(this.uri, wheres)}$`)\n this.#compiled = { regex, version }\n return regex\n }\n}\n","import type { Class, ControllerAction, MiddlewareReference, ResourceOptions, RouteClosure, RouteRegistrar } from '@orieljs/contracts'\nimport type { RouteDefinition, RouteHandler } from './RouteDefinition'\n\n/** Attributes shared by the routes of a group (Laravel's group attribute array). */\nexport interface GroupAttributes {\n prefix?: string\n /** Name prefix ('admin.'). */\n as?: string\n middleware?: MiddlewareReference[]\n controller?: Class<unknown>\n}\n\n/** What a GroupRegistrar needs from the router. */\nexport interface GroupHost {\n group(attributes: GroupAttributes, routes: () => void | Promise<void>): Promise<void>\n addRoute(methods: readonly string[], uri: string, action: RouteHandler): RouteDefinition\n resource(name: string, controller: Class<unknown>, options?: ResourceOptions): void\n apiResource(name: string, controller: Class<unknown>, options?: ResourceOptions): void\n}\n\n/** Every HTTP verb a route can respond to. BaseRouter reuses this instead of redeclaring it. */\nexport const ALL_VERBS = ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS']\n\n/** Merges a nested group's attributes into its parent's, like Laravel's RouteGroup::merge. */\nexport function mergeGroup(parent: GroupAttributes, child: GroupAttributes): GroupAttributes {\n const prefix = [parent.prefix, child.prefix]\n .map((part) => (part ?? '').replace(/^\\/+|\\/+$/g, ''))\n .filter((part) => part !== '')\n .join('/')\n const merged: GroupAttributes = {\n middleware: [...(parent.middleware ?? []), ...(child.middleware ?? [])],\n }\n if (prefix !== '') merged.prefix = prefix\n const as = (parent.as ?? '') + (child.as ?? '')\n if (as !== '') merged.as = as\n const controller = child.controller ?? parent.controller\n if (controller !== undefined) merged.controller = controller\n return merged\n}\n\n/**\n * Route.prefix('admin').name('admin.').middleware('auth').group(() => …), and the one-route form\n * Route.middleware('auth').get('/x', action) (Laravel's RouteRegistrar).\n */\nexport class GroupRegistrar implements RouteRegistrar {\n readonly #attributes: GroupAttributes = {}\n\n constructor(private readonly router: GroupHost) {}\n\n prefix(prefix: string): this {\n this.#attributes.prefix = prefix\n return this\n }\n\n name(prefix: string): this {\n this.#attributes.as = prefix\n return this\n }\n\n middleware(...middleware: MiddlewareReference[]): this {\n this.#attributes.middleware = [...(this.#attributes.middleware ?? []), ...middleware.flat()]\n return this\n }\n\n controller(controller: Class<unknown>): this {\n this.#attributes.controller = controller\n return this\n }\n\n group(routes: () => void | Promise<void>): Promise<void> {\n return this.router.group({ ...this.#attributes }, routes)\n }\n\n get<C>(uri: string, action: ControllerAction<C> | RouteClosure | string): RouteDefinition {\n return this.#one(['GET', 'HEAD'], uri, action)\n }\n\n post<C>(uri: string, action: ControllerAction<C> | RouteClosure | string): RouteDefinition {\n return this.#one(['POST'], uri, action)\n }\n\n put<C>(uri: string, action: ControllerAction<C> | RouteClosure | string): RouteDefinition {\n return this.#one(['PUT'], uri, action)\n }\n\n patch<C>(uri: string, action: ControllerAction<C> | RouteClosure | string): RouteDefinition {\n return this.#one(['PATCH'], uri, action)\n }\n\n delete<C>(uri: string, action: ControllerAction<C> | RouteClosure | string): RouteDefinition {\n return this.#one(['DELETE'], uri, action)\n }\n\n options<C>(uri: string, action: ControllerAction<C> | RouteClosure | string): RouteDefinition {\n return this.#one(['OPTIONS'], uri, action)\n }\n\n any<C>(uri: string, action: ControllerAction<C> | RouteClosure | string): RouteDefinition {\n return this.#one(ALL_VERBS, uri, action)\n }\n\n match<C>(methods: string[], uri: string, action: ControllerAction<C> | RouteClosure | string): RouteDefinition {\n return this.#one(methods, uri, action)\n }\n\n resource(name: string, controller: Class<unknown>, options?: ResourceOptions): void {\n void this.router.group({ ...this.#attributes }, () => this.router.resource(name, controller, options))\n }\n\n apiResource(name: string, controller: Class<unknown>, options?: ResourceOptions): void {\n void this.router.group({ ...this.#attributes }, () => this.router.apiResource(name, controller, options))\n }\n\n #one(methods: readonly string[], uri: string, action: RouteHandler): RouteDefinition {\n let route: RouteDefinition | undefined\n void this.router.group({ ...this.#attributes }, () => {\n route = this.router.addRoute(methods, uri, action)\n })\n return route!\n }\n}\n","import type { ResourceOptions } from '@orieljs/contracts'\nimport { Str } from '@orieljs/support'\n\nexport type ResourceMethod = 'index' | 'create' | 'store' | 'show' | 'edit' | 'update' | 'destroy'\n\nexport interface ResourceRoute {\n readonly method: ResourceMethod\n readonly verbs: readonly string[]\n readonly uri: string\n readonly name: string\n}\n\n/** Laravel's order (ResourceRegistrar::$resourceDefaults). */\nconst DEFAULTS: readonly ResourceMethod[] = ['index', 'create', 'store', 'show', 'edit', 'update', 'destroy']\nconst API_DEFAULTS: readonly ResourceMethod[] = ['index', 'store', 'show', 'update', 'destroy']\n\n/** 'blog-posts' → 'blog_post' (Laravel's getResourceWildcard), unless options.parameters renames it. */\nfunction wildcard(segment: string, options: ResourceOptions): string {\n const renamed = options.parameters?.[segment]\n return (renamed ?? Str.singular(segment)).replace(/-/g, '_')\n}\n\n/**\n * The routes Route.resource()/apiResource() register. 'photos.comments' nests:\n * photos/{photo}/comments/{comment}, named photos.comments.*.\n */\nexport function resourceRoutes(name: string, options: ResourceOptions = {}, api = false): ResourceRoute[] {\n const segments = name.split('.')\n const last = segments.at(-1)!\n const base = [...segments.slice(0, -1).map((segment) => `${segment}/{${wildcard(segment, options)}}`), last].join('/')\n const member = `${base}/{${wildcard(last, options)}}`\n\n let methods = api ? API_DEFAULTS : DEFAULTS\n if (options.only !== undefined) methods = methods.filter((method) => options.only!.includes(method))\n if (options.except !== undefined) methods = methods.filter((method) => !options.except!.includes(method))\n\n const table: Record<ResourceMethod, { verbs: string[]; uri: string }> = {\n index: { verbs: ['GET', 'HEAD'], uri: base },\n create: { verbs: ['GET', 'HEAD'], uri: `${base}/create` },\n store: { verbs: ['POST'], uri: base },\n show: { verbs: ['GET', 'HEAD'], uri: member },\n edit: { verbs: ['GET', 'HEAD'], uri: `${member}/edit` },\n update: { verbs: ['PUT', 'PATCH'], uri: member },\n destroy: { verbs: ['DELETE'], uri: member },\n }\n return methods.map((method) => ({\n method,\n verbs: table[method].verbs,\n uri: table[method].uri,\n name: options.names?.[method] ?? `${name}.${method}`,\n }))\n}\n","import { ConfigRepository, HttpRequest, Session, type Container, type UrlGenerator } from '@orieljs/contracts'\nimport { currentContainer } from '@orieljs/container'\nimport type { BaseRouter } from './BaseRouter'\nimport { RouteNotDefinedError, UrlGenerationError } from './errors'\nimport { PARAMETER, WHOLE_OPTIONAL } from './RouteDefinition'\n\nconst VALID_URL = /^(#|\\/\\/|https?:\\/\\/|(mailto|tel|sms):)/i\n\n// Duplicated in Http's input.ts on purpose: Http, Routing and Pipeline may not import each other.\nconst isPlainObject = (value: unknown): value is Record<string, unknown> => {\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/** PHP's http_build_query: nested objects and arrays become a[b]=1&a[0]=2; null/undefined are skipped. */\nexport function buildQuery(values: Record<string, unknown>): string {\n const pairs: string[] = []\n const add = (key: string, value: unknown): void => {\n if (value === null || value === undefined) return\n if (typeof value === 'object' && (Array.isArray(value) || isPlainObject(value))) {\n for (const [child, nested] of Object.entries(value)) add(`${key}[${child}]`, nested)\n return\n }\n const text = value === true ? '1' : value === false ? '0' : String(value)\n pairs.push(`${encodeURIComponent(key)}=${encodeURIComponent(text)}`)\n }\n for (const [key, value] of Object.entries(values)) add(key, value)\n return pairs.join('&')\n}\n\n/** A model's URL value: the {post:slug} field when given, else getRouteKey(), else the value itself. */\nfunction routeKey(value: unknown, field: string | undefined): unknown {\n if (typeof value !== 'object' || value === null) return value\n const model = value as { getRouteKey?: () => unknown; getAttribute?: (key: string) => unknown } & Record<string, unknown>\n if (field !== undefined) return typeof model.getAttribute === 'function' ? model.getAttribute(field) : model[field]\n return typeof model.getRouteKey === 'function' ? model.getRouteKey() : value\n}\n\n/** Laravel's UrlGenerator. The root is the current request's origin, else config('app.url'). */\nexport class BaseUrlGenerator implements UrlGenerator {\n constructor(\n private readonly router: BaseRouter,\n private readonly container?: Container,\n ) {}\n\n /** 'http://localhost' (no trailing slash). */\n root(): string {\n const request = this.#request()\n if (request !== undefined) return new URL(request.url()).origin\n const configured = this.#config<string | undefined>('app.url', undefined)\n return (configured ?? 'http://localhost').replace(/\\/+$/, '')\n }\n\n to(path: string, query: Record<string, unknown> = {}, absolute = true): string {\n const queryString = buildQuery(query)\n const base = VALID_URL.test(path) ? path : this.#join(path, absolute)\n if (queryString === '') return base\n return `${base}${base.includes('?') ? '&' : '?'}${queryString}`\n }\n\n /**\n * route('posts.show', post) / route('posts.show', [post, comment]) / route('posts.show', { post: 1, page: 2 }).\n * Named values fill their parameters, positional values fill the rest in URI order; extra named values become\n * the query string, extra positional ones are dropped.\n */\n route(name: string, parameters?: unknown, absolute = true): string {\n const route = this.router.getByName(name)\n if (route === undefined) throw new RouteNotDefinedError(name)\n const named: Record<string, unknown> = isPlainObject(parameters) ? { ...parameters } : {}\n const positional: unknown[] = Array.isArray(parameters)\n ? [...parameters]\n : parameters === undefined || parameters === null || isPlainObject(parameters)\n ? []\n : [parameters]\n\n const values = new Map<string, string | undefined>()\n const missing: string[] = []\n for (const parameter of route.parameters) {\n let value: unknown\n if (Object.hasOwn(named, parameter.name)) {\n value = named[parameter.name]\n delete named[parameter.name]\n } else if (positional.length > 0) {\n value = positional.shift()\n }\n const key = routeKey(value, parameter.field)\n const text = key === undefined || key === null ? undefined : String(key)\n if (text === undefined && !parameter.optional) missing.push(parameter.name)\n values.set(parameter.name, text)\n }\n if (missing.length > 0) throw new UrlGenerationError(name, route.uri, missing)\n\n const path =\n route.uri === '/'\n ? ''\n : route.uri\n .split('/')\n .filter((segment) => {\n const whole = WHOLE_OPTIONAL.exec(segment)\n return whole === null || values.get(whole[1]!) !== undefined\n })\n .map((segment) =>\n segment.replace(PARAMETER, (_match, parameter: string) => {\n const value = values.get(parameter)\n return value === undefined ? '' : encodeURIComponent(value)\n }),\n )\n .join('/')\n const query = Object.fromEntries(Object.entries(named).map(([key, value]) => [key, routeKey(value, undefined)]))\n return this.to(path, query, absolute)\n }\n\n asset(path: string): string {\n if (VALID_URL.test(path)) return path\n const base = this.#config<string | undefined>('app.asset_url', undefined)?.replace(/\\/+$/, '') ?? this.root()\n const trimmed = path.replace(/^\\/+/, '')\n return trimmed === '' ? base : `${base}/${trimmed}`\n }\n\n /** The current URL without the query string. */\n current(): string {\n return this.#request()?.url() ?? this.root()\n }\n\n /** The current URL with the query string. */\n full(): string {\n return this.#request()?.fullUrl() ?? this.root()\n }\n\n /** The Referer header, then the session's previous URL, then `fallback`, then the root (Laravel's order). */\n previous(fallback?: string): string {\n const scope = this.#scope()\n const request = this.#request()\n const referer = request?.header('referer')\n if (referer !== undefined && referer !== '') return this.to(referer)\n if (request !== undefined && scope?.bound(Session)) {\n const previous = scope.make(Session).previousUrl()\n if (previous !== undefined && previous !== '') return this.to(previous)\n }\n return this.to(fallback ?? '/')\n }\n\n hasRoute(name: string): boolean {\n return this.router.getByName(name) !== undefined\n }\n\n #join(path: string, absolute: boolean): string {\n const trimmed = path.replace(/^\\/+|\\/+$/g, '')\n if (!absolute) return `/${trimmed}`\n return trimmed === '' ? this.root() : `${this.root()}/${trimmed}`\n }\n\n #scope(): Container | undefined {\n return currentContainer() ?? this.container\n }\n\n /** The HttpRequest, only when running inside a request scope. */\n #request(): HttpRequest | undefined {\n const scope = this.#scope()\n return scope?.bound(HttpRequest) ? scope.make(HttpRequest) : undefined\n }\n\n #config<T>(key: string, fallback: T): T {\n const scope = this.#scope()\n return scope?.bound(ConfigRepository) ? scope.make(ConfigRepository).get<T>(key, fallback) : fallback\n }\n}\n","import { Router, type Abstract } from '@orieljs/contracts'\nimport { facade } from '@orieljs/support'\nimport type { BaseRouter } from './BaseRouter'\n\n/**\n * The Route facade: Route.get('/', …), Route.prefix('admin').group(…), Route.resource(…). Typed as the BaseRouter\n * so the extras (permanentRedirect, patterns, has, currentRouteName, …) are available too.\n */\nexport const Route = facade<BaseRouter>(Router as Abstract<BaseRouter>)\n","import { pathToFileURL } from 'node:url'\nimport type { Application, Router } from '@orieljs/contracts'\n\n/** A route file may export a function instead of (or as well as) calling the Route facade at the top level. */\nexport type RouteFileCallback = (router: Router) => void | Promise<void>\n\nlet generation = 0\n\n/**\n * Imports a route file inside app.run(), so the Route facade in it resolves this application. Each load adds a\n * fresh `?oriel-routes=<n>` query: ESM caches modules, and a fresh app per test must register its routes again.\n * A default export that is a function is called with the router.\n */\nexport async function loadRoutesFrom(app: Application, router: Router, file: string): Promise<void> {\n const url = `${pathToFileURL(file).href}?oriel-routes=${++generation}`\n const module = (await app.run(() => import(/* @vite-ignore */ url))) as { default?: unknown }\n if (typeof module.default === 'function') await app.run(() => (module.default as RouteFileCallback)(router))\n}\n\n/** The health route's page (Laravel's `/up`): 200 as long as the application boots and handles requests. */\nexport function healthResponse(): Response {\n const html =\n '<!DOCTYPE html>\\n<html lang=\"en\">\\n<head>\\n<meta charset=\"utf-8\">\\n<title>Application up</title>\\n</head>\\n' +\n '<body><h1>Application up</h1></body>\\n</html>'\n return new Response(html, { status: 200, headers: { 'content-type': 'text/html; charset=utf-8' } })\n}\n","import { Router, RoutingPaths, UrlGenerator } from '@orieljs/contracts'\nimport { ServiceProvider } from '@orieljs/support'\nimport { BaseRouter } from './BaseRouter'\nimport { BaseUrlGenerator } from './BaseUrlGenerator'\nimport { RoutingError } from './errors'\nimport { healthResponse, loadRoutesFrom } from './routeFiles'\n\n/**\n * Binds the Router and the UrlGenerator, and once the app has booted loads the files given to withRouting(): the health URI,\n * then routes/web.ts in the `web` middleware group, then routes/api.ts under the api prefix in the `api` group\n * (Laravel's ApplicationBuilder::withRouting).\n */\nexport class RoutingServiceProvider extends ServiceProvider {\n override register(): void {\n this.app.singleton(Router, () => new BaseRouter(this.app))\n this.app.singleton(UrlGenerator, () => {\n const router = this.app.make(Router)\n if (!(router instanceof BaseRouter)) {\n throw new RoutingError('The UrlGenerator needs the BaseRouter: the bound Router was replaced by another implementation.')\n }\n return new BaseUrlGenerator(router, this.app)\n })\n }\n\n /**\n * The files load in a booted() callback, after every provider's boot() (Laravel's withRouting does the same), so\n * what the app's own providers set up at boot (Route.pattern/bind/model, gates, shared view data) is in place\n * when the route files run.\n */\n override boot(): void {\n this.app.booted(async () => {\n if (!this.app.bound(RoutingPaths)) return\n const { web, api, health, apiPrefix } = this.app.make(RoutingPaths)\n const router = this.app.make(Router)\n if (health !== undefined) router.get(health, () => healthResponse())\n if (web !== undefined) await router.middleware('web').group(() => loadRoutesFrom(this.app, router, web))\n if (api !== undefined) await router.prefix(apiPrefix).middleware('api').group(() => loadRoutesFrom(this.app, router, api))\n })\n }\n}\n","import type { Encrypter, Session, SessionHandler } from '@orieljs/contracts'\nimport { Arr, Str } from '@orieljs/support'\n\ntype Attributes = Record<string, unknown>\n\nconst unique = (values: string[]): string[] => [...new Set(values)]\n\n/**\n * Laravel's Illuminate\\Session\\Store (and EncryptedStore when an Encrypter is given).\n * Attributes use dot notation, so 'url.intended' is stored as { url: { intended } }.\n * The payload is JSON: Dates become strings and class instances become plain objects.\n */\nexport class Store implements Session {\n #id = ''\n #name: string\n #attributes: Attributes = {}\n #started = false\n readonly #handler: SessionHandler\n readonly #encrypter: Encrypter | undefined\n\n constructor(name: string, handler: SessionHandler, id?: string, encrypter?: Encrypter) {\n this.#name = name\n this.#handler = handler\n this.#encrypter = encrypter\n this.setId(id)\n }\n\n /** Loads the session from the handler and makes sure it has a CSRF token. */\n async start(): Promise<void> {\n this.#attributes = { ...this.#attributes, ...(await this.#readFromHandler()) }\n if (!this.has('_token')) this.regenerateToken()\n this.#started = true\n }\n\n /** Ages the flash data and writes the session through the handler. */\n async save(): Promise<void> {\n this.ageFlashData()\n const payload = JSON.stringify(this.#attributes)\n await this.#handler.write(this.getId(), this.#encrypter === undefined ? payload : this.#encrypter.encrypt(payload, false))\n this.#started = false\n }\n\n /** Forgets last request's flash data and marks this request's flash data as old. */\n ageFlashData(): void {\n this.forget(...this.get<string[]>('_flash.old', []))\n this.put('_flash.old', this.get<string[]>('_flash.new', []))\n this.put('_flash.new', [])\n }\n\n all(): Attributes {\n return { ...this.#attributes }\n }\n\n only(keys: string[]): Attributes {\n return Arr.only(this.#attributes, keys)\n }\n\n except(keys: string[]): Attributes {\n return Arr.except(this.#attributes, keys)\n }\n\n /** Whether the key is present, even with a null value. */\n exists(...keys: string[]): boolean {\n return keys.every((key) => Arr.has(this.#attributes, key))\n }\n\n missing(...keys: string[]): boolean {\n return !this.exists(...keys)\n }\n\n /** Whether the key is present and not null/undefined. */\n has(key: string): boolean {\n const value = this.get<unknown>(key)\n return value !== undefined && value !== null\n }\n\n get<T = unknown>(key: string, defaultValue?: T): T {\n return Arr.get(this.#attributes, key, defaultValue)\n }\n\n pull<T = unknown>(key: string, defaultValue?: T): T {\n const value = this.get(key, defaultValue)\n this.forget(key)\n return value\n }\n\n put(key: string | Attributes, value?: unknown): void {\n const values = typeof key === 'string' ? { [key]: value } : key\n for (const [name, item] of Object.entries(values)) Arr.set(this.#attributes, name, item)\n }\n\n push(key: string, value: unknown): void {\n const list = this.get<unknown>(key, [])\n this.put(key, [...(Array.isArray(list) ? list : [list]), value])\n }\n\n increment(key: string, amount = 1): number {\n const value = Number(this.get(key, 0)) + amount\n this.put(key, value)\n return value\n }\n\n decrement(key: string, amount = 1): number {\n return this.increment(key, -amount)\n }\n\n forget(...keys: string[]): void {\n for (const key of keys) Arr.forget(this.#attributes, key)\n }\n\n /** Removes a key and returns its value. */\n remove<T = unknown>(key: string): T {\n return this.pull<T>(key)\n }\n\n flush(): void {\n this.#attributes = {}\n }\n\n /** Available on this request and the next one. */\n flash(key: string, value: unknown = true): void {\n this.put(key, value)\n this.push('_flash.new', key)\n this.#removeFromOldFlashData([key])\n }\n\n /** Available on this request only. */\n now(key: string, value: unknown): void {\n this.put(key, value)\n this.push('_flash.old', key)\n }\n\n /** Keeps all of last request's flash data for one more request. */\n reflash(): void {\n this.#mergeNewFlashes(this.get<string[]>('_flash.old', []))\n this.put('_flash.old', [])\n }\n\n /** Keeps some of last request's flash data for one more request. */\n keep(...keys: string[]): void {\n this.#mergeNewFlashes(keys)\n this.#removeFromOldFlashData(keys)\n }\n\n flashInput(input: Attributes): void {\n this.flash('_old_input', input)\n }\n\n hasOldInput(key?: string): boolean {\n const old = this.getOldInput<unknown>(key)\n return key === undefined ? typeof old === 'object' && old !== null && Object.keys(old).length > 0 : old !== undefined && old !== null\n }\n\n getOldInput<T = unknown>(key?: string, defaultValue?: T): T {\n return Arr.get(this.get<Attributes>('_old_input', {}), key, defaultValue)\n }\n\n token(): string {\n return this.get<string>('_token')\n }\n\n regenerateToken(): void {\n this.put('_token', Str.random(40))\n }\n\n /** New session id and CSRF token. With destroy, the old record is deleted. */\n async regenerate(destroy = false): Promise<void> {\n await this.migrate(destroy)\n this.regenerateToken()\n }\n\n /** New session id, keeping the data (and the CSRF token). With destroy, the old record is deleted. */\n async migrate(destroy = false): Promise<void> {\n if (destroy) await this.#handler.destroy(this.getId())\n ;(this.#handler as { setExists?(exists: boolean): void }).setExists?.(false)\n this.setId(this.#generateSessionId())\n }\n\n /** Flushes the data and migrates to a new id, destroying the old record. */\n async invalidate(): Promise<void> {\n this.flush()\n await this.migrate(true)\n }\n\n previousUrl(): string | undefined {\n return this.get<string | undefined>('_previous.url')\n }\n\n setPreviousUrl(url: string): void {\n this.put('_previous.url', url)\n }\n\n isStarted(): boolean {\n return this.#started\n }\n\n getName(): string {\n return this.#name\n }\n\n setName(name: string): void {\n this.#name = name\n }\n\n getId(): string {\n return this.#id\n }\n\n /** Invalid ids (anything but 40 alphanumerics) are replaced by a fresh one, so ids from cookies can't be forged. */\n setId(id: string | undefined | null): void {\n this.#id = this.isValidId(id) ? id : this.#generateSessionId()\n }\n\n isValidId(id: unknown): id is string {\n return typeof id === 'string' && /^[a-zA-Z0-9]{40}$/.test(id)\n }\n\n getHandler(): SessionHandler {\n return this.#handler\n }\n\n #generateSessionId(): string {\n return Str.random(40)\n }\n\n async #readFromHandler(): Promise<Attributes> {\n let data = await this.#handler.read(this.getId())\n if (data === '') return {}\n if (this.#encrypter !== undefined) {\n try {\n data = this.#encrypter.decrypt<string>(data, false)\n } catch {\n return {}\n }\n }\n try {\n const parsed: unknown = JSON.parse(data)\n return typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed) ? (parsed as Attributes) : {}\n } catch {\n return {}\n }\n }\n\n #mergeNewFlashes(keys: string[]): void {\n this.put('_flash.new', unique([...this.get<string[]>('_flash.new', []), ...keys]))\n }\n\n #removeFromOldFlashData(keys: string[]): void {\n this.put('_flash.old', this.get<string[]>('_flash.old', []).filter((key) => !keys.includes(key)))\n }\n}\n","import type { SessionHandler } from '@orieljs/contracts'\n\n/** Laravel's ArraySessionHandler: in-memory sessions (tests, `SESSION_DRIVER=array`). */\nexport class ArraySessionHandler implements SessionHandler {\n readonly #storage = new Map<string, { data: string; time: number }>()\n\n constructor(\n private readonly minutes: number,\n private readonly clock: () => number = Date.now,\n ) {}\n\n async read(id: string): Promise<string> {\n const session = this.#storage.get(id)\n if (session === undefined) return ''\n return session.time >= this.clock() - this.minutes * 60_000 ? session.data : ''\n }\n\n async write(id: string, data: string): Promise<void> {\n this.#storage.set(id, { data, time: this.clock() })\n }\n\n async destroy(id: string): Promise<void> {\n this.#storage.delete(id)\n }\n\n async gc(maxLifetimeSeconds: number): Promise<void> {\n const expiration = this.clock() - maxLifetimeSeconds * 1000\n for (const [id, session] of this.#storage) if (session.time <= expiration) this.#storage.delete(id)\n }\n\n /** The raw stored payload (for tests and debugging). */\n raw(id: string): string | undefined {\n return this.#storage.get(id)?.data\n }\n}\n","import { mkdir, readdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport type { SessionHandler } from '@orieljs/contracts'\nimport { Str } from '@orieljs/support'\n\nconst VALID_ID = /^[a-zA-Z0-9]{40}$/\n\n/**\n * Laravel's FileSessionHandler: one file per session in `path` (storage/framework/sessions).\n * Only 40-character alphanumeric ids are ever turned into a path, so an id can't escape the directory.\n */\nexport class FileSessionHandler implements SessionHandler {\n constructor(\n private readonly path: string,\n private readonly minutes: number,\n private readonly clock: () => number = Date.now,\n ) {}\n\n async read(id: string): Promise<string> {\n if (!VALID_ID.test(id)) return ''\n const file = join(this.path, id)\n try {\n const { mtimeMs } = await stat(file)\n if (mtimeMs < this.clock() - this.minutes * 60_000) return ''\n return await readFile(file, 'utf8')\n } catch {\n return ''\n }\n }\n\n async write(id: string, data: string): Promise<void> {\n if (!VALID_ID.test(id)) return\n await mkdir(this.path, { recursive: true })\n // Write then rename, so a concurrent read never sees a half-written file.\n const temporary = join(this.path, `.${id}.${Str.random(8)}.tmp`)\n await writeFile(temporary, data, 'utf8')\n await rename(temporary, join(this.path, id))\n }\n\n async destroy(id: string): Promise<void> {\n if (VALID_ID.test(id)) await rm(join(this.path, id), { force: true })\n }\n\n async gc(maxLifetimeSeconds: number): Promise<void> {\n const expiration = this.clock() - maxLifetimeSeconds * 1000\n const files = await readdir(this.path).catch(() => [] as string[])\n for (const file of files) {\n if (!VALID_ID.test(file)) continue\n const { mtimeMs } = await stat(join(this.path, file)).catch(() => ({ mtimeMs: Number.POSITIVE_INFINITY }))\n if (mtimeMs <= expiration) await rm(join(this.path, file), { force: true })\n }\n }\n}\n","import { AuthFactory, ExceptionHandler, HttpRequest, type Container, type DatabaseConnection, type Guard, type Row, type SessionHandler } from '@orieljs/contracts'\n\n/**\n * Laravel's DatabaseSessionHandler over the DatabaseManager contract: table `sessions` with `id`, `user_id`,\n * `ip_address`, `user_agent`, `payload` (base64) and `last_activity` (unix seconds). One instance per Store,\n * because `exists` is per-request state.\n */\nexport class DatabaseSessionHandler implements SessionHandler {\n #exists = false\n\n constructor(\n private readonly connection: () => DatabaseConnection,\n private readonly table: string,\n private readonly minutes: number,\n /** The current container, for the request (ip, user agent) and the logged-in user. */\n private readonly container: () => Container | undefined = () => undefined,\n private readonly clock: () => number = Date.now,\n ) {}\n\n async read(id: string): Promise<string> {\n const session = await this.#query().where('id', id).first()\n if (session === undefined) return ''\n this.#exists = true\n if (Number(session.last_activity) < this.#now() - this.minutes * 60) return ''\n return typeof session.payload === 'string' ? Buffer.from(session.payload, 'base64').toString('utf8') : ''\n }\n\n async write(id: string, data: string): Promise<void> {\n const payload = await this.#payload(data)\n if (this.#exists) {\n await this.#query().where('id', id).update(payload)\n return\n }\n try {\n await this.#query().insert({ id, ...payload })\n } catch {\n await this.#query().where('id', id).update(payload)\n }\n this.#exists = true\n }\n\n async destroy(id: string): Promise<void> {\n await this.#query().where('id', id).delete()\n }\n\n async gc(maxLifetimeSeconds: number): Promise<void> {\n await this.#query().where('last_activity', '<=', this.#now() - maxLifetimeSeconds).delete()\n }\n\n /** Called by Store.migrate(): the next write inserts a new row. */\n setExists(exists: boolean): void {\n this.#exists = exists\n }\n\n #query() {\n return this.connection().table<Row>(this.table)\n }\n\n #now(): number {\n return Math.floor(this.clock() / 1000)\n }\n\n async #payload(data: string): Promise<Row> {\n const payload: Row = { payload: Buffer.from(data, 'utf8').toString('base64'), last_activity: this.#now() }\n const container = this.container()\n if (container === undefined) return payload\n if (container.bound(HttpRequest)) {\n const request = container.make(HttpRequest)\n payload.ip_address = request.ip() ?? null\n payload.user_agent = (request.header('user-agent') ?? '').slice(0, 500)\n }\n if (container.bound(AuthFactory)) {\n // Only when the guard already holds a user, so writing a session never triggers a user query.\n const guard = await this.#guard(container)\n payload.user_id = guard?.hasUser() ? ((await guard.id()) ?? null) : null\n }\n return payload\n }\n\n /** The default guard, or undefined when it can't be built (the error is reported, not thrown). */\n async #guard(container: Container): Promise<Guard | undefined> {\n try {\n return container.make(AuthFactory).guard()\n } catch (error) {\n // A guard that can't be built must not take every web request down with it.\n try {\n if (container.bound(ExceptionHandler)) await container.make(ExceptionHandler).report(error)\n } catch {\n // A failing reporter must not bring the request down either.\n }\n return undefined\n }\n }\n}\n","import type { CookieJar, HttpRequest, SessionHandler } from '@orieljs/contracts'\n\n/**\n * Laravel's CookieSessionHandler: the whole session lives in a cookie named after the session id, queued on the\n * request's CookieJar (EncryptCookies encrypts it). The payload records its own expiry.\n */\nexport class CookieSessionHandler implements SessionHandler {\n constructor(\n private readonly jar: () => CookieJar,\n private readonly request: () => HttpRequest | undefined,\n private readonly minutes: number,\n private readonly expireOnClose = false,\n private readonly clock: () => number = Date.now,\n ) {}\n\n async read(id: string): Promise<string> {\n const value = this.request()?.cookie(id)\n if (value === undefined || value === '') return ''\n try {\n const decoded = JSON.parse(value) as { data?: unknown; expires?: unknown }\n return typeof decoded.data === 'string' && typeof decoded.expires === 'number' && decoded.expires >= this.#now()\n ? decoded.data\n : ''\n } catch {\n return ''\n }\n }\n\n async write(id: string, data: string): Promise<void> {\n const jar = this.jar()\n const value = JSON.stringify({ data, expires: this.#now() + this.minutes * 60 })\n jar.queue(jar.make(id, value, this.expireOnClose ? 0 : this.minutes))\n }\n\n async destroy(id: string): Promise<void> {\n const jar = this.jar()\n jar.queue(jar.forget(id))\n }\n\n async gc(): Promise<void> {}\n\n #now(): number {\n return Math.floor(this.clock() / 1000)\n }\n}\n","import type { SessionHandler } from '@orieljs/contracts'\n\n/** The part of an ioredis client the handler uses (an ioredis `Redis` satisfies it). */\nexport interface RedisSessionClient {\n get(key: string): Promise<string | null>\n set(key: string, value: string, mode: 'EX', seconds: number): Promise<unknown>\n del(key: string): Promise<number>\n}\n\n/** Sessions in Redis with a TTL of `minutes` (Laravel's redis driver, without going through the cache store). */\nexport class RedisSessionHandler implements SessionHandler {\n constructor(\n private readonly client: RedisSessionClient,\n private readonly minutes: number,\n private readonly prefix = 'oriel_session:',\n ) {}\n\n async read(id: string): Promise<string> {\n return (await this.client.get(this.prefix + id)) ?? ''\n }\n\n async write(id: string, data: string): Promise<void> {\n await this.client.set(this.prefix + id, data, 'EX', Math.max(1, this.minutes * 60))\n }\n\n async destroy(id: string): Promise<void> {\n await this.client.del(this.prefix + id)\n }\n\n /** Redis expires keys itself. */\n async gc(): Promise<void> {}\n}\n","import { Redis } from 'ioredis'\nimport {\n ConfigRepository,\n CookieJar,\n DatabaseManager,\n Encrypter,\n HttpRequest,\n type Container,\n type SessionHandler,\n} from '@orieljs/contracts'\nimport { ArraySessionHandler } from './handlers/ArraySessionHandler'\nimport { CookieSessionHandler } from './handlers/CookieSessionHandler'\nimport { DatabaseSessionHandler } from './handlers/DatabaseSessionHandler'\nimport { FileSessionHandler } from './handlers/FileSessionHandler'\nimport { RedisSessionHandler } from './handlers/RedisSessionHandler'\nimport { Store } from './Store'\n\n/** config/session.ts (Laravel 11's keys). */\nexport interface SessionConfig {\n driver?: string | null\n lifetime?: number\n expire_on_close?: boolean\n encrypt?: boolean\n files?: string\n connection?: string | null\n table?: string\n lottery?: [number, number]\n cookie?: string\n path?: string\n domain?: string | null\n secure?: boolean | null\n http_only?: boolean\n same_site?: 'lax' | 'strict' | 'none' | null\n}\n\n/** Builds a handler for a custom driver. Called once per Store (per request scope). */\nexport type SessionHandlerFactory = (container: Container, config: SessionConfig) => SessionHandler\n\n/** An entry of config('database.redis'). */\nexport interface RedisConnectionConfig {\n url?: string\n host?: string\n port?: number\n password?: string\n username?: string\n db?: number\n lazyConnect?: boolean\n}\n\n/** An ioredis client from a `database.redis.<name>` entry: its url, else host/port/password/db, else localhost. */\nexport function makeRedisClient(config: RedisConnectionConfig = {}): Redis {\n const options: Record<string, unknown> = {}\n for (const key of ['host', 'port', 'password', 'username', 'db', 'lazyConnect'] as const) if (config[key] !== undefined) options[key] = config[key]\n return typeof config.url === 'string' && config.url !== '' ? new Redis(config.url, options) : new Redis(options)\n}\n\n/**\n * Laravel's SessionManager. A root singleton: it keeps the handlers that may be shared between requests (array,\n * file, redis) and builds a new Store for each request scope (database and cookie handlers are per Store).\n */\nexport class SessionManager {\n readonly #custom = new Map<string, SessionHandlerFactory>()\n readonly #shared = new Map<string, SessionHandler>()\n #redis: Redis | undefined\n\n constructor(private readonly app: Container) {}\n\n getSessionConfig(): SessionConfig {\n return this.app.make(ConfigRepository).get<SessionConfig>('session', {})\n }\n\n getDefaultDriver(): string | undefined {\n return this.getSessionConfig().driver ?? undefined\n }\n\n /** Register a custom driver: Session.extend('mongo', (container, config) => new MongoHandler(...)). */\n extend(driver: string, factory: SessionHandlerFactory): this {\n this.#custom.set(driver, factory)\n return this\n }\n\n /** A new Store for `container` (the request or job scope). */\n build(container: Container, driver?: string): Store {\n const config = this.getSessionConfig()\n const handler = this.handler(driver ?? config.driver ?? 'array', container)\n const encrypter = config.encrypt === true ? container.make(Encrypter) : undefined\n return new Store(config.cookie ?? 'oriel_session', handler, undefined, encrypter)\n }\n\n handler(driver: string, container: Container): SessionHandler {\n const config = this.getSessionConfig()\n const lifetime = config.lifetime ?? 120\n const custom = this.#custom.get(driver)\n if (custom !== undefined) return custom(container, config)\n switch (driver) {\n case 'array':\n return this.#share('array', () => new ArraySessionHandler(lifetime))\n case 'file':\n return this.#share('file', () => new FileSessionHandler(config.files ?? 'storage/framework/sessions', lifetime))\n case 'redis':\n return this.#share('redis', () => new RedisSessionHandler(this.redis(), lifetime))\n case 'database':\n return new DatabaseSessionHandler(\n () => container.make(DatabaseManager).connection(config.connection ?? undefined),\n config.table ?? 'sessions',\n lifetime,\n () => container,\n )\n case 'cookie':\n return new CookieSessionHandler(\n () => container.make(CookieJar),\n () => (container.bound(HttpRequest) ? container.make(HttpRequest) : undefined),\n lifetime,\n config.expire_on_close === true,\n )\n default:\n throw new Error(`Driver [${driver}] not supported.`)\n }\n }\n\n /** The redis client for config('session.connection') (an entry of config('database.redis'), default 'default'). */\n redis(): Redis {\n if (this.#redis === undefined) {\n const name = this.getSessionConfig().connection ?? 'default'\n this.#redis = makeRedisClient(this.app.make(ConfigRepository).get<RedisConnectionConfig>(`database.redis.${name}`, {}))\n }\n return this.#redis\n }\n\n /** Closes the redis connection, if one was opened. */\n async disconnect(): Promise<void> {\n await this.#redis?.quit()\n this.#redis = undefined\n }\n\n #share(driver: string, make: () => SessionHandler): SessionHandler {\n let handler = this.#shared.get(driver)\n if (handler === undefined) {\n handler = make()\n this.#shared.set(driver, handler)\n }\n return handler\n }\n}\n","import type { OrielError } from '@orieljs/contracts'\n\n/** Laravel's TokenMismatchException: rendered as 419 by the exception handler. */\nexport class TokenMismatchError extends Error implements OrielError {\n readonly kind = 'TokenMismatch' as const\n readonly status = 419\n override readonly name = 'TokenMismatchError'\n constructor(message = 'CSRF token mismatch.') {\n super(message)\n }\n}\n","import { randomInt } from 'node:crypto'\nimport { ConfigRepository, Container, Session, type HttpRequest, type Middleware, type Next } from '@orieljs/contracts'\nimport { inject } from '@orieljs/container'\nimport type { SessionConfig } from '../SessionManager'\nimport type { Store } from '../Store'\nimport { attachCookie, sessionCookie } from './cookies'\n\n/**\n * Laravel's StartSession: loads the session named by the cookie, runs the request, remembers the previous URL,\n * sends the session cookie and saves the session. Http renders errors inside the pipeline, so the \"after\" part\n * always runs and flashed errors are saved.\n */\nexport class StartSession implements Middleware {\n readonly #container = inject(Container)\n readonly #config = inject(ConfigRepository)\n\n async handle(request: HttpRequest, next: Next): Promise<Response> {\n const config = this.#config.get<SessionConfig>('session', {})\n if (config.driver === undefined || config.driver === null) return next(request)\n\n const session = this.#container.make(Session) as Session & Partial<Pick<Store, 'setId' | 'getName' | 'getHandler'>>\n session.setId?.(request.cookie(session.getName?.() ?? config.cookie ?? 'oriel_session'))\n await session.start()\n await this.#collectGarbage(session, config)\n\n let response = await next(request)\n this.#storeCurrentUrl(request, session)\n response = attachCookie(\n response,\n sessionCookie(\n config,\n {\n name: (session as Partial<Pick<Store, 'getName'>>).getName?.() ?? config.cookie ?? 'oriel_session',\n value: session.getId(),\n httpOnly: config.http_only ?? true,\n },\n request,\n ),\n )\n await session.save()\n return response\n }\n\n /** Laravel's lottery: on average lottery[0] requests out of lottery[1] clean up expired sessions. */\n async #collectGarbage(session: Partial<Pick<Store, 'getHandler'>>, config: SessionConfig): Promise<void> {\n const [chances, outOf] = config.lottery ?? [2, 100]\n if (session.getHandler !== undefined && randomInt(1, outOf + 1) <= chances) {\n await session.getHandler().gc((config.lifetime ?? 120) * 60)\n }\n }\n\n #storeCurrentUrl(request: HttpRequest, session: Session): void {\n const prefetch = request.header('purpose') === 'prefetch' || request.header('sec-purpose') === 'prefetch'\n if (request.isMethod('GET') && !request.ajax() && !prefetch) session.setPreviousUrl(request.fullUrl())\n }\n}\n","import type { Cookie, HttpRequest } from '@orieljs/contracts'\nimport type { SessionConfig } from '../SessionManager'\n\n/** A minimal Set-Cookie serializer, Session never imports Cookie. */\nfunction serialize(cookie: Cookie): string {\n const parts = [`${cookie.name}=${encodeURIComponent(cookie.value)}`]\n if (cookie.minutes > 0) {\n parts.push(`Expires=${new Date(Date.now() + cookie.minutes * 60_000).toUTCString()}`, `Max-Age=${cookie.minutes * 60}`)\n }\n parts.push(`Path=${cookie.path}`)\n if (cookie.domain !== undefined && cookie.domain !== '') 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 return parts.join('; ')\n}\n\n/** Append the cookie's Set-Cookie straight onto the response (EncryptCookies encrypts response cookies). */\nexport function attachCookie(response: Response, cookie: Cookie): Response {\n const headers = new Headers(response.headers)\n headers.append('Set-Cookie', serialize(cookie))\n return new Response(response.body, { status: response.status, statusText: response.statusText, headers })\n}\n\n/**\n * Whether a cookie should be Secure. An explicit `true`/`false` always wins; when `secure` is null/undefined\n * (the default, ruling F6), it follows Symfony's `setSecureDefault`: Secure when the request itself is HTTPS.\n */\nfunction resolveSecure(secure: boolean | null | undefined, request: HttpRequest | undefined): boolean {\n return secure ?? (request !== undefined && request.url().startsWith('https:'))\n}\n\n/** Builds the session cookie (or XSRF-TOKEN) from session config, shared by StartSession and VerifyCsrfToken. */\nexport function sessionCookie(\n config: SessionConfig,\n options: { name: string; value: string; httpOnly: boolean },\n request?: HttpRequest,\n): Cookie {\n return {\n name: options.name,\n value: options.value,\n minutes: config.expire_on_close === true ? 0 : (config.lifetime ?? 120),\n path: config.path ?? '/',\n ...(config.domain ? { domain: config.domain } : {}),\n secure: resolveSecure(config.secure, request),\n httpOnly: options.httpOnly,\n sameSite: config.same_site ?? 'lax',\n }\n}\n","import {\n Application,\n ConfigRepository,\n Container,\n Encrypter,\n Session,\n type HttpRequest,\n type Middleware,\n type Next,\n} from '@orieljs/contracts'\nimport { inject } from '@orieljs/container'\nimport { Str } from '@orieljs/support'\nimport { equals } from '../equals'\nimport { TokenMismatchError } from '../errors'\nimport type { SessionConfig } from '../SessionManager'\nimport { attachCookie, sessionCookie } from './cookies'\n\n/**\n * Laravel's VerifyCsrfToken (ValidateCsrfToken). Reads pass; writes need the session token as `_token`,\n * `X-CSRF-TOKEN` or the encrypted `X-XSRF-TOKEN` header. Paths in `except` and config('http.csrf_except') skip the\n * check. Every passing response gets the `XSRF-TOKEN` cookie (readable by JavaScript).\n */\nexport class VerifyCsrfToken implements Middleware {\n /** URIs (wildcards allowed) excluded from the check, in addition to config('http.csrf_except'). */\n protected except: string[] = []\n\n /** Whether to send the XSRF-TOKEN cookie. */\n protected addHttpCookie = true\n\n readonly #container = inject(Container)\n readonly #config = inject(ConfigRepository)\n\n async handle(request: HttpRequest, next: Next): Promise<Response> {\n if (this.isReading(request) || this.runningUnitTests() || this.inExceptArray(request) || this.tokensMatch(request)) {\n const response = await next(request)\n return this.addHttpCookie ? this.addCookieToResponse(response, request) : response\n }\n throw new TokenMismatchError()\n }\n\n protected isReading(request: HttpRequest): boolean {\n return ['HEAD', 'GET', 'OPTIONS'].includes(request.method().toUpperCase())\n }\n\n protected runningUnitTests(): boolean {\n if (!this.#container.bound(Application)) return false\n const app = this.#container.make(Application)\n return app.runningInConsole() && app.runningUnitTests()\n }\n\n protected inExceptArray(request: HttpRequest): boolean {\n const configured = this.#config.get<unknown>('http.csrf_except', [])\n const patterns = [...this.except, ...(Array.isArray(configured) ? configured.map(String) : [])]\n return patterns.some((pattern) => {\n const trimmed = pattern === '/' ? pattern : pattern.replace(/^\\/+|\\/+$/g, '')\n return Str.is(trimmed, request.fullUrl()) || request.is(trimmed)\n })\n }\n\n protected tokensMatch(request: HttpRequest): boolean {\n const sessionToken = this.#container.make(Session).token()\n const token = this.getTokenFromRequest(request)\n return typeof sessionToken === 'string' && typeof token === 'string' && token !== '' && equals(sessionToken, token)\n }\n\n protected getTokenFromRequest(request: HttpRequest): string | undefined {\n const input = request.input<unknown>('_token')\n const token = (typeof input === 'string' && input !== '' ? input : undefined) ?? request.header('X-CSRF-TOKEN')\n if (token !== undefined && token !== '') return token\n const header = request.header('X-XSRF-TOKEN')\n if (header === undefined || header === '' || !this.#container.bound(Encrypter)) return undefined\n try {\n // The XSRF-TOKEN cookie was encrypted by EncryptCookies with its name prefix (40 hex chars + '|').\n return this.#container.make(Encrypter).decrypt<string>(header, false).slice(41)\n } catch {\n return undefined\n }\n }\n\n protected addCookieToResponse(response: Response, request: HttpRequest): Response {\n const token = this.#container.make(Session).token()\n // No token (e.g. invalidate() without regenerateToken()): skip rather than queue a literal \"undefined\" value.\n if (!token) return response\n const config = this.#config.get<SessionConfig>('session', {})\n return attachCookie(\n response,\n sessionCookie(config, { name: 'XSRF-TOKEN', value: token, httpOnly: false }, request),\n )\n }\n}\n","import { timingSafeEqual } from 'node:crypto'\n\n/** Constant-time string comparison (PHP's hash_equals). */\nexport function equals(known: string, user: string): boolean {\n const a = Buffer.from(known)\n const b = Buffer.from(user)\n return a.length === b.length && timingSafeEqual(a, b)\n}\n","import type { MessageBag } from '@orieljs/contracts'\n\n/**\n * A read-only MessageBag over one bag of the flashed validation errors. Http flashes\n * `errors: { [bag]: { field: string[] } }`; views read them with `errors().first('email')`.\n */\nexport class SessionMessageBag implements MessageBag {\n readonly #messages: Record<string, string[]>\n\n constructor(messages: Record<string, string[]> = {}) {\n this.#messages = messages\n }\n\n has(key: string): boolean {\n return this.get(key).length > 0\n }\n\n first(key?: string): string | undefined {\n return key === undefined ? this.all()[0] : this.get(key)[0]\n }\n\n get(key: string): string[] {\n const messages = Object.hasOwn(this.#messages, key) ? this.#messages[key] : undefined\n return Array.isArray(messages) ? messages.map(String) : []\n }\n\n all(): string[] {\n return Object.values(this.#messages).flatMap((messages) => (Array.isArray(messages) ? messages.map(String) : []))\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.keys(this.#messages).map((key) => [key, this.get(key)]))\n }\n}\n\n/** The bag named `bag` (default 'default') out of the session's flashed `errors` value. */\nexport function errorBagFrom(errors: unknown, bag = 'default'): SessionMessageBag {\n if (typeof errors !== 'object' || errors === null) return new SessionMessageBag()\n const messages = (errors as Record<string, unknown>)[bag]\n return new SessionMessageBag(typeof messages === 'object' && messages !== null ? (messages as Record<string, string[]>) : {})\n}\n","import { Application, Session } from '@orieljs/contracts'\nimport { currentContainer, inject } from '@orieljs/container'\nimport { facade } from '@orieljs/support'\nimport { SessionManager, type SessionHandlerFactory } from './SessionManager'\nimport { errorBagFrom, type SessionMessageBag } from './ViewErrorBag'\n\n/**\n * The current scope's session, or undefined where there is none: no container, no Session binding, or the\n * application itself (a console command, schedule:run, a mail view rendered outside a request). Session is scoped,\n * so resolving it on the application would throw.\n */\nfunction scopeSession(): Session | undefined {\n const container = currentContainer()\n if (container === undefined || !container.bound(Session)) return undefined\n if (container.bound(Application) && (container.make(Application) as unknown) === container) return undefined\n return container.make(Session)\n}\n\n/** The Session facade (the current request's session). `Session.extend()` registers a custom driver. */\nexport const SessionFacade = facade(Session, {\n extend: (driver: string, factory: SessionHandlerFactory): SessionManager => inject(SessionManager).extend(driver, factory),\n})\n\n/** session(): the store; session(key, default?): a value; session({ key: value }): put values. */\nexport function session(): Session\nexport function session(values: Record<string, unknown>): void\nexport function session<T = unknown>(key: string, defaultValue?: T): T\nexport function session(key?: string | Record<string, unknown>, defaultValue?: unknown): unknown {\n const store = inject(Session)\n if (key === undefined) return store\n if (typeof key === 'string') return store.get(key, defaultValue)\n store.put(key)\n return undefined\n}\n\n/** old(key?, default?): input flashed by the previous request (Laravel's old()). The default outside a request. */\nexport function old<T = unknown>(key?: string, defaultValue?: T): T {\n const store = scopeSession()\n return store === undefined ? (defaultValue as T) : store.getOldInput<T>(key, defaultValue)\n}\n\n/** csrfToken(): the session's CSRF token (Laravel's csrf_token()). */\nexport function csrfToken(): string {\n return inject(Session).token()\n}\n\n/**\n * errors(bag?): the validation errors flashed by the previous request, as a MessageBag. Empty outside a request,\n * so views rendered from a console command or a job (mail, TSX) can call it safely.\n */\nexport function errors(bag = 'default'): SessionMessageBag {\n return errorBagFrom(scopeSession()?.get('errors'), bag)\n}\n","import { Router, Session } from '@orieljs/contracts'\nimport { ServiceProvider } from '@orieljs/support'\nimport { StartSession } from './middleware/StartSession'\nimport { VerifyCsrfToken } from './middleware/VerifyCsrfToken'\nimport { SessionManager } from './SessionManager'\n\nexport class SessionServiceProvider extends ServiceProvider {\n override register(): void {\n // Laravel 11's config/session.php. The cookie name can't come from APP_NAME here (no env() in packages).\n this.mergeConfigFrom(\n {\n driver: 'database',\n lifetime: 120,\n expire_on_close: false,\n encrypt: false,\n files: this.app.storagePath('framework/sessions'),\n connection: null,\n table: 'sessions',\n lottery: [2, 100],\n cookie: 'oriel_session',\n path: '/',\n domain: null,\n secure: null,\n http_only: true,\n same_site: 'lax',\n },\n 'session',\n )\n this.app.singleton(SessionManager, (container) => new SessionManager(container))\n this.app.scoped(Session, (container) => container.make(SessionManager).build(container))\n }\n\n override boot(): void {\n if (!this.app.bound(Router)) return\n this.app.make(Router).pushMiddlewareToGroup('web', StartSession).pushMiddlewareToGroup('web', VerifyCsrfToken)\n }\n}\n","import type { OrielError, ValidationError } from '@orieljs/contracts'\n\nexport class ValidationErrorImpl extends Error implements ValidationError {\n readonly kind = 'Validation' as const\n readonly status = 422\n override readonly name = 'ValidationError'\n constructor(\n readonly errors: Record<string, string[]>,\n readonly errorBag = 'default',\n readonly redirectTo?: string,\n ) {\n super('The given data was invalid.')\n }\n}\n\nexport class AuthorizationErrorImpl extends Error implements OrielError {\n readonly kind = 'Authorization' as const\n readonly status = 403\n override readonly name = 'AuthorizationError'\n constructor(message = 'This action is unauthorized.') {\n super(message)\n }\n}\n\nexport class UnknownValidationRuleError extends Error implements OrielError {\n readonly kind = 'Server' as const\n readonly status = 500\n override readonly name = 'UnknownValidationRuleError'\n constructor(name: string) {\n super(`Validation rule \"${name}\" is not registered. Register it with ValidationFactory.extend() first.`)\n }\n}\n\n/** A rule was written with a parameter it can't use (a bad regex, an unparseable date). A developer error, not a user one. */\nexport class InvalidRuleParameterError extends Error implements OrielError {\n readonly kind = 'Server' as const\n readonly status = 500\n override readonly name = 'InvalidRuleParameterError'\n constructor(rule: string, parameter: string, reason: string) {\n super(`Validation rule \"${rule}\" has an invalid parameter \"${parameter}\": ${reason}`)\n }\n}\n","import type { Rules } from '@orieljs/contracts'\nimport { HttpRequest, ValidationFactory } from '@orieljs/contracts'\nimport { inject } from '@orieljs/container'\nimport { AuthorizationErrorImpl } from './errors'\n\n/**\n * Mirrors Illuminate\\Foundation\\Http\\FormRequest, minus dependency injection by type (Oriel resolves the current\n * request and the ValidationFactory through inject(), never through constructor parameters — see spec §3 rule 5).\n * A subclass only has to implement rules(); authorize()/messages()/attributes() default to Laravel's own defaults.\n */\nexport abstract class FormRequest {\n abstract rules(): Rules\n\n authorize(): boolean | Promise<boolean> {\n return true\n }\n\n messages(): Record<string, string> {\n return {}\n }\n\n attributes(): Record<string, string> {\n return {}\n }\n\n /**\n * `const data = await StorePostRequest.validate()` (spec §4.3). Resolves the current request and the\n * ValidationFactory from the active container, runs authorize() first (throwing AuthorizationErrorImpl if it\n * returns false), then validates request.all() against rules()/messages()/attributes() and returns the typed\n * validated data (or throws the 422 ValidationError — see ValidatorImpl.validated()).\n */\n static async validate<T = Record<string, unknown>>(this: new () => FormRequest): Promise<T> {\n const instance = new this()\n if (!(await instance.authorize())) throw new AuthorizationErrorImpl()\n\n const request = inject(HttpRequest)\n const factory = inject(ValidationFactory)\n const validator = factory.make(request.all(), instance.rules(), instance.messages(), instance.attributes())\n return validator.validated<T>()\n }\n}\n","import { Str } from '@orieljs/support'\n\n/** Humanizes a (possibly dotted) attribute key, e.g. \"items.0.product_name\" -> \"items.0.product name\". */\nexport function defaultAttributeName(key: string): string {\n return key\n .split('.')\n .map((segment) => Str.snake(segment).replace(/_/g, ' '))\n .join('.')\n}\n\nexport function applyReplacements(template: string, replacements: Record<string, string>): string {\n return Object.entries(replacements).reduce((message, [key, value]) => message.replaceAll(`:${key}`, value), template)\n}\n\n/** Laravel's English lang/en/validation.php, reproduced as closely as possible (see plan Notes/assumptions). */\nexport const DEFAULT_MESSAGES: Record<string, string> = {\n required: 'The :attribute field is required.',\n required_if: 'The :attribute field is required when :other is :value.',\n required_unless: 'The :attribute field is required unless :other is in :values.',\n required_with: 'The :attribute field is required when :values is present.',\n required_with_all: 'The :attribute field is required when :values are present.',\n required_without: 'The :attribute field is required when :values is not present.',\n required_without_all: 'The :attribute field is required when none of :values are present.',\n string: 'The :attribute field must be a string.',\n integer: 'The :attribute field must be an integer.',\n numeric: 'The :attribute field must be a number.',\n boolean: 'The :attribute field must be true or false.',\n array: 'The :attribute field must be an array.',\n email: 'The :attribute field must be a valid email address.',\n url: 'The :attribute field must be a valid URL.',\n uuid: 'The :attribute field must be a valid UUID.',\n alpha: 'The :attribute field must only contain letters.',\n alpha_num: 'The :attribute field must only contain letters and numbers.',\n alpha_dash: 'The :attribute field must only contain letters, numbers, dashes and underscores.',\n regex: 'The :attribute field format is invalid.',\n confirmed: 'The :attribute field confirmation does not match.',\n same: 'The :attribute field must match :other.',\n different: 'The :attribute field must be different from :other.',\n accepted: 'The :attribute field must be accepted.',\n digits: 'The :attribute field must be :digits digits.',\n date: 'The :attribute field must be a valid date.',\n before: 'The :attribute field must be a date before :date.',\n after: 'The :attribute field must be a date after :date.',\n in: 'The selected :attribute is invalid.',\n not_in: 'The selected :attribute is invalid.',\n unique: 'The :attribute has already been taken.',\n exists: 'The selected :attribute is invalid.',\n file: 'The :attribute field must be a file.',\n image: 'The :attribute field must be an image.',\n mimes: 'The :attribute field must be a file of type: :values.',\n 'max.string': 'The :attribute field must not be greater than :max characters.',\n 'max.numeric': 'The :attribute field must not be greater than :max.',\n 'max.array': 'The :attribute field must not have more than :max items.',\n 'max.file': 'The :attribute field must not be greater than :max kilobytes.',\n 'min.string': 'The :attribute field must be at least :min characters.',\n 'min.numeric': 'The :attribute field must be at least :min.',\n 'min.array': 'The :attribute field must have at least :min items.',\n 'min.file': 'The :attribute field must be at least :min kilobytes.',\n 'between.string': 'The :attribute field must be between :min and :max characters.',\n 'between.numeric': 'The :attribute field must be between :min and :max.',\n 'between.array': 'The :attribute field must have between :min and :max items.',\n 'between.file': 'The :attribute field must be between :min and :max kilobytes.',\n 'size.string': 'The :attribute field must be :size characters.',\n 'size.numeric': 'The :attribute field must be :size.',\n 'size.array': 'The :attribute field must contain :size items.',\n 'size.file': 'The :attribute field must be :size kilobytes.',\n}\n","import type { MessageBag } from '@orieljs/contracts'\n\nexport class MessageBagImpl implements MessageBag {\n private readonly items: Record<string, string[]> = {}\n\n /** Not part of the MessageBag contract — used internally by ValidatorImpl and by after() hooks. */\n add(key: string, message: string): void {\n ;(this.items[key] ??= []).push(message)\n }\n\n has(key: string): boolean {\n return (this.items[key]?.length ?? 0) > 0\n }\n\n first(key?: string): string | undefined {\n if (key !== undefined) return this.items[key]?.[0]\n for (const messages of Object.values(this.items)) {\n if (messages[0] !== undefined) return messages[0]\n }\n return undefined\n }\n\n get(key: string): string[] {\n return this.items[key] ?? []\n }\n\n all(): string[] {\n return Object.values(this.items).flat()\n }\n\n isEmpty(): boolean {\n return Object.keys(this.items).length === 0\n }\n\n count(): number {\n return this.all().length\n }\n\n toObject(): Record<string, string[]> {\n return structuredClone(this.items)\n }\n}\n","import { DatabaseManager } from '@orieljs/contracts'\nimport { inject } from '@orieljs/container'\nimport type { BuiltinRule } from '../parse'\n\n/**\n * The column to query when a unique/exists rule doesn't name one: the attribute itself, except for a\n * wildcard-expanded field like \"items.0.email\", which checks the last non-numeric segment (\"email\") rather than a\n * column literally named after the path (Laravel's guessColumnForQuery).\n */\nexport function guessColumn(attribute: string, expandedFromWildcard = false): string {\n if (!expandedFromWildcard) return attribute\n return attribute.split('.').filter((segment) => !/^\\d+$/.test(segment)).at(-1) ?? attribute\n}\n\n/** Laravel's idiom `unique:users,email,NULL,id` (and an empty or null ignore) means \"exclude nothing\". */\nfunction isNoExcept(except: unknown): boolean {\n return except === undefined || except === null || except === '' || except === 'NULL'\n}\n\n/**\n * Shared query shape behind both `unique`/`exists` string rules and `Rule.unique()`/`Rule.exists()` (Review Focus\n * #2): resolve DatabaseManager, filter table/column on value, optionally exclude a record by idColumn/except, and\n * report whether any row matches. Kept in one place so a future fix to this path can't miss one of the two callers.\n */\nexport async function matchingRecordExists(\n table: string,\n column: string,\n value: unknown,\n except?: unknown,\n idColumn = 'id',\n): Promise<boolean> {\n const db = inject(DatabaseManager)\n let query = db.connection().table(table).where(column, value)\n if (!isNoExcept(except)) query = query.where(idColumn, '!=', except)\n return query.exists()\n}\n\nexport const databaseRules: Record<string, BuiltinRule> = {\n unique: {\n validate: async (ctx) => {\n const [table, column, except, idColumn] = ctx.parameters\n return !(await matchingRecordExists(table!, column || guessColumn(ctx.attribute, ctx.expandedFromWildcard), ctx.value, except, idColumn || 'id'))\n },\n messageKey: () => 'unique',\n },\n exists: {\n validate: async (ctx) => {\n const [table, column] = ctx.parameters\n return matchingRecordExists(table!, column || guessColumn(ctx.attribute, ctx.expandedFromWildcard), ctx.value)\n },\n messageKey: () => 'exists',\n },\n}\n","import type { ValidationRule } from '@orieljs/contracts'\nimport { Arr } from '@orieljs/support'\n\n/** Everything a single rule needs to validate one concrete field. */\nexport interface RuleContext {\n /** The concrete, wildcard-expanded field path, e.g. \"items.1.name\". */\n attribute: string\n /** True when `attribute` came from expanding a wildcard pattern such as \"items.*.email\". */\n expandedFromWildcard?: boolean\n value: unknown\n parameters: string[]\n data: Record<string, unknown>\n /** Every named rule attached to this field (for size-type resolution: numeric/array/file/string). */\n ruleNames: string[]\n}\n\nexport interface BuiltinRule {\n validate(ctx: RuleContext): boolean | Promise<boolean>\n /** Which DEFAULT_MESSAGES key to use, e.g. `max.${sizeType}`. Most rules return a constant name. */\n messageKey(ctx: RuleContext): string\n /** Extra :placeholder substitutions beyond :attribute (e.g. :max, :other, :values). */\n replacements?(ctx: RuleContext): Record<string, string>\n /** Used when messageKey() isn't in DEFAULT_MESSAGES (e.g. an extend()ed rule with a custom message). */\n defaultMessage?: string\n /** Runs even when the value is missing, blank, or null under nullable (the required* family, and accepted); a failure stops the field. */\n implicit?: boolean\n}\n\nexport type ParsedRule =\n | { kind: 'named'; name: string; parameters: string[] }\n | { kind: 'object'; rule: ValidationRule }\n\nfunction splitParameters(name: string, raw: string): string[] {\n // regex/not_regex parameters are never comma-split, so a pattern containing a comma survives intact.\n return name === 'regex' || name === 'not_regex' ? [raw] : raw.split(',')\n}\n\nfunction splitOnce(value: string, separator: string): [string, string | undefined] {\n const index = value.indexOf(separator)\n return index === -1 ? [value, undefined] : [value.slice(0, index), value.slice(index + 1)]\n}\n\nexport function parseRuleSpec(spec: string | ReadonlyArray<string | ValidationRule>): ParsedRule[] {\n const items = typeof spec === 'string' ? spec.split('|') : spec\n return items\n .filter((item) => item !== '')\n .map((item): ParsedRule => {\n if (typeof item !== 'string') return { kind: 'object', rule: item }\n const [name, raw] = splitOnce(item, ':')\n return { kind: 'named', name, parameters: raw === undefined ? [] : splitParameters(name, raw) }\n })\n}\n\n/** Laravel's definition of \"empty\" for the required family: null, undefined, '' and []. false and 0 are NOT empty. */\nexport function isEmptyValue(value: unknown): boolean {\n if (value === null || value === undefined) return true\n if (typeof value === 'string') return value === ''\n if (Array.isArray(value)) return value.length === 0\n return false\n}\n\n/** Duck-types Contracts/Http's UploadedFile without importing @orieljs/http. */\nexport function isUploadedFileLike(value: unknown): value is {\n clientName: string\n mimeType: string\n size: number\n extension(): string\n arrayBuffer(): Promise<ArrayBuffer>\n} {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as Record<string, unknown>).clientName === 'string' &&\n typeof (value as Record<string, unknown>).arrayBuffer === 'function'\n )\n}\n\n/**\n * Keys that must never be followed or written when walking user input: assigning through them reaches\n * Object.prototype (or a constructor) instead of a plain data slot. Mirrors the guard in Arr.set.\n */\nexport const UNSAFE_KEYS: ReadonlySet<string> = new Set(['__proto__', 'prototype', 'constructor'])\n\n/**\n * Expands a `*`-wildcard rule pattern (e.g. \"items.*.name\") into every concrete path present in `data`\n * (e.g. [\"items.0.name\", \"items.1.name\"]). A pattern with no `*` is returned unchanged. A `*` segment whose\n * container is missing, not an array and not a plain object expands to nothing for that branch (Review Focus #4:\n * every reported error is keyed by a concrete path, never the literal pattern). Object keys in UNSAFE_KEYS are\n * treated as absent, so a JSON body like {\"items\":{\"__proto__\":{...}}} never yields a path through the prototype.\n */\nexport function expandWildcardKeys(pattern: string, data: Record<string, unknown>): string[] {\n const segments = pattern.split('.')\n let paths = ['']\n for (const segment of segments) {\n const next: string[] = []\n for (const base of paths) {\n const prefix = base === '' ? '' : `${base}.`\n if (segment !== '*') {\n next.push(`${prefix}${segment}`)\n continue\n }\n const container = Arr.get<unknown>(data, base === '' ? undefined : base)\n if (Array.isArray(container)) {\n container.forEach((_, index) => next.push(`${prefix}${index}`))\n } else if (container !== null && typeof container === 'object') {\n Object.keys(container)\n .filter((key) => !UNSAFE_KEYS.has(key))\n .forEach((key) => next.push(`${prefix}${key}`))\n }\n }\n paths = next\n }\n return paths\n}\n","import type { BuiltinRule } from '../parse'\nimport { isUploadedFileLike } from '../parse'\n\nconst IMAGE_EXTENSIONS = new Set(['jpg', 'jpeg', 'png', 'bmp', 'gif', 'svg', 'webp'])\n\nexport const fileRules: Record<string, BuiltinRule> = {\n file: { validate: (ctx) => isUploadedFileLike(ctx.value), messageKey: () => 'file' },\n image: {\n validate: (ctx) => {\n if (!isUploadedFileLike(ctx.value)) return false\n if (ctx.value.mimeType.startsWith('image/')) return true\n return IMAGE_EXTENSIONS.has(ctx.value.extension().toLowerCase())\n },\n messageKey: () => 'image',\n },\n mimes: {\n validate: (ctx) => {\n if (!isUploadedFileLike(ctx.value)) return false\n const allowed = ctx.parameters.map((p) => p.toLowerCase())\n return allowed.includes(ctx.value.extension().toLowerCase())\n },\n messageKey: () => 'mimes',\n replacements: (ctx) => ({ values: ctx.parameters.join(', ') }),\n },\n}\n","import { Arr } from '@orieljs/support'\nimport type { BuiltinRule, RuleContext } from '../parse'\nimport { InvalidRuleParameterError } from '../errors'\nimport { defaultAttributeName } from '../messages'\n\nconst EMAIL_RE = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i\nconst ALPHA_RE = /^[A-Za-z]+$/\nconst ALPHA_NUM_RE = /^[A-Za-z0-9]+$/\nconst ALPHA_DASH_RE = /^[A-Za-z0-9_-]+$/\nconst ACCEPTED_VALUES: unknown[] = ['yes', 'on', 1, '1', true, 'true']\n\nfunction compileRegex(raw: string): RegExp {\n const match = /^\\/(.*)\\/([a-z]*)$/.exec(raw)\n try {\n return match ? new RegExp(match[1]!, match[2]) : new RegExp(raw)\n } catch (error) {\n throw new InvalidRuleParameterError('regex', raw, error instanceof Error ? error.message : String(error))\n }\n}\n\n/**\n * Shapes a string must have before it counts as a date. Date.parse alone is far too lenient (V8 reads \"1\" as the\n * year 2001), so a value needs an ISO date, a slashed/dotted/dashed day-month-year, or a month name with a number.\n */\nconst DATE_SHAPES = [\n /^\\d{4}-\\d{1,2}-\\d{1,2}(?:[T\\s].*)?$/,\n /^\\d{1,2}[/.-]\\d{1,2}[/.-]\\d{2,4}(?:\\s.*)?$/,\n /^(?=.*\\d).*\\b(?:jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)[a-z]*\\b/i,\n]\nconst DATE_ONLY_RE = /^(\\d{4})-(\\d{2})-(\\d{2})$/\n\n/**\n * Parses a user-supplied date string to epoch milliseconds, or NaN. A bare YYYY-MM-DD means local midnight, like\n * PHP's strtotime, so it compares sensibly against `today`/`tomorrow`.\n */\nfunction parseDate(value: string): number {\n const trimmed = value.trim()\n if (!DATE_SHAPES.some((shape) => shape.test(trimmed))) return Number.NaN\n const dateOnly = DATE_ONLY_RE.exec(trimmed)\n if (dateOnly) {\n const [, y, m, d] = dateOnly.map(Number) as [number, number, number, number]\n const local = new Date(y, m - 1, d)\n return local.getMonth() === m - 1 && local.getDate() === d ? local.getTime() : Number.NaN\n }\n return Date.parse(trimmed)\n}\n\nfunction startOfDay(offsetDays: number): number {\n const date = new Date()\n date.setHours(0, 0, 0, 0)\n date.setDate(date.getDate() + offsetDays)\n return date.getTime()\n}\n\nconst RELATIVE_RE = /^([+-]\\d+)\\s*(second|minute|hour|day|week|month|year)s?$/i\n\n/** strtotime's keywords (today, tomorrow, yesterday, now) and \"+N unit\"/\"-N unit\" offsets from now, or undefined. */\nfunction relativeDate(param: string): number | undefined {\n switch (param.trim().toLowerCase()) {\n case 'now':\n return Date.now()\n case 'today':\n return startOfDay(0)\n case 'tomorrow':\n return startOfDay(1)\n case 'yesterday':\n return startOfDay(-1)\n }\n const match = RELATIVE_RE.exec(param.trim())\n if (!match) return undefined\n const amount = Number(match[1])\n const date = new Date()\n switch (match[2]!.toLowerCase()) {\n case 'second':\n date.setSeconds(date.getSeconds() + amount)\n break\n case 'minute':\n date.setMinutes(date.getMinutes() + amount)\n break\n case 'hour':\n date.setHours(date.getHours() + amount)\n break\n case 'day':\n date.setDate(date.getDate() + amount)\n break\n case 'week':\n date.setDate(date.getDate() + amount * 7)\n break\n case 'month':\n date.setMonth(date.getMonth() + amount)\n break\n case 'year':\n date.setFullYear(date.getFullYear() + amount)\n break\n }\n return date.getTime()\n}\n\n/** An attribute path such as \"starts_at\" or \"event.starts_at\". */\nconst FIELD_REFERENCE_RE = /^[A-Za-z_][\\w-]*(?:\\.[\\w-]+)*$/\n\n/**\n * Resolves a before/after parameter, in order: another field's date value, a relative keyword/offset, a literal\n * date. A parameter shaped like a field name whose field is missing or not a date gives NaN (the user's value\n * fails). Anything else that can't be parsed is a mistake in the rule itself, so it throws a 'Server' error\n * instead of blaming the user's input.\n */\nfunction resolveDateParam(rule: string, param: string, data: Record<string, unknown>): number {\n const fieldValue = Arr.get<unknown>(data, param)\n if (typeof fieldValue === 'string') {\n const parsed = parseDate(fieldValue)\n if (!Number.isNaN(parsed)) return parsed\n }\n const relative = relativeDate(param)\n if (relative !== undefined) return relative\n const literal = parseDate(param)\n if (!Number.isNaN(literal)) return literal\n if (FIELD_REFERENCE_RE.test(param)) return Number.NaN\n throw new InvalidRuleParameterError(rule, param, 'expected a date, today/tomorrow/yesterday/now, \"+N unit\", or a field name')\n}\n\nfunction compareDate(ctx: RuleContext, rule: 'before' | 'after'): boolean {\n const target = resolveDateParam(rule, ctx.parameters[0] ?? '', ctx.data)\n if (typeof ctx.value !== 'string') return false\n const value = parseDate(ctx.value)\n if (Number.isNaN(value) || Number.isNaN(target)) return false\n return rule === 'before' ? value < target : value > target\n}\n\nexport const formatRules: Record<string, BuiltinRule> = {\n email: { validate: (ctx) => typeof ctx.value === 'string' && EMAIL_RE.test(ctx.value), messageKey: () => 'email' },\n url: {\n validate: (ctx) => {\n if (typeof ctx.value !== 'string') return false\n try {\n new URL(ctx.value)\n return true\n } catch {\n return false\n }\n },\n messageKey: () => 'url',\n },\n uuid: { validate: (ctx) => typeof ctx.value === 'string' && UUID_RE.test(ctx.value), messageKey: () => 'uuid' },\n alpha: { validate: (ctx) => typeof ctx.value === 'string' && ALPHA_RE.test(ctx.value), messageKey: () => 'alpha' },\n alpha_num: {\n validate: (ctx) => typeof ctx.value === 'string' && ALPHA_NUM_RE.test(ctx.value),\n messageKey: () => 'alpha_num',\n },\n alpha_dash: {\n validate: (ctx) => typeof ctx.value === 'string' && ALPHA_DASH_RE.test(ctx.value),\n messageKey: () => 'alpha_dash',\n },\n regex: {\n validate: (ctx) => typeof ctx.value === 'string' && compileRegex(ctx.parameters[0] ?? '').test(ctx.value),\n messageKey: () => 'regex',\n },\n confirmed: {\n validate: (ctx: RuleContext) => ctx.value === Arr.get(ctx.data, `${ctx.attribute}_confirmation`),\n messageKey: () => 'confirmed',\n },\n same: {\n validate: (ctx) => ctx.value === Arr.get(ctx.data, ctx.parameters[0] ?? ''),\n messageKey: () => 'same',\n replacements: (ctx) => ({ other: defaultAttributeName(ctx.parameters[0] ?? '') }),\n },\n different: {\n validate: (ctx) => ctx.value !== Arr.get(ctx.data, ctx.parameters[0] ?? ''),\n messageKey: () => 'different',\n replacements: (ctx) => ({ other: defaultAttributeName(ctx.parameters[0] ?? '') }),\n },\n accepted: { implicit: true, validate: (ctx) => ACCEPTED_VALUES.includes(ctx.value), messageKey: () => 'accepted' },\n digits: {\n validate: (ctx) =>\n typeof ctx.value !== 'object' && new RegExp(`^\\\\d{${ctx.parameters[0]}}$`).test(String(ctx.value)),\n messageKey: () => 'digits',\n replacements: (ctx) => ({ digits: ctx.parameters[0] ?? '' }),\n },\n date: {\n validate: (ctx) => typeof ctx.value === 'string' && !Number.isNaN(parseDate(ctx.value)),\n messageKey: () => 'date',\n },\n before: {\n validate: (ctx) => compareDate(ctx, 'before'),\n messageKey: () => 'before',\n replacements: (ctx) => ({ date: ctx.parameters[0] ?? '' }),\n },\n after: {\n validate: (ctx) => compareDate(ctx, 'after'),\n messageKey: () => 'after',\n replacements: (ctx) => ({ date: ctx.parameters[0] ?? '' }),\n },\n}\n","import { Arr } from '@orieljs/support'\nimport type { BuiltinRule, RuleContext } from '../parse'\nimport { isEmptyValue } from '../parse'\n\nfunction isFieldPresent(field: string, data: Record<string, unknown>): boolean {\n return Arr.has(data, field) && !isEmptyValue(Arr.get(data, field))\n}\n\nfunction anyPresent(fields: string[], data: Record<string, unknown>): boolean {\n return fields.some((field) => isFieldPresent(field, data))\n}\n\nfunction allPresent(fields: string[], data: Record<string, unknown>): boolean {\n return fields.every((field) => isFieldPresent(field, data))\n}\n\nexport const presenceRules: Record<string, BuiltinRule> = {\n required: {\n implicit: true,\n validate: (ctx: RuleContext) => !isEmptyValue(ctx.value),\n messageKey: () => 'required',\n },\n required_if: {\n implicit: true,\n validate: (ctx: RuleContext) => {\n const [other, ...values] = ctx.parameters\n const applies = values.includes(String(Arr.get(ctx.data, other)))\n return !applies || !isEmptyValue(ctx.value)\n },\n messageKey: () => 'required_if',\n replacements: (ctx) => ({ other: ctx.parameters[0] ?? '', value: ctx.parameters.slice(1).join(', ') }),\n },\n required_unless: {\n implicit: true,\n validate: (ctx: RuleContext) => {\n const [other, ...values] = ctx.parameters\n const applies = !values.includes(String(Arr.get(ctx.data, other)))\n return !applies || !isEmptyValue(ctx.value)\n },\n messageKey: () => 'required_unless',\n replacements: (ctx) => ({ other: ctx.parameters[0] ?? '', values: ctx.parameters.slice(1).join(', ') }),\n },\n required_with: {\n implicit: true,\n validate: (ctx: RuleContext) => !anyPresent(ctx.parameters, ctx.data) || !isEmptyValue(ctx.value),\n messageKey: () => 'required_with',\n replacements: (ctx) => ({ values: ctx.parameters.join(' / ') }),\n },\n required_with_all: {\n implicit: true,\n validate: (ctx: RuleContext) => !allPresent(ctx.parameters, ctx.data) || !isEmptyValue(ctx.value),\n messageKey: () => 'required_with_all',\n replacements: (ctx) => ({ values: ctx.parameters.join(' / ') }),\n },\n required_without: {\n implicit: true,\n validate: (ctx: RuleContext) => ctx.parameters.every((f) => isFieldPresent(f, ctx.data)) || !isEmptyValue(ctx.value),\n messageKey: () => 'required_without',\n replacements: (ctx) => ({ values: ctx.parameters.join(' / ') }),\n },\n required_without_all: {\n implicit: true,\n validate: (ctx: RuleContext) => anyPresent(ctx.parameters, ctx.data) || !isEmptyValue(ctx.value),\n messageKey: () => 'required_without_all',\n replacements: (ctx) => ({ values: ctx.parameters.join(' / ') }),\n },\n}\n","import type { BuiltinRule } from '../parse'\n\nconst BOOLEAN_VALUES: unknown[] = [true, false, 0, 1, '0', '1']\n\n/** PHP's is_numeric for strings: optional surrounding whitespace and sign, decimal digits, optional exponent. */\nconst NUMERIC_STRING_RE = /^\\s*[+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eE][+-]?\\d+)?\\s*$/\n\n/**\n * Laravel's `numeric` (PHP is_numeric): a finite number, or a decimal string. Unlike `Number()`, it rejects\n * \"Infinity\", hex/binary/octal literals (\"0x1F\", \"0b101\", \"0o7\") and the empty string.\n */\nexport function isNumeric(value: unknown): boolean {\n if (typeof value === 'number') return Number.isFinite(value)\n return typeof value === 'string' && NUMERIC_STRING_RE.test(value)\n}\n\nexport const typeRules: Record<string, BuiltinRule> = {\n string: { validate: (ctx) => typeof ctx.value === 'string', messageKey: () => 'string' },\n integer: {\n validate: (ctx) => typeof ctx.value !== 'object' && /^-?\\d+$/.test(String(ctx.value).trim()),\n messageKey: () => 'integer',\n },\n numeric: {\n validate: (ctx) => isNumeric(ctx.value),\n messageKey: () => 'numeric',\n },\n boolean: { validate: (ctx) => BOOLEAN_VALUES.includes(ctx.value), messageKey: () => 'boolean' },\n array: { validate: (ctx) => Array.isArray(ctx.value), messageKey: () => 'array' },\n}\n","import type { BuiltinRule, RuleContext } from '../parse'\nimport { isUploadedFileLike } from '../parse'\nimport { isNumeric } from './type'\n\ntype SizeType = 'numeric' | 'array' | 'file' | 'string'\n\nfunction hasAny(ctx: RuleContext, names: string[]): boolean {\n return names.some((name) => ctx.ruleNames.includes(name))\n}\n\n/** A JSON object is a PHP associative array, so it's counted like one. */\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (typeof value !== 'object' || value === null) return false\n const proto: unknown = Object.getPrototypeOf(value)\n return proto === Object.prototype || proto === null\n}\n\n/**\n * What a size rule measures and which message family it reports, decided in one place so the check and the\n * message always agree (Laravel's getSize + getAttributeType):\n * - numeric/integer rule: the number itself (a non-numeric value falls back to its string length, which the\n * numeric rule rejects anyway);\n * - an array (or plain object): its item count;\n * - an uploaded file: its size in fractional kilobytes;\n * - a file/image rule on something that isn't a file: NaN, so every size comparison fails;\n * - anything else: the length of its string form (a number without a numeric rule counts its digits).\n */\nfunction measure(ctx: RuleContext): { type: SizeType; size: number } {\n const { value } = ctx\n if (hasAny(ctx, ['numeric', 'integer'])) {\n return { type: 'numeric', size: isNumeric(value) ? Number(value) : stringLength(value) }\n }\n if (Array.isArray(value)) return { type: 'array', size: value.length }\n if (isUploadedFileLike(value)) return { type: 'file', size: value.size / 1024 }\n if (hasAny(ctx, ['file', 'image'])) return { type: 'file', size: Number.NaN }\n if (isPlainObject(value)) return { type: 'array', size: Object.keys(value).length }\n if (hasAny(ctx, ['array'])) return { type: 'array', size: stringLength(value) }\n return { type: 'string', size: stringLength(value) }\n}\n\nfunction stringLength(value: unknown): number {\n if (value === null || value === undefined) return 0\n return [...String(value)].length\n}\n\nfunction sizeOf(ctx: RuleContext): number {\n return measure(ctx).size\n}\n\nfunction sizeType(ctx: RuleContext): SizeType {\n return measure(ctx).type\n}\n\nexport const sizeRules: Record<string, BuiltinRule> = {\n max: {\n validate: (ctx) => sizeOf(ctx) <= Number(ctx.parameters[0]),\n messageKey: (ctx) => `max.${sizeType(ctx)}`,\n replacements: (ctx) => ({ max: ctx.parameters[0] ?? '' }),\n },\n min: {\n validate: (ctx) => sizeOf(ctx) >= Number(ctx.parameters[0]),\n messageKey: (ctx) => `min.${sizeType(ctx)}`,\n replacements: (ctx) => ({ min: ctx.parameters[0] ?? '' }),\n },\n between: {\n validate: (ctx) => {\n const size = sizeOf(ctx)\n return size >= Number(ctx.parameters[0]) && size <= Number(ctx.parameters[1])\n },\n messageKey: (ctx) => `between.${sizeType(ctx)}`,\n replacements: (ctx) => ({ min: ctx.parameters[0] ?? '', max: ctx.parameters[1] ?? '' }),\n },\n size: {\n validate: (ctx) => sizeOf(ctx) === Number(ctx.parameters[0]),\n messageKey: (ctx) => `size.${sizeType(ctx)}`,\n replacements: (ctx) => ({ size: ctx.parameters[0] ?? '' }),\n },\n in: { validate: (ctx) => ctx.parameters.includes(String(ctx.value)), messageKey: () => 'in' },\n not_in: { validate: (ctx) => !ctx.parameters.includes(String(ctx.value)), messageKey: () => 'not_in' },\n}\n","import type { BuiltinRule } from './parse'\nimport { databaseRules } from './rules/database'\nimport { fileRules } from './rules/file'\nimport { formatRules } from './rules/format'\nimport { presenceRules } from './rules/presence'\nimport { sizeRules } from './rules/size'\nimport { typeRules } from './rules/type'\n\n/** Every built-in rule, merged. Later tasks (database rules) add their own spread here. */\nexport const builtinRules: Record<string, BuiltinRule> = {\n ...presenceRules,\n ...typeRules,\n ...formatRules,\n ...sizeRules,\n ...fileRules,\n ...databaseRules,\n}\n","import type { ValidationRule } from '@orieljs/contracts'\nimport { applyReplacements, DEFAULT_MESSAGES, defaultAttributeName } from './messages'\nimport { guessColumn, matchingRecordExists } from './rules/database'\n\n/**\n * Base for the fluent builders. Each one reports under a built-in rule name (`in`, `unique`, `exists`), so when it\n * runs inside a Validator its failure goes through exactly the same lookup as the string rule: custom messages\n * (\"email.unique\", \"items.*.email.unique\", \"unique\"), custom attributes, then the default text. Called directly\n * as a plain ValidationRule, validate() fails with the default English message.\n */\nexport abstract class BuiltinRuleObject implements ValidationRule {\n abstract readonly ruleName: string\n\n abstract passes(attribute: string, value: unknown, data: Record<string, unknown>, expandedFromWildcard?: boolean): boolean | Promise<boolean>\n\n // Declares all 4 contract parameters so a subclass's inferred type (from `Rule.in(...)` etc.) still accepts a\n // call with the full 4-arg ValidationRule.validate signature, as Rule.test.ts makes.\n async validate(attribute: string, value: unknown, fail: (message: string) => void, data: Record<string, unknown>, expandedFromWildcard = false): Promise<void> {\n if (await this.passes(attribute, value, data, expandedFromWildcard)) return\n fail(applyReplacements(DEFAULT_MESSAGES[this.ruleName]!, { attribute: defaultAttributeName(attribute) }))\n }\n}\n\nclass InRule extends BuiltinRuleObject {\n readonly ruleName = 'in'\n\n constructor(private readonly values: readonly unknown[]) {\n super()\n }\n\n passes(_attribute: string, value: unknown): boolean {\n return this.values.map(String).includes(String(value))\n }\n}\n\n/** Structural shape of Database's Model — duck-typed so this package never imports `@orieljs/database` (B27). */\ninterface ModelInstanceLike {\n getKey(): unknown\n getKeyName(): string\n}\n\nfunction isModelInstance(value: unknown): value is ModelInstanceLike {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as ModelInstanceLike).getKey === 'function' &&\n typeof (value as ModelInstanceLike).getKeyName === 'function'\n )\n}\n\nclass UniqueRule extends BuiltinRuleObject {\n readonly ruleName = 'unique'\n private exceptId: unknown\n private idColumnName: string | undefined\n\n constructor(\n private readonly table: string,\n private readonly column?: string,\n ) {\n super()\n }\n\n /**\n * Excludes the current record from the uniqueness check. Laravel's `Rule::unique('users')->ignore($user)` accepts\n * a model directly (the common case: \"update your profile without changing your email\"), so a model instance is\n * bound by its key (`getKey()`/`getKeyName()`), not the object itself — the object would reach the query builder\n * as an opaque value and either be rejected by the driver or stringified (B27). A plain id still works as before;\n * null (or \"NULL\") excludes nothing.\n */\n ignore(id: unknown, idColumn?: string): this {\n if (isModelInstance(id)) {\n this.exceptId = id.getKey()\n this.idColumnName = idColumn ?? id.getKeyName()\n } else {\n this.exceptId = id\n this.idColumnName = idColumn ?? 'id'\n }\n return this\n }\n\n async passes(attribute: string, value: unknown, _data?: Record<string, unknown>, expandedFromWildcard = false): Promise<boolean> {\n const column = this.column ?? guessColumn(attribute, expandedFromWildcard)\n return !(await matchingRecordExists(this.table, column, value, this.exceptId, this.idColumnName ?? 'id'))\n }\n}\n\nclass ExistsRule extends BuiltinRuleObject {\n readonly ruleName = 'exists'\n\n constructor(\n private readonly table: string,\n private readonly column?: string,\n ) {\n super()\n }\n\n passes(attribute: string, value: unknown, _data?: Record<string, unknown>, expandedFromWildcard = false): Promise<boolean> {\n return matchingRecordExists(this.table, this.column ?? guessColumn(attribute, expandedFromWildcard), value)\n }\n}\n\n/** Fluent rule-object builders, for when a plain string rule can't express what's needed (e.g. .ignore()). */\nexport const Rule = {\n in: (values: readonly unknown[]): InRule => new InRule(values),\n unique: (table: string, column?: string): UniqueRule => new UniqueRule(table, column),\n exists: (table: string, column?: string): ExistsRule => new ExistsRule(table, column),\n}\n","import type { Rules, Validator } from '@orieljs/contracts'\nimport { Arr } from '@orieljs/support'\nimport { UnknownValidationRuleError, ValidationErrorImpl } from './errors'\nimport { MessageBagImpl } from './MessageBag'\nimport { BuiltinRuleObject } from './Rule'\nimport { applyReplacements, DEFAULT_MESSAGES, defaultAttributeName } from './messages'\nimport type { BuiltinRule, ParsedRule, RuleContext } from './parse'\nimport { expandWildcardKeys, parseRuleSpec, UNSAFE_KEYS } from './parse'\n\nconst SKIPPED_MODIFIERS = new Set(['bail', 'nullable', 'sometimes'])\n\n/**\n * Rebuilds a nested structure from flat dot-paths, the way Laravel's validated() does for wildcard fields.\n * `Arr.undot` (from @orieljs/support) always builds plain objects; it can't know \"items.0\"/\"items.1\" should\n * become an array. This walks the same way, then promotes any container it created itself whose keys are exactly\n * \"0\", \"1\", \"2\", … in order into a real array. Leaf values copied from the input (a Date, an uploaded file, an\n * object that happens to have \"0\"/\"1\" keys) are returned untouched, by identity. A path with a segment in\n * UNSAFE_KEYS is dropped, so nothing can be written through to Object.prototype. The input is never mutated.\n */\nfunction buildNested(flat: Record<string, unknown>): Record<string, unknown> {\n const root: Record<string, unknown> = {}\n const created = new Set<object>([root])\n for (const [path, value] of Object.entries(flat)) {\n const parts = path.split('.')\n if (parts.some((part) => UNSAFE_KEYS.has(part))) continue\n let current = root\n for (const part of parts.slice(0, -1)) {\n const existing = Object.hasOwn(current, part) ? current[part] : undefined\n if (typeof existing === 'object' && existing !== null && created.has(existing)) {\n current = existing as Record<string, unknown>\n continue\n }\n const container = cloneContainer(existing)\n created.add(container)\n current[part] = container\n current = container\n }\n current[parts.at(-1)!] = value\n }\n return arrayify(root, created) as Record<string, unknown>\n}\n\nfunction isPlainContainer(value: unknown): value is Record<string, unknown> {\n if (Array.isArray(value)) return true\n if (typeof value !== 'object' || value === null) return false\n const proto: unknown = Object.getPrototypeOf(value)\n return proto === Object.prototype || proto === null\n}\n\n/**\n * A fresh container to write a child path into. When a parent key was already copied from the input (rules on both\n * \"user\" and \"user.name\"), its plain contents are kept (Laravel returns the whole parent) but copied, so the input\n * is never mutated. Anything else (missing, a scalar, a class instance) starts empty.\n */\nfunction cloneContainer(existing: unknown): Record<string, unknown> {\n const container: Record<string, unknown> = {}\n if (!isPlainContainer(existing)) return container\n for (const [key, value] of Object.entries(existing)) {\n if (!UNSAFE_KEYS.has(key)) container[key] = value\n }\n return container\n}\n\nfunction arrayify(node: unknown, created: ReadonlySet<object>): unknown {\n if (node === null || typeof node !== 'object' || !created.has(node)) return node\n const entries = Object.entries(node as Record<string, unknown>).map(([k, v]) => [k, arrayify(v, created)] as const)\n const keys = entries.map(([k]) => k)\n const isArrayLike = keys.length > 0 && keys.every((k, i) => k === String(i))\n return isArrayLike ? entries.map(([, v]) => v) : Object.fromEntries(entries)\n}\n\n/**\n * Runs each field's rules the way Laravel's Validator does:\n * - a missing key, or a string that is blank after trimming, only runs implicit rules (the required* family and\n * accepted); every other rule, including ValidationRule objects, is skipped for it;\n * - an explicit null runs every rule unless the field is `nullable` (then only implicit rules run), so\n * `{ age: null }` still fails `integer`;\n * - `sometimes` skips a missing field entirely;\n * - a field stops validating after its first failure under `bail`, or after any implicit rule fails.\n */\nexport class ValidatorImpl implements Validator {\n private bag: MessageBagImpl | undefined\n private ranPromise: Promise<boolean> | undefined\n private readonly afterCallbacks: Array<(validator: Validator) => void | Promise<void>> = []\n\n constructor(\n private readonly data: Record<string, unknown>,\n private readonly rules: Rules,\n private readonly customMessages: Record<string, string>,\n private readonly customAttributes: Record<string, string>,\n private readonly registry: Record<string, BuiltinRule>,\n private readonly errorBagName = 'default',\n ) {}\n\n after(callback: (validator: Validator) => void | Promise<void>): this {\n this.afterCallbacks.push(callback)\n return this\n }\n\n /** Not part of the Validator contract — lets an after() hook add a failure (MessageBag itself is read-only). */\n fail(field: string, message: string): void {\n this.bag ??= new MessageBagImpl()\n this.bag.add(field, message)\n }\n\n async passes(): Promise<boolean> {\n this.ranPromise ??= this.run()\n return this.ranPromise\n }\n\n async fails(): Promise<boolean> {\n return !(await this.passes())\n }\n\n errors(): MessageBagImpl {\n return this.bag ?? new MessageBagImpl()\n }\n\n async validated<T = Record<string, unknown>>(): Promise<T> {\n if (!(await this.passes())) throw new ValidationErrorImpl(this.bag!.toObject(), this.errorBagName)\n const flat: Record<string, unknown> = {}\n for (const pattern of Object.keys(this.rules)) {\n for (const field of this.fieldsFor(pattern)) {\n if (Arr.has(this.data, field)) flat[field] = Arr.get(this.data, field)\n }\n }\n return buildNested(flat) as T\n }\n\n private fieldsFor(pattern: string): string[] {\n return pattern.includes('*') ? expandWildcardKeys(pattern, this.data) : [pattern]\n }\n\n private async run(): Promise<boolean> {\n this.bag = new MessageBagImpl()\n\n for (const [pattern, spec] of Object.entries(this.rules)) {\n const parsed = parseRuleSpec(spec)\n const names = parsed.filter((r): r is Extract<ParsedRule, { kind: 'named' }> => r.kind === 'named').map((r) => r.name)\n const bail = names.includes('bail')\n const nullable = names.includes('nullable')\n const sometimes = names.includes('sometimes')\n\n for (const field of this.fieldsFor(pattern)) {\n const present = Arr.has(this.data, field)\n if (sometimes && !present) continue\n\n const value = Arr.get(this.data, field)\n const isNull = value === null || value === undefined\n const isBlank = typeof value === 'string' && value.trim() === ''\n\n for (const rule of parsed) {\n if (rule.kind === 'named' && SKIPPED_MODIFIERS.has(rule.name)) continue\n const implicit = rule.kind === 'named' && (this.registry[rule.name]?.implicit ?? false)\n // Laravel's presentOrRuleIsImplicit: a missing key or a blank string only runs implicit rules.\n if (!implicit && (!present || isBlank)) continue\n // Laravel's isNotNullIfMarkedAsNullable: nullable + null only runs implicit rules.\n if (!implicit && nullable && isNull) continue\n\n const message = await this.runRule(rule, field, pattern, value, names)\n if (message !== undefined) {\n this.bag.add(field, message)\n // Laravel's shouldStopValidating: bail stops at the first failure; a failed implicit rule always stops.\n if (bail || implicit) break\n }\n }\n }\n }\n\n for (const callback of this.afterCallbacks) await callback(this)\n return this.bag.isEmpty()\n }\n\n private async runRule(\n rule: ParsedRule,\n field: string,\n pattern: string,\n value: unknown,\n ruleNames: string[],\n ): Promise<string | undefined> {\n const expanded = pattern.includes('*')\n if (rule.kind === 'object') {\n if (rule.rule instanceof BuiltinRuleObject) {\n if (await rule.rule.passes(field, value, this.data, expanded)) return undefined\n const ctx = { attribute: field, expandedFromWildcard: expanded, value, parameters: [], data: this.data, ruleNames }\n return this.failureMessage(rule.rule.ruleName, this.registry[rule.rule.ruleName], ctx, pattern)\n }\n let failure: string | undefined\n await rule.rule.validate(field, value, (message) => { failure = message }, this.data)\n return failure\n }\n\n const builtin = this.registry[rule.name]\n if (!builtin) throw new UnknownValidationRuleError(rule.name)\n\n const ctx = { attribute: field, expandedFromWildcard: expanded, value, parameters: rule.parameters, data: this.data, ruleNames }\n if (await builtin.validate(ctx)) return undefined\n return this.failureMessage(rule.name, builtin, ctx, pattern)\n }\n\n /** Custom message (concrete field, then wildcard pattern, then rule name) or the default, with :attribute filled. */\n private failureMessage(name: string, builtin: BuiltinRule | undefined, ctx: RuleContext, pattern: string): string {\n const field = ctx.attribute\n const template =\n this.customMessages[`${field}.${name}`] ??\n this.customMessages[`${pattern}.${name}`] ??\n this.customMessages[name] ??\n DEFAULT_MESSAGES[builtin?.messageKey(ctx) ?? name] ??\n builtin?.defaultMessage ??\n 'The :attribute field is invalid.'\n\n const display = this.customAttributes[field] ?? this.customAttributes[pattern] ?? defaultAttributeName(field)\n return applyReplacements(template, { attribute: display, ...(builtin?.replacements?.(ctx) ?? {}) })\n }\n}\n","import type { RuleCallback, Rules, ValidationFactory } from '@orieljs/contracts'\nimport type { BuiltinRule } from './parse'\nimport { builtinRules } from './registry'\nimport { ValidatorImpl } from './Validator'\n\nexport class ValidationFactoryImpl implements ValidationFactory {\n private readonly extended: Record<string, BuiltinRule> = {}\n\n make(\n data: Record<string, unknown>,\n rules: Rules,\n messages: Record<string, string> = {},\n attributes: Record<string, string> = {},\n ): ValidatorImpl {\n return new ValidatorImpl(data, rules, messages, attributes, { ...builtinRules, ...this.extended })\n }\n\n extend(name: string, callback: RuleCallback, message?: string): void {\n this.extended[name] = {\n validate: (ctx) => callback(ctx.attribute, ctx.value, ctx.parameters, ctx.data),\n messageKey: () => name,\n defaultMessage: message ?? 'The :attribute field is invalid.',\n }\n }\n}\n","import type { ValidationFactory } from '@orieljs/contracts'\nimport { ValidationFactory as ValidationFactoryToken } from '@orieljs/contracts'\nimport { facade } from '@orieljs/support'\n\n/** Laravel's Validator facade: Validator.make(...)/Validator.extend(...), proxied to the resolved ValidationFactory. */\nexport const Validator = facade<ValidationFactory>(ValidationFactoryToken)\n","import { ValidationFactory as ValidationFactoryToken } from '@orieljs/contracts'\nimport { ServiceProvider } from '@orieljs/support'\nimport { ValidationFactoryImpl } from './ValidationFactory'\n\nexport class ValidationServiceProvider extends ServiceProvider {\n override register(): void {\n this.app.singleton(ValidationFactoryToken, () => new ValidationFactoryImpl())\n }\n}\n","import { AuthServiceProvider } from '@orieljs/auth'\nimport { BusServiceProvider } from '@orieljs/bus'\nimport { CacheServiceProvider } from '@orieljs/cache'\nimport { ConsoleServiceProvider } from '@orieljs/console'\nimport type { ServiceProviderClass } from '@orieljs/contracts'\nimport { CookieServiceProvider } from '@orieljs/cookie'\nimport { DatabaseServiceProvider } from '@orieljs/database'\nimport { EncryptionServiceProvider } from '@orieljs/encryption'\nimport { EventServiceProvider } from '@orieljs/events'\nimport { FilesystemServiceProvider } from '@orieljs/filesystem'\nimport { HashingServiceProvider } from '@orieljs/hashing'\nimport { HttpServiceProvider } from '@orieljs/http'\nimport { LogServiceProvider } from '@orieljs/log'\nimport { MailServiceProvider } from '@orieljs/mail'\nimport { NotificationsServiceProvider } from '@orieljs/notifications'\nimport { PipelineServiceProvider } from '@orieljs/pipeline'\nimport { QueueServiceProvider } from '@orieljs/queue'\nimport { RoutingServiceProvider } from '@orieljs/routing'\nimport { SessionServiceProvider } from '@orieljs/session'\nimport { ValidationServiceProvider } from '@orieljs/validation'\nimport { ViewServiceProvider } from '@orieljs/view'\n\n/**\n * The framework's providers, in dependency order: each one's register() and boot() may rely on the ones before it\n * (the web group needs Encryption, Cookie and Session before Auth and Routing; Queue needs Database for batches).\n * The app's own providers are registered after these.\n */\nexport function defaultProviders(): ServiceProviderClass[] {\n return [\n PipelineServiceProvider, EncryptionServiceProvider, CookieServiceProvider, SessionServiceProvider,\n HashingServiceProvider, LogServiceProvider, EventServiceProvider, CacheServiceProvider,\n FilesystemServiceProvider, DatabaseServiceProvider, QueueServiceProvider, BusServiceProvider,\n MailServiceProvider, NotificationsServiceProvider, ValidationServiceProvider, AuthServiceProvider,\n ViewServiceProvider, RoutingServiceProvider, HttpServiceProvider, ConsoleServiceProvider,\n ]\n}\n","import { Application as FoundationApplication, ApplicationBuilder } from '@orieljs/foundation'\nimport { defaultProviders } from './providers'\n\n/** The application class apps use: configure() includes the framework's providers, as Laravel's does. */\nexport class Application extends FoundationApplication {\n constructor(basePath: string) {\n super(basePath)\n // Bind this class too, so inject(Application) from '@orieljs/framework' returns the running app.\n this.instance(Application, this)\n }\n\n static override configure(options: { basePath: string }): ApplicationBuilder {\n return new ApplicationBuilder(new Application(options.basePath)).withProviders(defaultProviders())\n }\n}\n","import { BusDispatcher, EventDispatcher, FilesystemManager, MailManager, QueueManager } from '@orieljs/contracts'\nimport { Notification as BaseNotification } from '@orieljs/notifications'\nimport { facade } from '@orieljs/support'\nimport { BusFake, EventFake, MailFake, NotificationFake, QueueFake, StorageFake } from '@orieljs/testing'\n\n// The component facades don't know about Testing; the framework adds Laravel's X::fake() on top.\nexport const Mail = facade(MailManager, { fake: (...args: Parameters<typeof MailFake.fake>) => MailFake.fake(...args) })\nexport const Queue = facade(QueueManager, { fake: (...args: Parameters<typeof QueueFake.fake>) => QueueFake.fake(...args) })\nexport const Bus = facade(BusDispatcher, { fake: (...args: Parameters<typeof BusFake.fake>) => BusFake.fake(...args) })\nexport const Event = facade(EventDispatcher, { fake: (...args: Parameters<typeof EventFake.fake>) => EventFake.fake(...args) })\nexport const Storage = facade(FilesystemManager, { fake: (...args: Parameters<typeof StorageFake.fake>) => StorageFake.fake(...args) })\n\n/** The notification base class with Laravel's Notification::fake(). */\nexport abstract class Notification extends BaseNotification {\n static fake(...args: Parameters<typeof NotificationFake.fake>): ReturnType<typeof NotificationFake.fake> {\n return NotificationFake.fake(...args)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AIAA,SAAS,uBAAuB;AEAhC,SAAS,kBAAkB;AGA3B,SAAS,cAAAA,mBAAkB;AMA3B,SAAS,kBAAkB;AMA3B,SAAS,eAAe;AACxB,SAAS,YAAY;AACrB,SAAS,qBAAqB;ArBCvB,IAAM,sBAAN,cAAkC,MAA6C;EAKpF,YACE,UAAU,oBACD,SAAmB,CAAC,GACpBC,aACT;AACA,UAAM,OAAO;AAHJ,SAAA,SAAA;AACA,SAAA,aAAAA;EAGX;EAJW;EACA;EAPF,OAAO;EACP,SAAS;EACA,OAAO;AAS3B;AAGO,IAAM,qBAAN,cAAiC,MAA4B;EACzD,OAAO;EACE,OAAO;EAChB;EACA;EAET,YAAY,SAAkB,SAAS,KAAK,MAAe;AACzD,UAAM,YAAY,UAAa,YAAY,KAAK,iCAAiC,OAAO;AACxF,SAAK,SAAS;AACd,SAAK,OAAO;EACd;AACF;AC1BO,IAAM,aAAN,MAAiB;EACtB,YAAqBC,QAAwB,aAAmC,UAAmB;AAA9E,SAAA,QAAAA;AAAwB,SAAA,cAAA;AAAmC,SAAA,WAAA;EAAoB;EAA/E;EAAwB;EAAmC;AAClF;AAGO,IAAM,YAAN,MAAgB;EACrB,YAAqBA,QAAwB,MAAuB;AAA/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AAqB;AAAA,IAAwB;AAAA,IAAqB;AAAA,EACpE;AACF;;;AC/BO,IAAMC,eAAN,MAAM,qBAAoBA,aAAsB;AAAA,EACrD,YAAY,UAAkB;AAC5B,UAAM,QAAQ;AAEd,SAAK,SAAS,cAAa,IAAI;AAAA,EACjC;AAAA,EAEA,OAAgB,UAAU,SAAmD;AAC3E,WAAO,IAAI,mBAAmB,IAAI,aAAY,QAAQ,QAAQ,CAAC,EAAE,cAAc,iBAAiB,CAAC;AAAA,EACnG;AACF;;;ACRO,IAAMC,QAAO,OAAO,aAAa,EAAE,MAAM,IAAI,SAA2C,SAAS,KAAK,GAAG,IAAI,EAAE,CAAC;AAChH,IAAMC,SAAQ,OAAO,cAAc,EAAE,MAAM,IAAI,SAA4C,UAAU,KAAK,GAAG,IAAI,EAAE,CAAC;AACpH,IAAMC,OAAM,OAAO,eAAe,EAAE,MAAM,IAAI,SAA0C,QAAQ,KAAK,GAAG,IAAI,EAAE,CAAC;AAC/G,IAAMC,SAAQ,OAAO,iBAAiB,EAAE,MAAM,IAAI,SAA4C,UAAU,KAAK,GAAG,IAAI,EAAE,CAAC;AACvH,IAAMC,WAAU,OAAO,mBAAmB,EAAE,MAAM,IAAI,SAA8C,YAAY,KAAK,GAAG,IAAI,EAAE,CAAC;AAG/H,IAAeC,gBAAf,cAAoC,aAAiB;AAAA,EAC1D,OAAO,QAAQ,MAA0F;AACvG,WAAO,iBAAiB,KAAK,GAAG,IAAI;AAAA,EACtC;AACF;","names":["createHash","redirectTo","guard","token","config","url","currentContainer","value","session","store","event","text","createHash","Str","now","row","HttpRequest","app","ConfigRepository","BindingResolutionError","method","ClassRegistry","inject","request","PasswordBroker","DatabaseManager","Hasher","auth","AuthFactory","redirect","UrlGenerator","Container","route","files","Gate","manager","GateToken","PasswordBrokerToken","value","cache","store","manager","errors","QueueManager","list","BatchRepository","currentContainer","BusDispatcher","delaySeconds","inject","createHash","join","sleep","createHash","sleep","store","value","raw","Repository","now","hash","createHash","join","token","FOREVER_SECONDS","Str","sleep","config","url","list","CacheManager","CacheManagerToken","manager","mkdir","writeFile","dirname","join","join","join","existsSync","join","pathToFileURL","createHash","text","resolve","io","app","inject","config","equals","value","token","ConsoleKernel","Application","join","dirname","mkdir","writeFile","Str","event","now","Schedule","sleep","files","existsSync","pathToFileURL","url","handler","SHOULD_QUEUE","QUEUE_OPTIONS","isQueueable","createHash","start","currentContainer","ConfigRepository","BusDispatcher","ScheduleToken","createHmac","timingSafeEqual","cookie","now","value","equals","response","createHmac","timingSafeEqual","CookieJar","request","inject","config","HttpRequest","sql","sql","sql","AsyncLocalStorage","existsSync","readdirSync","join","pathToFileURL","AsyncLocalStorage","existsSync","join","existsSync","readdirSync","join","pathToFileURL","relative","mkdir","writeFile","dirname","sep","existsSync","readdirSync","join","pathToFileURL","randomUUID","sql","castType","Database","config","url","value","raw","json","Collection","text","join","sets","list","level","Builder","Str","scopes","registry","now","Factory","existsSync","readdirSync","pathToFileURL","AsyncLocalStorage","event","currentContainer","handler","DatabaseManager","pad","manager","files","mkdir","dirname","writeFile","relative","sep","number","randomUUID","start","env","app","ClassRegistry","createHmac","timingSafeEqual","readFile","writeFile","equals","timingSafeEqual","Encrypter","value","serialize","createHmac","app","config","readFile","writeFile","list","EncrypterToken","ConfigRepository","existsSync","readdirSync","statSync","join","pathToFileURL","event","SHOULD_QUEUE","registry","readdirSync","join","statSync","value","existsSync","pathToFileURL","inject","Dispatcher","e","list","isString","wildcard","response","ClassRegistry","config","mkdir","readFile","readdir","rename","rm","stat","writeFile","dirname","extname","resolve","sep","mkdir","dirname","relative","sep","config","resolve","stat","readFile","writeFile","rm","rename","extname","readdir","value","response","objects","FilesystemManager","app","link","FilesystemManagerToken","bcrypt","value","bcrypt","config","Hasher","createReadStream","stat","basename","Readable","readFile","Readable","pipeline","existsSync","mkdir","readFile","writeFile","dirname","response","readBody","raw","value","currentRequest","serializeCookie","cookie","session","errors","url","request","EXTENSIONS","mimeFromExtension","inject","isPlainObject","text","files","Str","token","Session","guard","currentContainer","HttpRequest","UrlGenerator","html","basename","stat","Readable","createReadStream","Kernel","app","route","CurrentRoute","handler","renderError","config","aliases","ConfigRepository","Router","readFile","start","number","Redirector","redirect","view","ViewFactory","resolve","pipeline","existsSync","mkdir","dirname","writeFile","HttpKernel","ExceptionHandler","ResponseFactory","pino","createWriteStream","mkdirSync","readdirSync","basename","dirname","extname","join","level","value","now","dirname","basename","extname","mkdirSync","join","createWriteStream","readdirSync","pino","manager","config","LogManager","LogManagerToken","randomUUID","view","list","randomUUID","manager","logger","html","config","text","currentContainer","value","SHOULD_QUEUE","delaySeconds","QUEUE_OPTIONS","MailManager","MailManagerToken","randomUUID","randomUUID","text","url","html","escapeHtml","value","route","parseStoredDate","now","currentContainer","randomUUID","SHOULD_QUEUE","QUEUE_OPTIONS","copyShouldQueueFields","NotificationDispatcherToken","Dispatcher","list","fake","facade","registry","value","app","Buffer","randomUUID","randomUUID","Redis","randomUUID","sleep","existsSync","readdirSync","statSync","join","pathToFileURL","QUEUE_JOB","CHAIN","UNIQUE_LOCK","value","registry","isPlainObject","Buffer","name","optionalString","randomUUID","raw","cache","store","CacheManager","ClassRegistry","delaySeconds","FailedJobProvider","now","makeRedisClient","config","Redis","resolveRedisConfig","QueueManager","manager","handler","sleep","BusDispatcher","ExceptionHandler","EXTENSIONS","files","readdirSync","join","statSync","isClass","existsSync","pathToFileURL","text","list","number","pad","define","ConfigRepository","confirmToProceed","DatabaseManager","BatchRepository","pathToFileURL","value","request","aliases","handler","instances","route","PARAMETER","decode","raw","isClass","Str","currentContainer","view","list","CurrentRoute","isPlainObject","buildQuery","text","generation","app","url","pathToFileURL","html","Router","UrlGenerator","mkdir","readdir","readFile","rename","rm","stat","writeFile","join","Redis","timingSafeEqual","handler","value","list","old","url","session","join","stat","readFile","mkdir","Str","writeFile","rename","rm","files","readdir","request","guard","makeRedisClient","config","Redis","app","HttpRequest","serialize","cookie","response","ConfigRepository","equals","timingSafeEqual","inject","Container","Session","token","Encrypter","errors","Application","store","errors","redirectTo","request","value","inject","raw","Arr","relative","isPlainObject","registry","present","isBlank","ctx","ValidationFactoryToken","Application","Mail","Queue","Bus","Event","Storage","Notification"]}
|