@orieljs/framework 0.1.0-alpha.0 → 0.1.0-alpha.2

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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../Config/Repository.ts","../../Config/env.ts","../../Config/LoadEnvironment.ts","../../Config/LoadConfiguration.ts","../../Foundation/Application.ts","../../Foundation/ApplicationBuilder.ts","../../Foundation/errors.ts","../../Foundation/Vite.ts","../../Foundation/Http/ClosureKernel.ts","../../Testing/Console/PendingCommand.ts","../../Testing/assert.ts","../../Testing/Concerns/InteractsWithDatabase.ts","../../Testing/Database/assertions.ts","../../Testing/Database/traits.ts","../../Testing/Concerns/MakesHttpRequests.ts","../../Testing/Http/HttpClient.ts","../../Testing/environment.ts","../../Testing/TestResponse.ts","../../Testing/Fluent/AssertableInertia.ts","../../Testing/Fluent/AssertableJson.ts","../../Testing/Http/cookies.ts","../../Testing/Http/recorders.ts","../../Testing/Concerns/InteractsWithApplication.ts","../../Testing/Concerns/InteractsWithConsole.ts","../../Testing/TestCase.ts","../../Testing/Fakes/support.ts","../../Testing/Fakes/EventFake.ts","../../Testing/Fakes/BusFake.ts","../../Testing/Fakes/QueueFake.ts","../../Testing/Fakes/MailFake.ts","../../Testing/Fakes/NotificationFake.ts","../../Testing/Fakes/StorageFake.ts","../../Testing/FakeFile.ts"],"sourcesContent":["import 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/** Copies plain objects and arrays; class instances, functions and other values are kept by reference. */\nfunction clonePlain<T>(value: T): T {\n if (Array.isArray(value)) return value.map((item: unknown) => clonePlain(item)) as T\n if (typeof value === 'object' && value !== null) {\n const proto = Object.getPrototypeOf(value) as unknown\n if (proto !== Object.prototype && proto !== null) return value\n return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, clonePlain(item)])) as T\n }\n return value\n}\n\n/**\n * Imports config/*.{ts,js,mjs}; each file's default export becomes config[<file name>].\n * Config files are cached ES modules, so every call returns fresh copies (apps in one process never share config state).\n */\nexport async function loadConfiguration(configPath: string): Promise<Record<string, unknown>> {\n if (!existsSync(configPath)) return {}\n const files = readdirSync(configPath).filter((f) => CONFIG_FILE.test(f)).sort()\n const config: Record<string, unknown> = {}\n for (const file of files) {\n const name = CONFIG_FILE.exec(file)![1]!\n const mod = (await import(pathToFileURL(join(configPath, file)).href)) as { default?: unknown }\n config[name] = clonePlain(mod.default ?? {})\n }\n return config\n}\n","import { join } from 'node:path'\nimport {\n Application as ApplicationToken,\n ClassRegistry as ClassRegistryToken,\n ConfigRepository,\n HttpKernel,\n type Application as ApplicationContract,\n type ServiceProvider,\n type ServiceProviderClass,\n} from '@orieljs/contracts'\nimport { Container } from '@orieljs/container'\nimport { ClassRegistry, Str } from '@orieljs/support'\nimport { ApplicationBuilder } from './ApplicationBuilder'\nimport { ProviderBootError, ProviderRegisterError } from './errors'\nimport { Vite } from './Vite'\n\ntype LifecycleCallback = (app: ApplicationContract) => void | Promise<void>\n\nexport class Application extends Container implements ApplicationContract {\n readonly version = '0.1.0-alpha.1'\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 // One per request: a CSP nonce set with vite().useCspNonce() must not leak into other requests.\n this.scoped(Vite, () => new Vite(this))\n }\n\n /** Entry point used by bootstrap/app.ts. */\n static configure(options: { basePath: string }): ApplicationBuilder {\n return new ApplicationBuilder(new Application(options.basePath))\n }\n\n basePath(path = ''): string { return join(this.base, path) }\n appPath(path = ''): string { return this.basePath(join('app', path)) }\n bootstrapPath(path = ''): string { return this.basePath(join('bootstrap', path)) }\n configPath(path = ''): string { return this.basePath(join('config', path)) }\n databasePath(path = ''): string { return this.basePath(join('database', path)) }\n publicPath(path = ''): string { return this.basePath(join('public', path)) }\n resourcePath(path = ''): string { return this.basePath(join('resources', path)) }\n storagePath(path = ''): string { return this.basePath(join('storage', path)) }\n\n environment(): string\n environment(...environments: string[]): boolean\n environment(...environments: string[]): string | boolean {\n const fallback = process.env.APP_ENV ?? 'production'\n const current = this.bound(ConfigRepository)\n ? String(this.make(ConfigRepository).get('app.env', fallback))\n : fallback\n return environments.length === 0 ? current : environments.some((pattern) => Str.is(pattern, current))\n }\n\n isProduction(): boolean { return this.environment('production') }\n isLocal(): boolean { return this.environment('local') }\n runningUnitTests(): boolean { return this.environment('testing') }\n runningInConsole(): boolean { return this.inConsole }\n setRunningInConsole(value = true): void { this.inConsole = value }\n\n async register(provider: ServiceProvider | ServiceProviderClass): Promise<ServiceProvider> {\n const cls = typeof provider === 'function' ? provider : provider.constructor\n const existing = this.providers.find((p) => p.constructor === cls)\n if (existing) return existing\n\n const instance = typeof provider === 'function' ? new provider(this) : provider\n try {\n instance.register?.()\n } catch (error) {\n throw new ProviderRegisterError(instance.constructor.name, error)\n }\n this.providers.push(instance)\n if (this.hasBooted) await this.bootProvider(instance)\n return instance\n }\n\n getProviders(): ServiceProvider[] {\n return [...this.providers]\n }\n\n boot(): Promise<void> {\n return (this.bootPromise ??= this.runBoot())\n }\n\n isBooted(): boolean {\n return this.hasBooted\n }\n\n booting(callback: LifecycleCallback): void {\n this.bootingCallbacks.push(callback)\n }\n\n /** If already booted, the callback runs immediately (a rejection surfaces as an unhandled rejection). */\n booted(callback: LifecycleCallback): void {\n this.bootedCallbacks.push(callback)\n if (this.hasBooted) void callback(this)\n }\n\n terminating(callback: () => void | Promise<void>): void {\n this.terminatingCallbacks.push(callback)\n }\n\n async handle(request: Request): Promise<Response> {\n await this.boot()\n const scope = this.createScope()\n return scope.run(() => scope.make(HttpKernel).handle(request))\n }\n\n async terminate(): Promise<void> {\n for (const callback of this.terminatingCallbacks) await callback()\n }\n\n 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 { existsSync, readFileSync, statSync } from 'node:fs'\nimport { createHash, randomBytes } from 'node:crypto'\nimport { join } from 'node:path'\nimport { Application as ApplicationToken, ConfigRepository, HttpRequest, UrlGenerator, type Application, type Htmlable, type OrielError } from '@orieljs/contracts'\nimport { ContainerNotAvailableError, currentContainer } from '@orieljs/container'\n\n/** One entry of Vite's build manifest (vite's ManifestChunk). */\nexport interface ManifestChunk {\n file: string\n src?: string\n name?: string\n isEntry?: boolean\n isDynamicEntry?: boolean\n imports?: string[]\n dynamicImports?: string[]\n css?: string[]\n assets?: string[]\n [key: string]: unknown\n}\nexport type Manifest = Record<string, ManifestChunk>\n\nexport type TagAttributes = Record<string, string | boolean | null | undefined>\nexport type AttributesResolver = (src: string, url: string, chunk: ManifestChunk | undefined, manifest: Manifest | undefined) => TagAttributes\nexport type PreloadAttributesResolver = (src: string, url: string, chunk: ManifestChunk | undefined, manifest: Manifest | undefined) => TagAttributes | false\n\n/** A missing manifest or chunk (Laravel's ViteException / ViteManifestNotFoundException). */\nexport class ViteError extends Error implements OrielError {\n readonly kind = 'Server' as const\n readonly status = 500\n\n constructor(message: string) {\n super(message)\n this.name = 'ViteError'\n }\n}\n\n/** Markup the view renderer emits unescaped (Htmlable; Foundation can't import View's HtmlString). */\nexport class ViteHtml implements Htmlable {\n constructor(private readonly html: string) {}\n\n toHtml(): string {\n return this.html\n }\n\n toString(): string {\n return this.html\n }\n}\n\nconst CSS_PATH = /\\.(css|less|sass|scss|styl|stylus|pcss|postcss)(\\?[^.]*)?$/\n\n/** Parsed manifests by path, reloaded when the file changes (a long-running server outlives a `vite build`). */\nconst manifests = new Map<string, { mtimeMs: number; manifest: Manifest }>()\n\nconst escapeAttribute = (value: string): string => value.replace(/&/g, '&amp;').replace(/\"/g, '&quot;')\n\n/**\n * Laravel's Illuminate\\Foundation\\Vite: the script, style and preload tags for Vite entry points. While the dev\n * server runs (public/hot holds its URL) it points at the dev server; otherwise it reads public/build/manifest.json.\n */\nexport class Vite {\n #hotFile: string | undefined\n #buildDirectory = 'build'\n #manifestFilename = 'manifest.json'\n #nonce: string | undefined\n #integrityKey: string | false = 'integrity'\n #entryPoints: string[] = []\n readonly #scriptResolvers: AttributesResolver[] = []\n readonly #styleResolvers: AttributesResolver[] = []\n readonly #preloadResolvers: PreloadAttributesResolver[] = []\n #assetPathResolver: ((path: string) => string) | undefined\n readonly #preloaded: Record<string, string[]> = {}\n\n constructor(protected readonly app: Application) {}\n\n // Configuration --------------------------------------------------------------------------------------------\n\n useCspNonce(nonce?: string): string {\n this.#nonce = nonce ?? randomBytes(30).toString('base64url').slice(0, 40)\n return this.#nonce\n }\n\n cspNonce(): string | undefined {\n return this.#nonce\n }\n\n useIntegrityKey(key: string | false): this {\n this.#integrityKey = key\n return this\n }\n\n withEntryPoints(entryPoints: string[]): this {\n this.#entryPoints = entryPoints\n return this\n }\n\n useHotFile(path: string): this {\n this.#hotFile = path\n return this\n }\n\n useBuildDirectory(path: string): this {\n this.#buildDirectory = path\n return this\n }\n\n useManifestFilename(filename: string): this {\n this.#manifestFilename = filename\n return this\n }\n\n useScriptTagAttributes(attributes: TagAttributes | AttributesResolver): this {\n this.#scriptResolvers.push(typeof attributes === 'function' ? attributes : () => attributes)\n return this\n }\n\n useStyleTagAttributes(attributes: TagAttributes | AttributesResolver): this {\n this.#styleResolvers.push(typeof attributes === 'function' ? attributes : () => attributes)\n return this\n }\n\n /** Extra preload attributes; a resolver returning false drops that preload. */\n usePreloadTagAttributes(attributes: TagAttributes | PreloadAttributesResolver | false): this {\n this.#preloadResolvers.push(typeof attributes === 'function' ? attributes : () => attributes)\n return this\n }\n\n createAssetPathsUsing(resolver: (path: string) => string): this {\n this.#assetPathResolver = resolver\n return this\n }\n\n // Dev server -----------------------------------------------------------------------------------------------\n\n hotFile(): string {\n return this.#hotFile ?? this.app.publicPath('hot')\n }\n\n isRunningHot(): boolean {\n return existsSync(this.hotFile())\n }\n\n /** The dev server URL written by @orieljs/vite, or undefined when it isn't running. */\n devServerUrl(): string | undefined {\n return this.isRunningHot() ? readFileSync(this.hotFile(), 'utf8').trimEnd() : undefined\n }\n\n // Tags -----------------------------------------------------------------------------------------------------\n\n /** Laravel's @vite([...]): preloads (styles first), then stylesheets, then scripts. */\n tags(entryPoints: string | string[], buildDirectory = this.#buildDirectory): ViteHtml {\n const entries = [entryPoints].flat()\n if (this.isRunningHot()) {\n return new ViteHtml(['@vite/client', ...entries].map((entry) => this.#tagForChunk(entry, this.#hotAsset(entry), undefined, undefined)).join(''))\n }\n const manifest = this.manifest(buildDirectory)\n const tags: string[] = []\n const preloads: Array<[string, string, ManifestChunk | undefined]> = []\n const cssChunk = (css: string): [string, ManifestChunk | undefined] => {\n const found = Object.entries(manifest).find(([, chunk]) => chunk.file === css)\n return found === undefined ? [css, undefined] : [found[0], found[1]]\n }\n for (const entry of entries) {\n const chunk = this.#chunk(manifest, entry)\n preloads.push([chunk.src ?? entry, this.#assetPath(`${buildDirectory}/${chunk.file}`), chunk])\n for (const name of this.#resolveImports(manifest, chunk)) {\n const imported = manifest[name]!\n preloads.push([name, this.#assetPath(`${buildDirectory}/${imported.file}`), imported])\n for (const css of imported.css ?? []) {\n const [key, partial] = cssChunk(css)\n preloads.push([key, this.#assetPath(`${buildDirectory}/${css}`), partial])\n tags.push(this.#tagForChunk(key, this.#assetPath(`${buildDirectory}/${css}`), partial, manifest))\n }\n }\n tags.push(this.#tagForChunk(entry, this.#assetPath(`${buildDirectory}/${chunk.file}`), chunk, manifest))\n for (const css of chunk.css ?? []) {\n const [key, partial] = cssChunk(css)\n preloads.push([key, this.#assetPath(`${buildDirectory}/${css}`), partial])\n tags.push(this.#tagForChunk(key, this.#assetPath(`${buildDirectory}/${css}`), partial, manifest))\n }\n }\n const uniqueTags = [...new Set(tags)]\n const stylesheets = uniqueTags.filter((tag) => tag.startsWith('<link'))\n const scripts = uniqueTags.filter((tag) => !tag.startsWith('<link'))\n const seen = new Set<string>()\n const uniquePreloads = preloads.filter(([, url]) => (seen.has(url) ? false : (seen.add(url), true)))\n const sorted = [...uniquePreloads.filter(([, url]) => CSS_PATH.test(url)), ...uniquePreloads.filter(([, url]) => !CSS_PATH.test(url))]\n const preloadTags = sorted.map(([src, url, chunk]) => this.#preloadTag(src, url, chunk, manifest))\n return new ViteHtml(preloadTags.join('') + stylesheets.join('') + scripts.join(''))\n }\n\n /** Laravel's @viteReactRefresh: the React Refresh preamble while the dev server runs; nothing otherwise. */\n reactRefresh(): ViteHtml | undefined {\n if (!this.isRunningHot()) return undefined\n const attributes = this.#parseAttributes({ nonce: this.#nonce ?? false })\n return new ViteHtml(\n [\n `<script type=\"module\" ${attributes.join(' ')}>`,\n ` import RefreshRuntime from '${this.#hotAsset('@react-refresh')}'`,\n ' RefreshRuntime.injectIntoGlobalHook(window)',\n ' window.$RefreshReg$ = () => {}',\n ' window.$RefreshSig$ = () => (type) => type',\n ' window.__vite_plugin_react_preamble_installed__ = true',\n '</script>',\n ].join('\\n'),\n )\n }\n\n /** The URL of a processed asset (Vite::asset('resources/images/logo.svg')). */\n asset(path: string, buildDirectory = this.#buildDirectory): string {\n if (this.isRunningHot()) return this.#hotAsset(path)\n return this.#assetPath(`${buildDirectory}/${this.#chunk(this.manifest(buildDirectory), path).file}`)\n }\n\n /** The built file's contents (Vite::content()). */\n content(path: string, buildDirectory = this.#buildDirectory): string {\n const chunk = this.#chunk(this.manifest(buildDirectory), path)\n const file = this.app.publicPath(join(buildDirectory, chunk.file))\n if (!existsSync(file)) throw new ViteError(`Unable to locate file from Vite manifest: ${file}.`)\n return readFileSync(file, 'utf8')\n }\n\n /** md5 of the manifest (a cache-busting asset version); undefined while hot or without a build. */\n manifestHash(buildDirectory = this.#buildDirectory): string | undefined {\n if (this.isRunningHot()) return undefined\n const path = this.manifestPath(buildDirectory)\n return existsSync(path) ? createHash('md5').update(readFileSync(path)).digest('hex') : undefined\n }\n\n manifestPath(buildDirectory = this.#buildDirectory): string {\n return this.app.publicPath(join(buildDirectory, this.#manifestFilename))\n }\n\n manifest(buildDirectory = this.#buildDirectory): Manifest {\n const path = this.manifestPath(buildDirectory)\n if (!existsSync(path)) throw new ViteError(`Vite manifest not found at: ${path}`)\n const { mtimeMs } = statSync(path)\n const cached = manifests.get(path)\n if (cached !== undefined && cached.mtimeMs === mtimeMs) return cached.manifest\n const manifest = JSON.parse(readFileSync(path, 'utf8')) as Manifest\n manifests.set(path, { mtimeMs, manifest })\n return manifest\n }\n\n /** URL → the attributes of the preload tags rendered so far (without href), for Link headers. */\n preloadedAssets(): Record<string, string[]> {\n return { ...this.#preloaded }\n }\n\n /** Renders withEntryPoints() (Vite is Htmlable, like Laravel's). */\n toHtml(): string {\n return this.tags(this.#entryPoints).toHtml()\n }\n\n // Internals ------------------------------------------------------------------------------------------------\n\n #hotAsset(path: string): string {\n return `${this.devServerUrl() ?? ''}/${path}`\n }\n\n #assetPath(path: string): string {\n if (this.#assetPathResolver !== undefined) return this.#assetPathResolver(path)\n if (this.app.bound(UrlGenerator)) return this.app.make(UrlGenerator).asset(path)\n const base = this.app.bound(ConfigRepository) ? this.app.make(ConfigRepository).get<string | null>('app.asset_url', null) : null\n return `${(base ?? '').replace(/\\/+$/, '')}/${path.replace(/^\\/+/, '')}`\n }\n\n #chunk(manifest: Manifest, file: string): ManifestChunk {\n const chunk = manifest[file]\n if (chunk === undefined) throw new ViteError(`Unable to locate file in Vite manifest: ${file}.`)\n return chunk\n }\n\n /** Every static import, depth first, each once. */\n #resolveImports(manifest: Manifest, chunk: ManifestChunk, seen = new Set<string>()): string[] {\n const imports: string[] = []\n for (const name of chunk.imports ?? []) {\n if (seen.has(name)) continue\n seen.add(name)\n imports.push(name)\n const imported = manifest[name]\n if (imported !== undefined) imports.push(...this.#resolveImports(manifest, imported, seen))\n }\n return imports\n }\n\n #tagForChunk(src: string, url: string, chunk: ManifestChunk | undefined, manifest: Manifest | undefined): string {\n if (CSS_PATH.test(url)) {\n const attributes = this.#parseAttributes({ rel: 'stylesheet', href: url, nonce: this.#nonce ?? false, ...this.#styleAttributes(src, url, chunk, manifest) })\n return `<link ${attributes.join(' ')} />`\n }\n const attributes = this.#parseAttributes({ type: 'module', src: url, nonce: this.#nonce ?? false, ...this.#scriptAttributes(src, url, chunk, manifest) })\n return `<script ${attributes.join(' ')}></script>`\n }\n\n #preloadTag(src: string, url: string, chunk: ManifestChunk | undefined, manifest: Manifest): string {\n const css = CSS_PATH.test(url)\n let attributes: TagAttributes = {\n rel: css ? 'preload' : 'modulepreload',\n as: css ? 'style' : 'script',\n href: url,\n nonce: this.#nonce ?? false,\n crossorigin: (css ? this.#styleAttributes(src, url, chunk, manifest) : this.#scriptAttributes(src, url, chunk, manifest)).crossorigin ?? false,\n }\n if (this.#integrityKey !== false) attributes.integrity = (chunk?.[this.#integrityKey] as string | undefined) ?? false\n for (const resolver of this.#preloadResolvers) {\n const resolved = resolver(src, url, chunk, manifest)\n if (resolved === false) return ''\n attributes = { ...attributes, ...resolved }\n }\n const { href: _href, ...rest } = attributes\n this.#preloaded[url] = this.#parseAttributes(rest)\n return `<link ${this.#parseAttributes(attributes).join(' ')} />`\n }\n\n #scriptAttributes(src: string, url: string, chunk: ManifestChunk | undefined, manifest: Manifest | undefined): TagAttributes {\n let attributes: TagAttributes = this.#integrityKey !== false ? { integrity: (chunk?.[this.#integrityKey] as string | undefined) ?? false } : {}\n for (const resolver of this.#scriptResolvers) attributes = { ...attributes, ...resolver(src, url, chunk, manifest) }\n return attributes\n }\n\n #styleAttributes(src: string, url: string, chunk: ManifestChunk | undefined, manifest: Manifest | undefined): TagAttributes {\n let attributes: TagAttributes = this.#integrityKey !== false ? { integrity: (chunk?.[this.#integrityKey] as string | undefined) ?? false } : {}\n for (const resolver of this.#styleResolvers) attributes = { ...attributes, ...resolver(src, url, chunk, manifest) }\n return attributes\n }\n\n /** false/null/undefined are dropped, true is a bare attribute, anything else name=\"value\". */\n #parseAttributes(attributes: TagAttributes): string[] {\n return Object.entries(attributes)\n .filter(([, value]) => value !== false && value !== null && value !== undefined)\n .map(([name, value]) => (value === true ? name : `${name}=\"${escapeAttribute(String(value))}\"`))\n }\n}\n\n/**\n * The Vite instance for the current context: the request's own (scoped, so a CSP nonce stays in its request),\n * else a fresh one for the application (a mail view rendered by a queue worker).\n */\nexport function currentVite(): Vite {\n const container = currentContainer()\n if (container === undefined) throw new ContainerNotAvailableError('Vite')\n if (container.bound(HttpRequest)) return container.make(Vite)\n return new Vite(container.make(ApplicationToken))\n}\n\n/** vite(['resources/js/app.tsx']) → the tags (Laravel's @vite); vite() → the Vite instance. */\nexport function vite(): Vite\nexport function vite(entryPoints: string | string[], buildDirectory?: string): ViteHtml\nexport function vite(entryPoints?: string | string[], buildDirectory?: string): Vite | ViteHtml {\n const instance = currentVite()\n return entryPoints === undefined ? instance : instance.tags(entryPoints, buildDirectory)\n}\n\n/** Laravel's @viteReactRefresh: put it before vite([...]) in the root view of a React app. */\nexport function viteReactRefresh(): ViteHtml | undefined {\n return currentVite().reactRefresh()\n}\n","import type { HttpKernel } from '@orieljs/contracts'\n\ntype Handler = (request: Request) => unknown\n\n/** Wave 0 stand-in for the Http kernel: exact \"METHOD /path\" matching only. Replaced by Wave 1's router. */\nexport class ClosureKernel implements HttpKernel {\n private readonly routes = new Map<string, Handler>()\n\n on(method: string, path: string, handler: Handler): this {\n this.routes.set(`${method.toUpperCase()} ${path}`, handler)\n return this\n }\n\n async handle(request: Request): Promise<Response> {\n const handler = this.routes.get(`${request.method} ${new URL(request.url).pathname}`)\n if (!handler) return new Response('Not Found', { status: 404, headers: { 'content-type': 'text/plain; charset=utf-8' } })\n return toResponse(await handler(request))\n }\n}\n\nfunction toResponse(output: unknown): Response {\n if (output instanceof Response) return output\n if (output === undefined || output === null) return new Response(null, { status: 204 })\n if (typeof output === 'string') return new Response(output, { headers: { 'content-type': 'text/html; charset=utf-8' } })\n return Response.json(output)\n}\n","import { ConsoleKernel, type Application } from '@orieljs/contracts'\nimport { assert } from '../assert'\n\ntype Check = (output: string, lines: string[], exitCode: number) => void\n\n/**\n * Laravel's PendingCommand: `await t.artisan('inspire').expectsOutput('…').assertExitCode(0)`.\n * It runs through ConsoleKernel.call() when awaited (or run()), then checks every expectation against the\n * buffered output (stdout then stderr, as ConsoleKernel.output() returns it) and the exit code.\n *\n * The result must be awaited (or run() called): unlike Laravel, where the command runs when the\n * PendingCommand is destroyed, nothing runs here until then, so an un-awaited `t.artisan(...)` never runs\n * and checks nothing.\n */\nexport class PendingCommand implements PromiseLike<number> {\n private readonly checks: Check[] = []\n private result: Promise<number> | undefined\n\n constructor(\n private readonly app: Application,\n readonly command: string,\n readonly parameters: Record<string, unknown> = {},\n ) {}\n\n /** A line of output equals `line` exactly; with no argument, the command printed something. */\n expectsOutput(line?: string): this {\n this.checks.push((output, lines) => {\n if (line === undefined) assert(output !== '', 'The command was expected to print output, but printed nothing.')\n else assert(lines.includes(line), `Output \"${line}\" was not printed.\\n\\nOutput:\\n${output}`, { actual: output, expected: line })\n })\n return this\n }\n\n /** No line equals `line`; with no argument, the command printed nothing at all. */\n doesntExpectOutput(line?: string): this {\n this.checks.push((output, lines) => {\n if (line === undefined) assert(output === '', `The command printed output unexpectedly:\\n${output}`, { actual: output, expected: '' })\n else assert(!lines.includes(line), `Output \"${line}\" was printed.`)\n })\n return this\n }\n\n expectsOutputToContain(text: string): this {\n this.checks.push((output) => assert(output.includes(text), `Output does not contain \"${text}\".\\n\\nOutput:\\n${output}`, { actual: output, expected: text }))\n return this\n }\n\n doesntExpectOutputToContain(text: string): this {\n this.checks.push((output) => assert(!output.includes(text), `Output \"${text}\" was printed.`))\n return this\n }\n\n assertExitCode(code: number): this {\n this.checks.push((_output, _lines, exitCode) =>\n assert(exitCode === code, `Expected status code ${code} but received ${exitCode}.`, { actual: exitCode, expected: code }),\n )\n return this\n }\n\n assertNotExitCode(code: number): this {\n this.checks.push((_output, _lines, exitCode) => assert(exitCode !== code, `Unexpected status code ${code} was received.`))\n return this\n }\n\n assertSuccessful(): this {\n return this.assertExitCode(0)\n }\n\n assertOk(): this {\n return this.assertSuccessful()\n }\n\n assertFailed(): this {\n return this.assertNotExitCode(0)\n }\n\n /** Runs the command once and checks the expectations; resolves to the exit code. */\n run(): Promise<number> {\n return (this.result ??= this.execute())\n }\n\n then<R1 = number, R2 = never>(\n onfulfilled?: ((value: number) => R1 | PromiseLike<R1>) | null,\n onrejected?: ((reason: unknown) => R2 | PromiseLike<R2>) | null,\n ): Promise<R1 | R2> {\n return this.run().then(onfulfilled, onrejected)\n }\n\n private async execute(): Promise<number> {\n if (!this.app.bound(ConsoleKernel)) throw new Error(`Cannot run [${this.command}]: the Console component (ConsoleKernel) is not registered.`)\n const kernel = this.app.make(ConsoleKernel)\n const exitCode = await kernel.call(this.command, this.parameters)\n const output = kernel.output()\n const lines = output.split('\\n').map((line) => line.replace(/\\r$/, ''))\n for (const check of this.checks) check(output, lines, exitCode)\n return exitCode\n }\n}\n","import { AssertionError } from 'node:assert'\nimport { isDeepStrictEqual } from 'node:util'\n\n/** Fails the current test. `actual`/`expected` make Vitest print a diff. */\nexport function fail(message: string, details: { actual?: unknown; expected?: unknown } = {}): never {\n const error = new AssertionError({ message, actual: details.actual, expected: details.expected, operator: 'fail' })\n // Node's `diff: 'simple'` would be printed by Vitest as the diff itself; Vitest computes its own from actual/expected.\n delete (error as { diff?: unknown }).diff\n Error.captureStackTrace?.(error, fail)\n throw error\n}\n\nexport function assert(condition: unknown, message: string | (() => string), details?: { actual?: unknown; expected?: unknown }): asserts condition {\n if (!condition) fail(typeof message === 'function' ? message() : message, details)\n}\n\n/** Readable form of any value for failure messages. */\nexport function format(value: unknown): string {\n if (typeof value === 'string') return JSON.stringify(value)\n if (typeof value === 'function') return value.name === '' ? '[Function]' : `[Function ${value.name}]`\n try {\n return JSON.stringify(value, (_key, item: unknown) => (typeof item === 'bigint' ? `${item}n` : item)) ?? String(value)\n } catch {\n return String(value)\n }\n}\n\n/** Laravel's e() (Testing can't import @orieljs/view). */\nexport function escapeHtml(value: string): string {\n return value.replace(/[&<>\"']/g, (char) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '\"': '&quot;', \"'\": '&#039;' })[char]!)\n}\n\nexport function stripTags(html: string): string {\n return html.replace(/<[^>]*>/g, '')\n}\n\n/** Deep equality ignoring object key order (Laravel canonicalizes both sides before comparing). */\nexport function equals(a: unknown, b: unknown): boolean {\n return isDeepStrictEqual(canonical(a), canonical(b))\n}\n\nfunction canonical(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(canonical)\n if (typeof value === 'object' && value !== null && Object.getPrototypeOf(value) === Object.prototype) {\n return Object.fromEntries(Object.keys(value).sort().map((key) => [key, canonical((value as Record<string, unknown>)[key])]))\n }\n return value\n}\n\n/** Laravel's assertArraySubset: every key of `subset` exists in `actual` with a matching value (recursively). */\nexport function isSubset(subset: unknown, actual: unknown): boolean {\n if (typeof subset !== 'object' || subset === null) return equals(subset, actual)\n if (typeof actual !== 'object' || actual === null) return false\n if (Array.isArray(subset) !== Array.isArray(actual)) return false\n return Object.entries(subset).every(([key, value]) => Object.hasOwn(actual, key) && isSubset(value, (actual as Record<string, unknown>)[key]))\n}\n\n/** Every object anywhere in the tree. */\nexport function* objectsIn(value: unknown): Generator<Record<string, unknown>> {\n if (typeof value !== 'object' || value === null) return\n if (!Array.isArray(value)) yield value as Record<string, unknown>\n for (const child of Object.values(value)) yield* objectsIn(child)\n}\n\n/** Some object in the tree has `key` with a value equal to `expected` (a JSON fragment pair). */\nexport function containsPair(tree: unknown, key: string, expected: unknown): boolean {\n for (const object of objectsIn(tree)) if (Object.hasOwn(object, key) && isSubset(expected, object[key])) return true\n return false\n}\n\n/** Laravel's JSON structure: `['id', { author: ['name'] }]`, and `'*'` for \"every element\". */\nexport type JsonStructure = Array<string | { [key: string]: JsonStructure }> | { [key: string]: JsonStructure }\n\nexport function assertStructure(structure: JsonStructure, data: unknown, path = ''): void {\n const at = (key: string) => (path === '' ? key : `${path}.${key}`)\n const hasKey = (key: string) => typeof data === 'object' && data !== null && Object.hasOwn(data, key)\n if (Array.isArray(structure)) {\n for (const item of structure) {\n if (typeof item === 'string') assert(hasKey(item), `Failed asserting that the JSON has the key [${at(item)}].`, { actual: data })\n else assertStructure(item, data, path)\n }\n return\n }\n for (const [key, nested] of Object.entries(structure)) {\n if (key === '*') {\n assert(Array.isArray(data) || (typeof data === 'object' && data !== null), `Failed asserting that [${path || 'the JSON'}] is a list.`, { actual: data })\n for (const [index, element] of Object.entries(data as object)) assertStructure(nested, element, at(index))\n continue\n }\n assert(hasKey(key), `Failed asserting that the JSON has the key [${at(key)}].`, { actual: data })\n assertStructure(nested, (data as Record<string, unknown>)[key], at(key))\n }\n}\n","import { DatabaseManager, type ModelInstance, type Row } from '@orieljs/contracts'\nimport * as db from '../Database/assertions'\nimport type { TableOrModel } from '../Database/assertions'\nimport { runCommand } from '../Database/traits'\nimport { MakesHttpRequests } from './MakesHttpRequests'\n\n/** Laravel's InteractsWithDatabase: database assertions and seeding, plus the options RefreshDatabase reads. */\nexport abstract class InteractsWithDatabase extends MakesHttpRequests {\n /** Seed after RefreshDatabase/DatabaseMigrations migrate (Laravel's $seed). */\n seed = false\n /** Seed with this seeder class instead of DatabaseSeeder (Laravel's $seeder). */\n seeder: string | undefined = undefined\n /** Connections RefreshDatabase/DatabaseTransactions wrap in a transaction (undefined = the default connection). */\n connectionsToTransact: Array<string | undefined> = [undefined]\n\n protected get database(): DatabaseManager {\n return this.app.make(DatabaseManager)\n }\n\n async assertDatabaseHas(table: TableOrModel, data: Row, connection?: string): Promise<this> {\n await db.assertDatabaseHas(this.database, table, data, connection)\n return this\n }\n\n async assertDatabaseMissing(table: TableOrModel, data: Row, connection?: string): Promise<this> {\n await db.assertDatabaseMissing(this.database, table, data, connection)\n return this\n }\n\n async assertDatabaseCount(table: TableOrModel, count: number, connection?: string): Promise<this> {\n await db.assertDatabaseCount(this.database, table, count, connection)\n return this\n }\n\n async assertDatabaseEmpty(table: TableOrModel, connection?: string): Promise<this> {\n return this.assertDatabaseCount(table, 0, connection)\n }\n\n async assertModelExists(model: ModelInstance): Promise<this> {\n return this.assertDatabaseHas(model, { [model.getKeyName()]: model.getKey() })\n }\n\n async assertModelMissing(model: ModelInstance): Promise<this> {\n return this.assertDatabaseMissing(model, { [model.getKeyName()]: model.getKey() })\n }\n\n async assertSoftDeleted(table: TableOrModel, data: Row = {}, connection?: string, deletedAtColumn = 'deleted_at'): Promise<this> {\n await db.assertSoftDeleted(this.database, table, data, connection, deletedAtColumn)\n return this\n }\n\n async assertNotSoftDeleted(table: TableOrModel, data: Row = {}, connection?: string, deletedAtColumn = 'deleted_at'): Promise<this> {\n await db.assertNotSoftDeleted(this.database, table, data, connection, deletedAtColumn)\n return this\n }\n\n /** Runs `db:seed` (with a seeder class name, like Laravel's $this->seed(UserSeeder::class)). */\n async runSeeder(seeder?: string): Promise<this> {\n await runCommand(this.app, 'db:seed', seeder === undefined ? {} : { '--class': seeder })\n return this\n }\n}\n","import type { DatabaseConnection, DatabaseManager, ModelInstance, QueryBuilder, Row } from '@orieljs/contracts'\nimport { assert, fail } from '../assert'\n\n/** A table name, or a model (its table, and its connection when it has one). */\nexport type TableOrModel = string | ModelInstance\n\ntype SoftDeletable = ModelInstance & { getDeletedAtColumn?(): string; getConnectionName?(): string | undefined }\n\nconst SHOW = 3\n\nfunction target(db: DatabaseManager, table: TableOrModel, connection?: string): { table: string; connection: DatabaseConnection } {\n if (typeof table === 'string') return { table, connection: db.connection(connection) }\n return { table: table.getTable(), connection: db.connection(connection ?? (table as SoftDeletable).getConnectionName?.()) }\n}\n\n/** where() per attribute; null matches IS NULL (Laravel's where($column, null)). */\nfunction constrain(query: QueryBuilder, data: Row): QueryBuilder {\n for (const [column, value] of Object.entries(data)) {\n if (value === null) query.whereNull(column)\n else query.where(column, value)\n }\n return query\n}\n\nasync function similar(connection: DatabaseConnection, table: string, data: Row): Promise<string> {\n const query = connection.table(table)\n const columns = Object.keys(data)\n if (columns.length > 0) query.select(...columns)\n const rows = (await query.limit(SHOW).get()).all()\n if (rows.length === 0) return 'The table is empty.'\n return `Found similar results: ${JSON.stringify(rows, null, 2)}`\n}\n\nexport async function assertDatabaseHas(db: DatabaseManager, table: TableOrModel, data: Row, connection?: string): Promise<void> {\n const t = target(db, table, connection)\n if ((await constrain(t.connection.table(t.table), data).count()) > 0) return\n fail(`Failed asserting that a row in the table [${t.table}] matches the attributes ${JSON.stringify(data, null, 2)}.\\n\\n${await similar(t.connection, t.table, data)}`)\n}\n\nexport async function assertDatabaseMissing(db: DatabaseManager, table: TableOrModel, data: Row, connection?: string): Promise<void> {\n const t = target(db, table, connection)\n const count = await constrain(t.connection.table(t.table), data).count()\n assert(count === 0, `Failed asserting that a row in the table [${t.table}] does not match the attributes ${JSON.stringify(data, null, 2)}.`)\n}\n\nexport async function assertDatabaseCount(db: DatabaseManager, table: TableOrModel, expected: number, connection?: string): Promise<void> {\n const t = target(db, table, connection)\n const actual = await t.connection.table(t.table).count()\n assert(actual === expected, `Failed asserting that table [${t.table}] matches expected entries count of ${expected}. Entries found: ${actual}.`, { actual, expected })\n}\n\nfunction softDeleteTarget(db: DatabaseManager, table: TableOrModel, data: Row, connection: string | undefined, deletedAtColumn: string) {\n if (typeof table === 'string') return { ...target(db, table, connection), data, column: deletedAtColumn }\n const model = table as SoftDeletable\n return { ...target(db, model, connection), data: { [model.getKeyName()]: model.getKey() }, column: model.getDeletedAtColumn?.() ?? deletedAtColumn }\n}\n\nexport async function assertSoftDeleted(db: DatabaseManager, table: TableOrModel, data: Row = {}, connection?: string, deletedAtColumn = 'deleted_at'): Promise<void> {\n const t = softDeleteTarget(db, table, data, connection, deletedAtColumn)\n const count = await constrain(t.connection.table(t.table), t.data).whereNotNull(t.column).count()\n assert(count > 0, `Failed asserting that any soft deleted row in the table [${t.table}] matches the attributes ${JSON.stringify(t.data, null, 2)}.`)\n}\n\nexport async function assertNotSoftDeleted(db: DatabaseManager, table: TableOrModel, data: Row = {}, connection?: string, deletedAtColumn = 'deleted_at'): Promise<void> {\n const t = softDeleteTarget(db, table, data, connection, deletedAtColumn)\n const count = await constrain(t.connection.table(t.table), t.data).whereNull(t.column).count()\n assert(count > 0, `Failed asserting that any existing row in the table [${t.table}] matches the attributes ${JSON.stringify(t.data, null, 2)}.`)\n}\n","import { ConfigRepository, ConsoleKernel, DatabaseManager, type Application, type DatabaseConnection } from '@orieljs/contracts'\nimport type { InteractsWithApplication, TestTrait } from '../Concerns/InteractsWithApplication'\n\n/** Options a test case may declare (InteractsWithDatabase declares them): Laravel's $seed, $seeder, $connectionsToTransact. */\nexport interface DatabaseTestOptions {\n seed?: boolean\n seeder?: string\n connectionsToTransact?: Array<string | undefined>\n /**\n * Replaces the once-per-process `migrate:fresh` that RefreshDatabase runs on a file or server database, for a test\n * case that must not wipe the whole database. It must leave the schema migrated, and seeded when seed/seeder ask\n * for it. (Laravel's migrateFreshUsing() returns options for migrate:fresh; here it replaces the command.)\n */\n migrateFreshUsing?(): void | Promise<void>\n}\n\ntype DatabaseTest = InteractsWithApplication & DatabaseTestOptions\n\n/** Laravel's RefreshDatabaseState: the schema is migrated once per process (per worker). */\nexport const RefreshDatabaseState = { migrated: false }\n\n/** Runs a console command through the ConsoleKernel contract; a non-zero exit fails the test with its output. */\nexport async function runCommand(app: Application, command: string, parameters: Record<string, unknown> = {}): Promise<void> {\n if (!app.bound(ConsoleKernel)) throw new Error(`Running [${command}] needs the Console component (ConsoleKernel is not bound).`)\n const kernel = app.make(ConsoleKernel)\n const code = await kernel.call(command, parameters)\n if (code !== 0) throw new Error(`[${command}] failed with exit code ${code}:\\n${kernel.output()}`)\n}\n\n/** Laravel's migrateUsing()/migrateFreshUsing(): a --seeder class alone seeds; otherwise --seed when $seed is set. */\nfunction seedOptions(test: DatabaseTest): Record<string, unknown> {\n if (test.seeder !== undefined) return { '--seeder': test.seeder }\n return test.seed === true ? { '--seed': true } : {}\n}\n\n/** Laravel's usingInMemoryDatabase(): the default connection's database is ':memory:'. */\nexport function usingInMemoryDatabase(app: Application): boolean {\n const config = app.make(ConfigRepository)\n const name = config.get<string | undefined>('database.default')\n return name !== undefined && config.get(`database.connections.${name}.database`) === ':memory:'\n}\n\nfunction connectionsOf(test: DatabaseTest): DatabaseConnection[] {\n const db = test.app.make(DatabaseManager)\n return (test.connectionsToTransact ?? [undefined]).map((name) => db.connection(name))\n}\n\n/**\n * Laravel's beginDatabaseTransaction(): a transaction on each connection, held open for the whole test. Teardown\n * rolls each connection back to the level it had before, so a transaction the test left open is undone too.\n */\nasync function beginTransactions(test: DatabaseTest, connections: DatabaseConnection[]): Promise<void> {\n const levels = connections.map((connection) => connection.transactionLevel())\n for (const connection of connections) await connection.beginTransaction()\n test.beforeApplicationDestroyed(async () => {\n for (const [index, connection] of [...connections.entries()].reverse()) await rollBackTo(connection, levels[index] ?? 0)\n })\n}\n\nasync function rollBackTo(connection: DatabaseConnection, level: number): Promise<void> {\n let current = connection.transactionLevel()\n while (current > level) {\n await connection.rollBack()\n const next = connection.transactionLevel()\n if (next >= current) return // the connection didn't unwind (it was closed); don't spin\n current = next\n }\n}\n\n/**\n * Laravel's RefreshDatabase.\n * - In-memory SQLite: every test's new application has an empty database, so it just runs `migrate`.\n * - Otherwise: `migrate:fresh` once per process (or the test's own migrateFreshUsing()), then each test runs inside a\n * transaction that is rolled back.\n */\nexport const RefreshDatabase: TestTrait = {\n async setUp(test: DatabaseTest) {\n if (usingInMemoryDatabase(test.app)) return runCommand(test.app, 'migrate', seedOptions(test))\n if (!RefreshDatabaseState.migrated) {\n if (test.migrateFreshUsing !== undefined) await test.migrateFreshUsing()\n else await runCommand(test.app, 'migrate:fresh', seedOptions(test))\n RefreshDatabaseState.migrated = true\n }\n await beginTransactions(test, connectionsOf(test))\n },\n}\n\n/** Laravel's DatabaseMigrations: `migrate:fresh` before each test, `migrate:rollback` after it. */\nexport const DatabaseMigrations: TestTrait = {\n async setUp(test: DatabaseTest) {\n await runCommand(test.app, 'migrate:fresh', seedOptions(test))\n test.beforeApplicationDestroyed(() => runCommand(test.app, 'migrate:rollback'))\n },\n}\n\n/** Laravel's DatabaseTransactions: each test runs in a transaction that is rolled back (no migrations). */\nexport const DatabaseTransactions: TestTrait = {\n async setUp(test: DatabaseTest) {\n await beginTransactions(test, connectionsOf(test))\n },\n}\n","import { AuthFactory, type Authenticatable } from '@orieljs/contracts'\nimport { assert } from '../assert'\nimport { HttpClient, type RequestData } from '../Http/HttpClient'\nimport type { TestResponse } from '../TestResponse'\nimport { InteractsWithApplication } from './InteractsWithApplication'\n\ntype Headers = Record<string, string>\n\n/** Laravel's MakesHttpRequests: requests run in-process through the app's HttpKernel. State lasts for one test. */\nexport abstract class MakesHttpRequests extends InteractsWithApplication {\n private client: HttpClient | undefined\n\n /** The current test's HTTP client (created on first use). */\n protected get http(): HttpClient {\n return (this.client ??= this.createHttpClient())\n }\n\n protected createHttpClient(): HttpClient {\n return new HttpClient(this.app)\n }\n\n override async tearDown(): Promise<void> {\n try {\n await super.tearDown()\n } finally {\n this.client = undefined\n }\n }\n\n withHeaders(headers: Headers): this {\n Object.assign(this.http.headers, headers)\n return this\n }\n\n withHeader(name: string, value: string): this {\n this.http.headers[name] = value\n return this\n }\n\n withToken(token: string, type = 'Bearer'): this {\n return this.withHeader('Authorization', `${type} ${token}`)\n }\n\n withBasicAuth(username: string, password: string): this {\n return this.withToken(Buffer.from(`${username}:${password}`).toString('base64'), 'Basic')\n }\n\n /** Removes the Authorization header, whatever case it was set with (header names are case-insensitive). */\n withoutToken(): this {\n for (const name of Object.keys(this.http.headers)) if (name.toLowerCase() === 'authorization') delete this.http.headers[name]\n return this\n }\n\n /** Cookies are encrypted the way EncryptCookies expects when the app has an Encrypter. */\n withCookies(cookies: Record<string, string>): this {\n for (const [name, value] of Object.entries(cookies)) this.http.cookies.set(name, { value, encrypt: true })\n return this\n }\n\n withCookie(name: string, value: string): this {\n return this.withCookies({ [name]: value })\n }\n\n withUnencryptedCookies(cookies: Record<string, string>): this {\n for (const [name, value] of Object.entries(cookies)) this.http.cookies.set(name, { value, encrypt: false })\n return this\n }\n\n withUnencryptedCookie(name: string, value: string): this {\n return this.withUnencryptedCookies({ [name]: value })\n }\n\n /** Follow redirects (always with GET, like Laravel) and return the final response. */\n followingRedirects(): this {\n this.http.followRedirects = true\n return this\n }\n\n /** Sets the Referer and the session's previous URL, so redirect()->back() goes there. */\n from(url: string): this {\n this.http.previousUrl = url\n return this.withHeader('Referer', url)\n }\n\n /** Puts data in the session for the following requests (Laravel's withSession()). */\n withSession(data: Record<string, unknown>): this {\n this.http.session = { ...this.http.session, ...data }\n return this\n }\n\n /** Empties the session carried between requests. */\n flushSession(): this {\n this.http.session = {}\n return this\n }\n\n /** Every following request is authenticated as `user` on `guard` (which also becomes the default guard). */\n actingAs(user: Authenticatable, guard?: string): this {\n this.http.users.set(guard, user)\n if (guard !== undefined) this.http.defaultGuard = guard\n return this\n }\n\n be(user: Authenticatable, guard?: string): this {\n return this.actingAs(user, guard)\n }\n\n /** Errors escape from the request instead of being rendered (Laravel's withoutExceptionHandling()). */\n withoutExceptionHandling(): this {\n this.http.handleExceptions = false\n return this\n }\n\n withExceptionHandling(): this {\n this.http.handleExceptions = true\n return this\n }\n\n /** The user is authenticated (after the requests so far: carried session and actingAs). */\n async assertAuthenticated(guard?: string): Promise<this> {\n assert(await this.isAuthenticated(guard), 'The user is not authenticated')\n return this\n }\n\n async assertGuest(guard?: string): Promise<this> {\n assert(!(await this.isAuthenticated(guard)), 'The user is authenticated')\n return this\n }\n\n /** Same identifier and class as `user`. */\n async assertAuthenticatedAs(user: Authenticatable, guard?: string): Promise<this> {\n const current = await this.http.inScope((scope) => scope.make(AuthFactory).guard(guard).user())\n assert(current !== undefined, 'The current user is not authenticated.')\n assert(\n current.constructor === user.constructor && current.getAuthIdentifier() === user.getAuthIdentifier(),\n `The currently authenticated user [${String(current.getAuthIdentifier())}] is not who was expected [${String(user.getAuthIdentifier())}].`,\n )\n return this\n }\n\n protected isAuthenticated(guard?: string): Promise<boolean> {\n return this.http.inScope((scope) => scope.make(AuthFactory).guard(guard).check())\n }\n\n get(uri: string, headers: Headers = {}): Promise<TestResponse> {\n return this.http.request('GET', uri, { headers })\n }\n\n getJson(uri: string, headers: Headers = {}): Promise<TestResponse> {\n return this.http.request('GET', uri, { headers, json: true })\n }\n\n post(uri: string, data: RequestData = {}, headers: Headers = {}): Promise<TestResponse> {\n return this.http.request('POST', uri, { data, headers })\n }\n\n postJson(uri: string, data: RequestData = {}, headers: Headers = {}): Promise<TestResponse> {\n return this.http.request('POST', uri, { data, headers, json: true })\n }\n\n put(uri: string, data: RequestData = {}, headers: Headers = {}): Promise<TestResponse> {\n return this.http.request('PUT', uri, { data, headers })\n }\n\n putJson(uri: string, data: RequestData = {}, headers: Headers = {}): Promise<TestResponse> {\n return this.http.request('PUT', uri, { data, headers, json: true })\n }\n\n patch(uri: string, data: RequestData = {}, headers: Headers = {}): Promise<TestResponse> {\n return this.http.request('PATCH', uri, { data, headers })\n }\n\n patchJson(uri: string, data: RequestData = {}, headers: Headers = {}): Promise<TestResponse> {\n return this.http.request('PATCH', uri, { data, headers, json: true })\n }\n\n delete(uri: string, data: RequestData = {}, headers: Headers = {}): Promise<TestResponse> {\n return this.http.request('DELETE', uri, { data, headers })\n }\n\n deleteJson(uri: string, data: RequestData = {}, headers: Headers = {}): Promise<TestResponse> {\n return this.http.request('DELETE', uri, { data, headers, json: true })\n }\n\n options(uri: string, data: RequestData = {}, headers: Headers = {}): Promise<TestResponse> {\n return this.http.request('OPTIONS', uri, { data, headers })\n }\n\n head(uri: string, headers: Headers = {}): Promise<TestResponse> {\n return this.http.request('HEAD', uri, { headers })\n }\n\n /** A JSON request with any verb; GET/HEAD data goes into the query string. */\n json(method: string, uri: string, data: RequestData = {}, headers: Headers = {}): Promise<TestResponse> {\n return this.http.request(method, uri, { data, headers, json: true })\n }\n\n /** Any verb with form data (Laravel's call()). */\n call(method: string, uri: string, data: RequestData = {}, headers: Headers = {}): Promise<TestResponse> {\n return this.http.request(method, uri, { data, headers })\n }\n}\n","import {\n AuthFactory,\n ConfigRepository,\n Encrypter,\n ExceptionHandler,\n HttpKernel,\n Session,\n ViewFactory,\n type Application,\n type Authenticatable,\n type Class,\n type Container,\n} from '@orieljs/contracts'\nimport { fail } from '../assert'\nimport { clonePlain } from '../environment'\nimport { TestResponse, type ResponseContext } from '../TestResponse'\nimport { cookieHeader, encryptCookie, isExpired, responseCookies } from './cookies'\nimport { actingAsAuthFactory, recordingExceptionHandler, recordingViewFactory } from './recorders'\n\nexport type RequestData = Record<string, unknown>\n\nexport interface RequestOptions {\n data?: RequestData\n headers?: Record<string, string>\n /** Send data as a JSON body (the *Json methods). */\n json?: boolean\n}\n\n/** The address Http's request.ip() reads for requests that didn't come through a server (01-http-routing.md). */\nconst CLIENT_ADDRESS = Symbol.for('oriel:http.client-address')\nconst MAX_REDIRECTS = 20\n\n/**\n * Laravel's MakesHttpRequests state for one test: default headers, cookies, the session carried between\n * requests, actingAs users and options, plus the dispatch itself.\n */\nexport class HttpClient {\n readonly headers: Record<string, string> = {}\n /** Cookies to encrypt on send (withCookie) and to send as-is (withUnencryptedCookie, or captured from responses). */\n readonly cookies = new Map<string, { value: string; encrypt: boolean }>()\n /** actingAs() users by guard name (undefined = the default guard). */\n readonly users = new Map<string | undefined, Authenticatable>()\n followRedirects = false\n handleExceptions = true\n /** The guard actingAs(user, guard) made the default. */\n defaultGuard: string | undefined\n /** Session attributes carried from one request to the next (Laravel keeps one session store per test). */\n session: Record<string, unknown> | undefined\n /** from(url): the session's previous URL for the next request only (Laravel sets it once). */\n previousUrl: string | undefined\n /** Requests whose actingAs users reached the guards (the AuthFactory they went through). */\n private readonly actingAsApplied = new WeakMap<ResponseContext, AuthFactory>()\n\n constructor(protected readonly app: Application) {}\n\n async request(method: string, uri: string, options: RequestOptions = {}): Promise<TestResponse> {\n let response = await this.send(this.buildRequest(method, uri, options))\n if (!this.followRedirects) return response\n for (let hops = 0; isRedirect(response.status); hops++) {\n if (hops >= MAX_REDIRECTS) fail(`Too many redirects (more than ${MAX_REDIRECTS}), last location [${response.headers.get('Location')}].`)\n response = await this.send(this.buildRequest('GET', response.headers.get('Location') ?? '/', {}))\n }\n return response\n }\n\n /** Runs `fn` in a scope prepared like a request's (carried session, actingAs users), e.g. for assertAuthenticated(). */\n async inScope<T>(fn: (scope: Container) => T | Promise<T>): Promise<T> {\n await this.app.boot()\n const scope = this.app.createScope()\n return scope.run(async () => {\n await this.beforeRequest(scope, {})\n return fn(scope)\n })\n }\n\n /** Runs the request through the app's real HttpKernel, in a request scope this client owns. */\n protected async send(request: Request): Promise<TestResponse> {\n const app = this.app\n await app.boot()\n setClientAddress(request, '127.0.0.1')\n const scope = app.createScope()\n const context: ResponseContext = { request, app, client: this }\n const response = await scope.run(async () => {\n await this.beforeRequest(scope, context)\n this.previousUrl = undefined\n return scope.make(HttpKernel).handle(request)\n })\n await scope.run(() => this.afterRequest(scope, context))\n this.rememberCookies(response)\n await app.make(HttpKernel).terminate?.(request, response)\n if (!this.handleExceptions && context.exception !== undefined) throw context.exception\n return TestResponse.from(response, context)\n }\n\n /** Prepares the request scope: recorders, the carried session and actingAs users. */\n protected beforeRequest(scope: Container, context: ResponseContext): void {\n const views: NonNullable<ResponseContext['views']> = (context.views = [])\n if (this.app.bound(ViewFactory)) scope.instance(ViewFactory, recordingViewFactory(this.app.make(ViewFactory), views))\n if (this.app.bound(ExceptionHandler)) {\n scope.instance(ExceptionHandler, recordingExceptionHandler(this.app.make(ExceptionHandler), (error) => (context.exception = error)))\n }\n const session = this.scopeSession(scope)\n if (session !== undefined) {\n if (this.session !== undefined) session.put(clonePlain(this.session))\n if (this.previousUrl !== undefined) session.setPreviousUrl(this.previousUrl)\n context.session = session\n }\n if ((this.users.size > 0 || this.defaultGuard !== undefined) && this.app.bound(AuthFactory)) {\n const auth = this.app.make(AuthFactory)\n const acting = actingAsAuthFactory(auth, this.users, this.defaultGuard, () => {\n this.actingAsApplied.set(context, auth)\n })\n scope.instance(AuthFactory, acting)\n // Auth also binds its AuthManager class to the same singleton, so inject(AuthManager) must see the users too.\n const manager: unknown = auth.constructor\n if (typeof manager === 'function' && manager !== Object && this.app.bound(manager as Class<AuthFactory>)) {\n scope.instance(manager as Class<AuthFactory>, acting)\n }\n }\n }\n\n /** Keeps the session for the next request, like Laravel's per-test session store, and the guards' users. */\n protected async afterRequest(_scope: Container, context: ResponseContext): Promise<void> {\n if (context.session !== undefined) this.session = clonePlain(context.session.all())\n const auth = this.actingAsApplied.get(context)\n if (auth !== undefined) await this.syncActingAs(auth)\n }\n\n /**\n * Laravel's actingAs() sets the user on the guard once, so a logout (or a login as someone else) in the\n * request sticks. Reads each actingAs guard back and forgets or replaces its user to match.\n */\n protected async syncActingAs(auth: AuthFactory): Promise<void> {\n for (const guard of [...this.users.keys()]) {\n const user = await auth.guard(guard).user()\n if (user === undefined) this.users.delete(guard)\n else this.users.set(guard, user)\n }\n }\n\n /** The request's (scoped) Session, created now so the carried attributes are in place before StartSession. */\n protected scopeSession(scope: Container): Session | undefined {\n if (!scope.bound(Session)) return undefined\n try {\n return scope.make(Session)\n } catch {\n return undefined\n }\n }\n\n buildRequest(method: string, uri: string, options: RequestOptions): Request {\n const verb = method.toUpperCase()\n const url = new URL(uri, this.baseUrl())\n const headers = new Headers({ ...this.headers, ...options.headers })\n let body: string | FormData | URLSearchParams | undefined\n const data = options.data ?? {}\n\n if (verb === 'GET' || verb === 'HEAD') {\n for (const [key, value] of flatten(data)) if (typeof value === 'string') url.searchParams.append(key, value)\n } else if (options.json) {\n body = JSON.stringify(data)\n } else if (Object.keys(data).length > 0) {\n const fields = flatten(data)\n if (fields.some(([, value]) => typeof value !== 'string')) {\n const form = new FormData()\n for (const [key, value] of fields) form.append(key, value)\n body = form\n } else {\n body = new URLSearchParams(fields as Array<[string, string]>)\n }\n }\n if (options.json) {\n if (body !== undefined) headers.set('Content-Type', 'application/json')\n headers.set('Accept', 'application/json')\n }\n const cookies = this.cookieHeader()\n if (cookies !== '') headers.set('Cookie', cookies)\n return new Request(url, { method: verb, headers, body })\n }\n\n protected baseUrl(): string {\n const configured = this.app.bound(ConfigRepository) ? this.app.make(ConfigRepository).get<unknown>('app.url') : undefined\n return typeof configured === 'string' && configured !== '' ? configured : 'http://localhost'\n }\n\n protected cookieHeader(): string {\n const encrypter = this.app.bound(Encrypter) ? this.app.make(Encrypter) : undefined\n const values = new Map<string, string>()\n for (const [name, { value, encrypt }] of this.cookies) {\n values.set(name, encrypt && encrypter !== undefined ? encryptCookie(encrypter, name, value) : value)\n }\n return cookieHeader(values)\n }\n\n /** Like a browser: cookies the app sets are sent back on later requests in the same test; deleted ones are dropped. */\n protected rememberCookies(response: Response): void {\n for (const cookie of responseCookies(response)) {\n if (isExpired(cookie)) this.cookies.delete(cookie.name)\n else this.cookies.set(cookie.name, { value: cookie.value, encrypt: false })\n }\n }\n}\n\nfunction isRedirect(status: number): boolean {\n return status >= 300 && status < 400 && status !== 304\n}\n\nfunction setClientAddress(request: Request, address: string): void {\n const g = globalThis as unknown as Record<symbol, WeakMap<Request, string> | undefined>\n ;(g[CLIENT_ADDRESS] ??= new WeakMap<Request, string>()).set(request, address)\n}\n\n/** `{ user: { name: 'a' }, tags: ['x'] }` → `user[name]=a`, `tags[0]=x` (the PHP bracket form Http parses). */\nexport function flatten(data: RequestData, prefix = ''): Array<[string, string | Blob]> {\n const out: Array<[string, string | Blob]> = []\n for (const [key, value] of Object.entries(data)) {\n const name = prefix === '' ? key : `${prefix}[${key}]`\n if (value === undefined) continue\n if (value === null) out.push([name, ''])\n else if (value instanceof Blob) out.push([name, value])\n else if (value instanceof Date) out.push([name, value.toISOString()])\n else if (typeof value === 'object') out.push(...flatten(value as RequestData, name))\n else if (typeof value === 'boolean') out.push([name, value ? '1' : '0'])\n else out.push([name, String(value as string | number | bigint)])\n }\n return out\n}\n","/**\n * Laravel's phpunit.xml <env> block. Applied before every test's application is created; variables that are\n * already set (the shell, CI, vitest.config) win, like phpunit's non-forced <env>.\n */\nexport const TESTING_ENVIRONMENT: Readonly<Record<string, string>> = Object.freeze({\n APP_ENV: 'testing',\n BCRYPT_ROUNDS: '4',\n CACHE_STORE: 'array',\n DB_CONNECTION: 'sqlite',\n DB_DATABASE: ':memory:',\n MAIL_MAILER: 'array',\n QUEUE_CONNECTION: 'sync',\n SESSION_DRIVER: 'array',\n})\n\nexport function applyEnvironment(values: Record<string, string>, env: NodeJS.ProcessEnv = process.env): void {\n for (const [key, value] of Object.entries(values)) env[key] ??= value\n}\n\n/** Copies plain objects and arrays; class instances, functions and other values are kept by reference. */\nexport function clonePlain<T>(value: T): T {\n if (Array.isArray(value)) return value.map((item: unknown) => clonePlain(item)) as T\n if (typeof value === 'object' && value !== null) {\n const proto = Object.getPrototypeOf(value) as unknown\n if (proto !== Object.prototype && proto !== null) return value\n return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, clonePlain(item)])) as T\n }\n return value\n}\n","import { Encrypter, UrlGenerator, type Application, type InertiaPage, type Session, type View } from '@orieljs/contracts'\nimport { Arr } from '@orieljs/support'\nimport { assert, assertStructure, containsPair, equals, escapeHtml, fail, format, isSubset, stripTags, type JsonStructure } from './assert'\nimport { AssertableInertia, inertiaPageOf } from './Fluent/AssertableInertia'\nimport { AssertableJson } from './Fluent/AssertableJson'\nimport { decryptCookie, isExpired, responseCookies, type ResponseCookie } from './Http/cookies'\nimport type { HttpClient } from './Http/HttpClient'\n\n/** Field → messages, as Http flashes them per bag: `errors: { [bag]: { field: string[] } }`. */\ntype ErrorMessages = Record<string, string[]>\n/** `'email'`, `['email', 'name']` or `{ email: 'must be valid' }` (message fragments). */\nexport type ExpectedErrors = string | string[] | Record<string, string | string[]>\n\n/** What the HTTP client knows about the request that produced a response. */\nexport interface ResponseContext {\n /** The raw request sent to the kernel (redirect URLs are resolved against it). */\n request?: Request\n /** The application that handled it. */\n app?: Application\n /** The request's session after the response. */\n session?: Session\n /** Views made while handling the request, in order. */\n views?: View[]\n /** The last error the exception handler rendered. */\n exception?: unknown\n /** The client that sent the request (Inertia reloads reuse it, keeping the session and cookies). */\n client?: HttpClient\n}\n\nconst REDIRECTS = new Set([201, 301, 302, 303, 307, 308])\n\n/** Laravel's TestResponse: a Response with its body already read, plus fluent assertions. */\nexport class TestResponse {\n private decoded: { value: unknown } | undefined\n\n constructor(\n readonly baseResponse: Response,\n readonly content: string,\n readonly context: ResponseContext = {},\n ) {}\n\n /** Reads the body once, so every assertion is synchronous. */\n static async from(response: Response, context: ResponseContext = {}): Promise<TestResponse> {\n return new TestResponse(response, await response.text(), context)\n }\n\n get status(): number {\n return this.baseResponse.status\n }\n\n get headers(): Headers {\n return this.baseResponse.headers\n }\n\n /** The error the exception handler rendered for this request, if any. */\n get exception(): unknown {\n return this.context.exception\n }\n\n getContent(): string {\n return this.content\n }\n\n /** The decoded JSON body, or the value at a dot path (`data.0.id`). */\n json<T = unknown>(path?: string): T {\n if (this.decoded === undefined) {\n try {\n this.decoded = { value: JSON.parse(this.content) }\n } catch {\n fail(`Invalid JSON was returned from the route.\\n\\n${this.excerpt()}`)\n }\n }\n return Arr.get<T>(this.decoded.value, path)\n }\n\n dump(path?: string): this {\n console.log(path === undefined ? this.content : this.json(path))\n return this\n }\n\n // Status ------------------------------------------------------------------------------------------------\n\n assertStatus(status: number): this {\n if (this.status !== status) fail(this.statusMessage(`Expected response status code [${status}] but received ${this.status}.`), { actual: this.status, expected: status })\n return this\n }\n\n assertOk(): this { return this.assertStatus(200) }\n assertCreated(): this { return this.assertStatus(201) }\n assertAccepted(): this { return this.assertStatus(202) }\n assertMovedPermanently(): this { return this.assertStatus(301) }\n assertFound(): this { return this.assertStatus(302) }\n assertNotModified(): this { return this.assertStatus(304) }\n assertBadRequest(): this { return this.assertStatus(400) }\n assertUnauthorized(): this { return this.assertStatus(401) }\n assertPaymentRequired(): this { return this.assertStatus(402) }\n assertForbidden(): this { return this.assertStatus(403) }\n assertNotFound(): this { return this.assertStatus(404) }\n assertMethodNotAllowed(): this { return this.assertStatus(405) }\n assertNotAcceptable(): this { return this.assertStatus(406) }\n assertRequestTimeout(): this { return this.assertStatus(408) }\n assertConflict(): this { return this.assertStatus(409) }\n assertGone(): this { return this.assertStatus(410) }\n assertUnsupportedMediaType(): this { return this.assertStatus(415) }\n assertUnprocessable(): this { return this.assertStatus(422) }\n assertTooManyRequests(): this { return this.assertStatus(429) }\n assertInternalServerError(): this { return this.assertStatus(500) }\n assertServiceUnavailable(): this { return this.assertStatus(503) }\n\n /** 204 (or `status`) with an empty body. */\n assertNoContent(status = 204): this {\n this.assertStatus(status)\n assert(this.content === '', 'Response content is not empty.', { actual: this.content, expected: '' })\n return this\n }\n\n assertSuccessful(): this {\n assert(this.status >= 200 && this.status < 300, () => this.statusMessage(`Expected response status code [>=200, <300] but received ${this.status}.`))\n return this\n }\n\n assertClientError(): this {\n assert(this.status >= 400 && this.status < 500, () => this.statusMessage(`Expected response status code [>=400, <500] but received ${this.status}.`))\n return this\n }\n\n assertServerError(): this {\n assert(this.status >= 500 && this.status < 600, () => this.statusMessage(`Expected response status code [>=500, <600] but received ${this.status}.`))\n return this\n }\n\n // Redirects ---------------------------------------------------------------------------------------------\n\n /** A redirect status (201, 301, 302, 303, 307, 308); with `uri`, the Location must match it. */\n assertRedirect(uri?: string): this {\n assert(REDIRECTS.has(this.status), () => this.statusMessage(`Expected response status code [201, 301, 302, 303, 307, 308] but received ${this.status}.`))\n if (uri !== undefined) this.assertLocation(uri)\n return this\n }\n\n assertRedirectContains(uri: string): this {\n this.assertRedirect()\n const location = this.headers.get('Location') ?? ''\n assert(location.includes(uri), `Redirect location [${location}] does not contain [${uri}].`)\n return this\n }\n\n /** Relative and absolute forms of the same URL are equal (both are resolved against the request URL). */\n assertLocation(uri: string): this {\n const actual = this.absolute(this.headers.get('Location') ?? '')\n const expected = this.absolute(uri)\n assert(actual === expected, `Failed asserting that the redirect location [${actual}] equals [${expected}].`, { actual, expected })\n return this\n }\n\n // Headers -----------------------------------------------------------------------------------------------\n\n assertHeader(name: string, value?: string): this {\n const actual = this.headers.get(name)\n assert(actual !== null, `Header [${name}] not present on response.`)\n if (value !== undefined) assert(actual === value, `Header [${name}] was found, but value [${actual}] does not match [${value}].`, { actual, expected: value })\n return this\n }\n\n assertHeaderMissing(name: string): this {\n assert(!this.headers.has(name), `Unexpected header [${name}] is present on response.`)\n return this\n }\n\n /** Content-Disposition: attachment (optionally with this file name). */\n assertDownload(filename?: string): this {\n const disposition = this.headers.get('Content-Disposition') ?? ''\n assert(/^attachment/i.test(disposition), 'Response does not offer a file download.')\n if (filename !== undefined) {\n assert(disposition.includes(`filename=\"${filename}\"`) || disposition.includes(`filename=${filename}`), `Expected file [${filename}] is not present in Content-Disposition header [${disposition}].`)\n }\n return this\n }\n\n // Content -----------------------------------------------------------------------------------------------\n\n assertContent(value: string): this {\n assert(this.content === value, 'Response content does not match.', { actual: this.content, expected: value })\n return this\n }\n\n /** The content contains the value(s); values are HTML-escaped first unless `escape` is false (Laravel). */\n assertSee(value: string | string[], escape = true): this {\n for (const needle of this.needles(value, escape)) {\n assert(this.content.includes(needle), `Failed asserting that the response contains [${needle}].\\n\\n${this.excerpt()}`)\n }\n return this\n }\n\n assertDontSee(value: string | string[], escape = true): this {\n for (const needle of this.needles(value, escape)) {\n assert(!this.content.includes(needle), `Failed asserting that the response does not contain [${needle}].\\n\\n${this.excerpt()}`)\n }\n return this\n }\n\n assertSeeInOrder(values: string[], escape = true): this {\n return this.inOrder(this.content, this.needles(values, escape))\n }\n\n /** Like assertSee, against the content with its tags stripped. */\n assertSeeText(value: string | string[], escape = true): this {\n const text = stripTags(this.content)\n for (const needle of this.needles(value, escape)) {\n assert(text.includes(needle), `Failed asserting that the response text contains [${needle}].\\n\\n${this.excerpt(text)}`)\n }\n return this\n }\n\n assertDontSeeText(value: string | string[], escape = true): this {\n const text = stripTags(this.content)\n for (const needle of this.needles(value, escape)) {\n assert(!text.includes(needle), `Failed asserting that the response text does not contain [${needle}].`)\n }\n return this\n }\n\n assertSeeTextInOrder(values: string[], escape = true): this {\n return this.inOrder(stripTags(this.content), this.needles(values, escape))\n }\n\n // JSON --------------------------------------------------------------------------------------------------\n\n /**\n * The response JSON contains `data` (a subset match: extra keys in the response are fine), or fluent\n * assertions: assertJson(json => json.has('data', 3).etc()).\n */\n assertJson(data: Record<string, unknown> | unknown[] | ((json: AssertableJson) => unknown)): this {\n if (typeof data === 'function') {\n const json = AssertableJson.fromJson(this.json())\n data(json)\n if (!Array.isArray(json.toArray())) json.interacted()\n return this\n }\n const actual = this.json()\n assert(isSubset(data, actual), 'Unable to find the expected JSON subset in the response.', { actual, expected: data })\n return this\n }\n\n // Inertia -----------------------------------------------------------------------------------------------\n\n /**\n * An Inertia page response, with optional fluent assertions over its props. An async callback (reload(),\n * loadDeferredProps()) makes this return a promise: await it.\n */\n assertInertia(callback: (page: AssertableInertia) => Promise<unknown>): Promise<this>\n assertInertia(callback?: (page: AssertableInertia) => unknown): this\n assertInertia(callback?: (page: AssertableInertia) => unknown): this | Promise<this> {\n const page = AssertableInertia.fromTestResponse(this)\n const result = callback?.(page)\n if (typeof (result as PromiseLike<unknown> | undefined)?.then === 'function') return Promise.resolve(result).then(() => this)\n return this\n }\n\n /** The Inertia page object of this response. */\n inertiaPage(): InertiaPage {\n return inertiaPageOf(this)\n }\n\n /** The page props, or one prop by dot path. */\n inertiaProps<T = unknown>(key?: string): T {\n return Arr.get<T>(inertiaPageOf(this).props, key)\n }\n\n /** Inertia flash data waiting in the session for the next page (after a redirect). */\n assertInertiaFlash(key: string, ...expected: [] | [unknown]): this {\n AssertableInertia.assertFlashHas(this.session().get<Record<string, unknown>>('inertia.flash_data', {}), key, ...expected)\n return this\n }\n\n assertInertiaFlashMissing(key: string): this {\n AssertableInertia.assertFlashMissing(this.session().get<Record<string, unknown>>('inertia.flash_data', {}), key)\n return this\n }\n\n /** The response JSON equals `data` exactly (object key order is ignored). */\n assertExactJson(data: unknown): this {\n const actual = this.json()\n assert(equals(actual, data), 'Failed asserting that the response JSON matches exactly.', { actual, expected: data })\n return this\n }\n\n /** The value at `path` equals `expected` (strictly), or passes the predicate. */\n assertJsonPath(path: string, expected: unknown): this {\n assert(Arr.has(this.json(), path), `Failed asserting that the JSON has the path [${path}].`, { actual: this.json() })\n const actual = this.json(path)\n if (typeof expected === 'function') {\n assert((expected as (value: unknown) => unknown)(actual) === true, `Failed asserting that the value at [${path}] passes the given check (got ${format(actual)}).`)\n } else {\n assert(equals(actual, expected), `Failed asserting that the value at [${path}] equals ${format(expected)} (got ${format(actual)}).`, { actual, expected })\n }\n return this\n }\n\n assertJsonMissingPath(path: string): this {\n assert(!Arr.has(this.json(), path), `Failed asserting that the JSON does not have the path [${path}].`)\n return this\n }\n\n /** Each key/value pair appears somewhere in the JSON (Laravel's assertJsonFragment). */\n assertJsonFragment(data: Record<string, unknown>): this {\n const actual = this.json()\n for (const [key, value] of Object.entries(data)) {\n assert(containsPair(actual, key, value), `Unable to find JSON fragment ${format({ [key]: value })} in the response.`, { actual, expected: data })\n }\n return this\n }\n\n /** Passes when at least one pair of `data` is absent (Laravel's assertJsonMissing). */\n assertJsonMissing(data: Record<string, unknown>): this {\n const actual = this.json()\n const allPresent = Object.entries(data).every(([key, value]) => containsPair(actual, key, value))\n assert(!allPresent, `Found unexpected JSON fragment ${format(data)} in the response.`, { actual })\n return this\n }\n\n /** `['id', { author: ['name'] }]`, `{ data: { '*': ['id'] } }`; without a structure, just checks it's JSON. */\n assertJsonStructure(structure?: JsonStructure): this {\n const data = this.json()\n if (structure !== undefined) assertStructure(structure, data)\n return this\n }\n\n /** The JSON (or the value at `key`) has `count` elements. */\n assertJsonCount(count: number, key?: string): this {\n const value = this.json(key)\n const actual = Array.isArray(value) ? value.length : typeof value === 'object' && value !== null ? Object.keys(value).length : -1\n assert(actual === count, `Failed to assert that the response ${key === undefined ? '' : `[${key}] `}count matched the expected ${count} (got ${actual}).`, { actual, expected: count })\n return this\n }\n\n /** assertRedirect() to the URL of a named route (resolved with the app's UrlGenerator). */\n assertRedirectToRoute(name: string, parameters?: unknown): this {\n const app = this.context.app\n assert(app !== undefined && app.bound(UrlGenerator), 'assertRedirectToRoute() needs an application with a UrlGenerator (the Routing component).')\n return this.assertRedirect(app.make(UrlGenerator).route(name, parameters))\n }\n\n // Validation --------------------------------------------------------------------------------------------\n\n /** The JSON body has validation errors for these keys (and messages containing these fragments). */\n assertJsonValidationErrors(errors: ExpectedErrors, responseKey = 'errors'): this {\n const actual = this.json<unknown>(responseKey)\n assert(typeof actual === 'object' && actual !== null, `Failed to find validation errors in the response under [${responseKey}].\\n\\n${this.excerpt()}`)\n this.assertErrorsContain(actual as ErrorMessages, errors, 'response')\n return this\n }\n\n /** No validation errors in the JSON (or none for these keys). */\n assertJsonMissingValidationErrors(keys?: string | string[], responseKey = 'errors'): this {\n if (this.content === '') return this\n const errors = Arr.get<ErrorMessages | undefined>(this.json(), responseKey)\n if (errors === undefined || errors === null) return this\n const unexpected = keys === undefined ? Object.keys(errors) : [keys].flat().filter((key) => Object.hasOwn(errors, key))\n assert(unexpected.length === 0, `Found unexpected validation error(s) for [${unexpected.join(', ')}]: ${format(errors)}`)\n return this\n }\n\n /** No validation errors: JSON responses are checked in the body, others in the session. */\n assertValid(keys?: string | string[], errorBag = 'default', responseKey = 'errors'): this {\n if (this.isJson()) return this.assertJsonMissingValidationErrors(keys, responseKey)\n if (this.context.session?.has('errors') !== true) return this\n return keys === undefined ? this.assertSessionDoesntHaveErrors([], undefined, errorBag) : this.assertSessionDoesntHaveErrors(keys, undefined, errorBag)\n }\n\n /** Validation errors for these keys (message fragments match with \"contains\"): JSON body or session. */\n assertInvalid(errors: ExpectedErrors, errorBag = 'default', responseKey = 'errors'): this {\n if (this.isJson()) return this.assertJsonValidationErrors(errors, responseKey)\n this.assertSessionHas('errors')\n this.assertErrorsContain(this.sessionErrors(errorBag), errors, 'session')\n return this\n }\n\n // Session -----------------------------------------------------------------------------------------------\n\n /** The request's session after the response (flashed data is still there). */\n session(): Session {\n const session = this.context.session\n assert(session !== undefined, 'The response has no session: is the Session component registered?')\n return session\n }\n\n /** A key (with an optional value or predicate), several keys, or a { key: value } record. */\n assertSessionHas(key: string | string[] | Record<string, unknown>, value?: unknown): this {\n if (Array.isArray(key)) {\n for (const k of key) this.assertSessionHas(k)\n return this\n }\n if (typeof key === 'object') return this.assertSessionHasAll(key)\n const session = this.session()\n if (value === undefined) {\n assert(session.has(key), `Session is missing expected key [${key}].`)\n } else if (typeof value === 'function') {\n assert((value as (v: unknown) => unknown)(session.get(key)) === true, `Session value for [${key}] does not pass the given check.`)\n } else {\n assert(equals(session.get(key), value), `Session value for [${key}] does not match.`, { actual: session.get(key), expected: value })\n }\n return this\n }\n\n assertSessionHasAll(bindings: Record<string, unknown>): this {\n for (const [key, value] of Object.entries(bindings)) this.assertSessionHas(key, value)\n return this\n }\n\n assertSessionMissing(key: string | string[], value?: unknown): this {\n const session = this.session()\n for (const k of [key].flat()) {\n if (value === undefined) assert(!session.has(k), `Session has unexpected key [${k}].`)\n else assert(!equals(session.get(k), value), `Session has unexpected value for [${k}].`)\n }\n return this\n }\n\n /** Old input flashed with the redirect (withInput()). */\n assertSessionHasInput(key: string | string[] | Record<string, unknown>, value?: unknown): this {\n const session = this.session()\n const entries: Array<[string, unknown]> =\n typeof key === 'string' ? [[key, value]] : Array.isArray(key) ? key.map((k) => [k, undefined]) : Object.entries(key)\n for (const [k, expected] of entries) {\n const actual = session.getOldInput<unknown>(k)\n assert(actual !== undefined, `Session is missing expected key [${k}] in the old input.`)\n if (expected !== undefined) assert(equals(actual, expected), `Old input [${k}] does not match.`, { actual, expected })\n }\n return this\n }\n\n /**\n * The session has errors in `errorBag`: any at all, these keys, or these exact messages (Laravel's rules).\n * `format` is a ':message' template applied to the actual messages first.\n */\n assertSessionHasErrors(keys: ExpectedErrors = [], format?: string, errorBag = 'default'): this {\n this.assertSessionHas('errors')\n const errors = this.formatted(this.sessionErrors(errorBag), format)\n const expected = typeof keys === 'string' ? [keys] : keys\n if (Array.isArray(expected) && expected.length === 0) {\n assert(Object.keys(errors).length > 0, `Session has no errors in the [${errorBag}] bag.`)\n return this\n }\n for (const [key, messages] of normalizeExpected(expected)) {\n assert(Object.hasOwn(errors, key), `Session missing error: ${key}`, { actual: errors })\n for (const message of messages) {\n assert(errors[key]!.includes(message), `Session error for [${key}] does not include ${format === undefined ? '' : 'the formatted '}message ${JSON.stringify(message)}.`, { actual: errors[key], expected: message })\n }\n }\n return this\n }\n\n assertSessionHasErrorsIn(errorBag: string, keys: ExpectedErrors = [], format?: string): this {\n return this.assertSessionHasErrors(keys, format, errorBag)\n }\n\n /** No errors in any bag. */\n assertSessionHasNoErrors(): this {\n const bags = this.context.session?.get<Record<string, ErrorMessages> | undefined>('errors')\n const found = Object.fromEntries(Object.entries(bags ?? {}).filter(([, messages]) => Object.keys(messages ?? {}).length > 0))\n assert(Object.keys(found).length === 0, `Session has unexpected errors: \\n\\n${JSON.stringify(found, null, 2)}`, { actual: found, expected: {} })\n return this\n }\n\n /** No errors in the bag (or none for these keys). */\n assertSessionDoesntHaveErrors(keys: string | string[] = [], format?: string, errorBag = 'default'): this {\n const errors = this.formatted(this.sessionErrors(errorBag), format)\n const list = [keys].flat()\n if (list.length === 0) {\n assert(Object.keys(errors).length === 0, `Session has unexpected errors: \\n\\n${JSON.stringify(errors, null, 2)}`, { actual: errors, expected: {} })\n return this\n }\n for (const key of list) assert(!Object.hasOwn(errors, key), `Session has unexpected error: ${key}`, { actual: errors[key] })\n return this\n }\n\n // Cookies -----------------------------------------------------------------------------------------------\n\n /** A cookie the response sets (the last Set-Cookie with that name). */\n getCookie(name: string): ResponseCookie | undefined {\n return responseCookies(this.baseResponse).findLast((cookie) => cookie.name === name)\n }\n\n /** The cookie is set; with `value`, its (decrypted, unless `encrypted` is false) value matches. */\n assertCookie(name: string, value?: string, encrypted = true): this {\n const cookie = this.getCookie(name)\n assert(cookie !== undefined, `Cookie [${name}] not present on response.`)\n if (value === undefined) return this\n const actual = encrypted ? this.decrypted(cookie) : cookie.value\n assert(actual === value, `Cookie [${name}] was found, but value [${actual}] does not match [${value}].`, { actual, expected: value })\n return this\n }\n\n assertPlainCookie(name: string, value?: string): this {\n return this.assertCookie(name, value, false)\n }\n\n assertCookieExpired(name: string): this {\n const cookie = this.getCookie(name)\n assert(cookie !== undefined, `Cookie [${name}] not present on response.`)\n assert(isExpired(cookie), `Cookie [${name}] is not expired.`)\n return this\n }\n\n assertCookieNotExpired(name: string): this {\n const cookie = this.getCookie(name)\n assert(cookie !== undefined, `Cookie [${name}] not present on response.`)\n assert(!isExpired(cookie), `Cookie [${name}] is expired.`)\n return this\n }\n\n assertCookieMissing(name: string): this {\n assert(this.getCookie(name) === undefined, `Cookie [${name}] is present on response.`)\n return this\n }\n\n // Views -------------------------------------------------------------------------------------------------\n\n /**\n * The view the route returned. A request can make other views too (a mailable's, an error page), so this is the\n * last view whose rendered HTML is the response body, else the last view made.\n */\n get original(): View | undefined {\n const views = this.context.views ?? []\n return views.findLast((view) => renderedHtml(view) === this.content) ?? views.at(-1)\n }\n\n assertViewIs(name: string): this {\n const view = this.ensureView()\n assert(view.name === name, `Failed asserting that the response view [${view.name}] is [${name}].`, { actual: view.name, expected: name })\n return this\n }\n\n /** The view received `key` (dot paths allowed), optionally with this value or passing this predicate. */\n assertViewHas(key: string | string[] | Record<string, unknown>, value?: unknown): this {\n if (typeof key !== 'string') return this.assertViewHasAll(key)\n const data = this.viewDataOf(this.ensureView())\n assert(Arr.has(data, key), `Failed asserting that the view has key [${key}].`, { actual: Object.keys(data) })\n const actual = Arr.get(data, key)\n if (typeof value === 'function') assert((value as (v: unknown) => unknown)(actual) === true, `View data [${key}] does not pass the given check.`)\n else if (value !== undefined) assert(equals(actual, value), `View data [${key}] does not match the expected value.`, { actual, expected: value })\n return this\n }\n\n assertViewHasAll(bindings: string[] | Record<string, unknown>): this {\n if (Array.isArray(bindings)) for (const key of bindings) this.assertViewHas(key)\n else for (const [key, value] of Object.entries(bindings)) this.assertViewHas(key, value)\n return this\n }\n\n assertViewMissing(key: string): this {\n assert(!Arr.has(this.viewDataOf(this.ensureView()), key), `Failed asserting that the view does not have key [${key}].`)\n return this\n }\n\n /** The data the view received (dot path), or all of it. */\n viewData<T = unknown>(key?: string): T {\n return Arr.get<T>(this.viewDataOf(this.ensureView()), key)\n }\n\n // Internals ---------------------------------------------------------------------------------------------\n\n protected absolute(url: string): string {\n try {\n return new URL(url, this.context.request?.url ?? 'http://localhost').href\n } catch {\n return url\n }\n }\n\n protected excerpt(text: string = this.content): string {\n const limit = 2000\n return text.length > limit ? `${text.slice(0, limit)}…` : text\n }\n\n /** Adds the rendered exception (or the body) to a status failure, like Laravel does. */\n protected statusMessage(message: string): string {\n const error = this.context.exception\n if (error instanceof Error) return `${message}\\n\\nThe following exception occurred during the request:\\n\\n${error.stack ?? error.message}`\n return this.content === '' ? message : `${message}\\n\\n${this.excerpt()}`\n }\n\n protected isJson(): boolean {\n return (this.headers.get('Content-Type') ?? '').includes('json')\n }\n\n protected sessionErrors(errorBag: string): ErrorMessages {\n const bags = this.context.session?.get<Record<string, ErrorMessages> | undefined>('errors')\n return bags?.[errorBag] ?? {}\n }\n\n private formatted(errors: ErrorMessages, template?: string): ErrorMessages {\n if (template === undefined) return errors\n return Object.fromEntries(Object.entries(errors).map(([key, messages]) => [key, messages.map((m) => template.replaceAll(':message', m))]))\n }\n\n /** Laravel's assertInvalid/assertJsonValidationErrors: each key present; each expected fragment contained in a message. */\n private assertErrorsContain(errors: ErrorMessages, expected: ExpectedErrors, where: string): void {\n for (const [key, fragments] of normalizeExpected(expected)) {\n assert(Object.hasOwn(errors, key), `Failed to find a validation error in the ${where} for key: [${key}]`, { actual: errors })\n const messages = [errors[key]].flat() as string[]\n for (const fragment of fragments) {\n assert(messages.some((message) => message.includes(fragment)), `Failed to find a validation error for key and message: [${key}] => [${fragment}]`, { actual: messages, expected: fragment })\n }\n }\n }\n\n private ensureView(): View {\n const view = this.original\n assert(view !== undefined, 'The response is not a view.')\n return view\n }\n\n private viewDataOf(view: View): Record<string, unknown> {\n const source = view as View & { gatherData?(): Record<string, unknown>; getData?(): Record<string, unknown> }\n return source.gatherData?.() ?? source.getData?.() ?? {}\n }\n\n private decrypted(cookie: ResponseCookie): string | undefined {\n const app = this.context.app\n if (app === undefined || !app.bound(Encrypter)) return cookie.value\n return decryptCookie(app.make(Encrypter), cookie.name, cookie.value)\n }\n\n private needles(value: string | string[], escape: boolean): string[] {\n return [value].flat().map((needle) => (escape ? escapeHtml(needle) : needle))\n }\n\n private inOrder(haystack: string, needles: string[]): this {\n let position = 0\n for (const needle of needles) {\n const found = haystack.indexOf(needle, position)\n if (found === -1) fail(`Failed asserting that the response contains ${format(needles)} in that order (missing or out of order: [${needle}]).`)\n position = found + needle.length\n }\n return this\n }\n}\n\nfunction normalizeExpected(expected: ExpectedErrors): Array<[string, string[]]> {\n if (typeof expected === 'string') return [[expected, []]]\n if (Array.isArray(expected)) return expected.map((key) => [key, []])\n return Object.entries(expected).map(([key, messages]) => [key, [messages].flat()])\n}\n\n/** The HTML of the view's last render(), or undefined when it was never rendered (toHtml() throws then). */\nfunction renderedHtml(view: View): string | undefined {\n try {\n return view.toHtml()\n } catch {\n return undefined\n }\n}\n","import { existsSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { ConfigRepository, type Application, type InertiaPage } from '@orieljs/contracts'\nimport { Arr } from '@orieljs/support'\nimport { assert, equals, fail } from '../assert'\nimport type { TestResponse } from '../TestResponse'\nimport { AssertableJson } from './AssertableJson'\n\n/** The page object of a response: the JSON body of an Inertia visit, or the page script of a first visit. */\nexport function inertiaPageOf(response: TestResponse): InertiaPage {\n let page: unknown\n try {\n if (response.headers.has('X-Inertia')) page = JSON.parse(response.content)\n else {\n const match = /<script data-page=\"[^\"]*\" type=\"application\\/json\">([\\s\\S]*?)<\\/script>/.exec(response.content)\n page = match === null ? undefined : JSON.parse(match[1]!)\n }\n } catch {\n page = undefined\n }\n const valid =\n typeof page === 'object' && page !== null && ['component', 'props', 'url', 'version'].every((key) => Object.hasOwn(page as object, key))\n if (!valid) fail('Not a valid Inertia response.')\n return page as InertiaPage\n}\n\n/** Inertia's AssertableInertia: AssertableJson over the page props, plus the page component, url, version and flash. */\nexport class AssertableInertia extends AssertableJson {\n #page: InertiaPage | undefined\n #response: TestResponse | undefined\n\n static fromTestResponse(response: TestResponse): AssertableInertia {\n const page = inertiaPageOf(response)\n const instance = new AssertableInertia(page.props)\n instance.#page = page\n instance.#response = response\n return instance\n }\n\n /** Scopes are plain AssertableJson: the page-level methods only make sense at the root. */\n protected override newScope(props: unknown, path: string): AssertableJson {\n return new AssertableJson(props, path)\n }\n\n get page(): InertiaPage {\n if (this.#page === undefined) fail('This assertion is only available on the page root.')\n return this.#page\n }\n\n /** The component name; the page file must exist unless `shouldExist` is false (inertia.testing.ensure_pages_exist). */\n component(value?: string, shouldExist?: boolean): this {\n const actual = this.page.component\n assert(actual === value, 'Unexpected Inertia page component.', { actual, expected: value })\n const app = this.#app()\n const config = app?.bound(ConfigRepository) ? app.make(ConfigRepository) : undefined\n if (shouldExist === true || (shouldExist === undefined && config?.get<boolean>('inertia.testing.ensure_pages_exist', true) !== false)) {\n const paths = config?.get<string[]>('inertia.pages.paths', []) ?? []\n const extensions = config?.get<string[]>('inertia.pages.extensions', []) ?? []\n const exists = paths.some((path) => extensions.some((extension) => existsSync(join(path, `${value}.${extension}`))))\n if (!exists) fail(`Inertia page component file [${value}] does not exist.`)\n }\n return this\n }\n\n url(value: string): this {\n assert(this.page.url === value, 'Unexpected Inertia page url.', { actual: this.page.url, expected: value })\n return this\n }\n\n version(value: string): this {\n assert(this.page.version === value, 'Unexpected Inertia asset version.', { actual: this.page.version, expected: value })\n return this\n }\n\n /** The flash data has `key` (dot paths allowed), equal to `expected` when given. */\n hasFlash(key: string, ...expected: [] | [unknown]): this {\n AssertableInertia.assertFlashHas(this.page.flash ?? {}, key, ...expected)\n return this\n }\n\n missingFlash(key: string): this {\n AssertableInertia.assertFlashMissing(this.page.flash ?? {}, key)\n return this\n }\n\n static assertFlashHas(flash: Record<string, unknown>, key: string, ...expected: [] | [unknown]): void {\n assert(Arr.has(flash, key), `Inertia Flash Data is missing key [${key}].`)\n if (expected.length > 0) {\n const actual = Arr.get(flash, key)\n assert(equals(actual, expected[0]), `Inertia Flash Data [${key}] does not match expected value.`, { actual, expected: expected[0] })\n }\n }\n\n static assertFlashMissing(flash: Record<string, unknown>, key: string): void {\n assert(!Arr.has(flash, key), `Inertia Flash Data has unexpected key [${key}].`)\n }\n\n /**\n * Requests the page again as a partial reload (only/except) and checks it is the same page. Uses the test's\n * HTTP client, so the session and cookies carry over.\n */\n async reload(callback?: (page: AssertableInertia) => unknown, only?: string | string[], except?: string | string[]): Promise<this> {\n const client = this.#response?.context.client\n if (client === undefined) fail('reload() needs a response from the test HTTP client.')\n const headers: Record<string, string> = {\n 'X-Inertia': 'true',\n 'X-Requested-With': 'XMLHttpRequest',\n 'X-Inertia-Version': this.page.version,\n }\n const onlyList = only === undefined ? undefined : [only].flat().join(',')\n const exceptList = except === undefined ? undefined : [except].flat().join(',')\n if (onlyList !== undefined || exceptList !== undefined) headers['X-Inertia-Partial-Component'] = this.page.component\n if (onlyList !== undefined) headers['X-Inertia-Partial-Data'] = onlyList\n if (exceptList !== undefined) headers['X-Inertia-Partial-Except'] = exceptList\n const response = await client.request('GET', this.page.url, { headers })\n const reloaded = AssertableInertia.fromTestResponse(response)\n reloaded.component(this.page.component, false).url(this.page.url).version(this.page.version)\n await callback?.(reloaded)\n return this\n }\n\n reloadOnly(only: string | string[], callback?: (page: AssertableInertia) => unknown): Promise<this> {\n return this.reload(\n async (page) => {\n page.hasAll(typeof only === 'string' ? only.split(',') : only)\n await callback?.(page)\n },\n only,\n )\n }\n\n reloadExcept(except: string | string[], callback?: (page: AssertableInertia) => unknown): Promise<this> {\n return this.reload(\n async (page) => {\n page.missingAll(typeof except === 'string' ? except.split(',') : except)\n await callback?.(page)\n },\n undefined,\n except,\n )\n }\n\n /** Loads the deferred props of every group (or the given groups) in one partial reload. */\n loadDeferredProps(groupsOrCallback: string | string[] | ((page: AssertableInertia) => unknown), callback?: (page: AssertableInertia) => unknown): Promise<this> {\n const deferred = this.page.deferredProps ?? {}\n const groups = typeof groupsOrCallback === 'function' ? Object.keys(deferred) : [groupsOrCallback].flat()\n const props = groups.flatMap((group) => deferred[group] ?? [])\n return this.reloadOnly(props.join(','), typeof groupsOrCallback === 'function' ? groupsOrCallback : callback)\n }\n\n override toArray(): Record<string, unknown> {\n return {\n component: this.page.component,\n props: this.prop(),\n url: this.page.url,\n version: this.page.version,\n flash: this.page.flash ?? {},\n ...(this.page.encryptHistory === true ? { encryptHistory: true } : {}),\n ...(this.page.clearHistory === true ? { clearHistory: true } : {}),\n }\n }\n\n #app(): Application | undefined {\n return this.#response?.context.app\n }\n}\n","import { Arr } from '@orieljs/support'\nimport { assert, equals, fail, format } from '../assert'\n\ntype Json = unknown\ntype Scope<T extends AssertableJson> = (json: T) => unknown\n\n/** 'string', 'integer', 'double', 'number', 'boolean', 'array' (a list or an object, like PHP), 'object', 'null'. */\nfunction typeOf(value: unknown): string[] {\n if (value === null) return ['null']\n if (Array.isArray(value)) return ['array']\n switch (typeof value) {\n case 'string':\n return ['string']\n case 'boolean':\n return ['boolean']\n case 'number':\n return Number.isInteger(value) ? ['integer', 'number'] : ['double', 'float', 'number']\n case 'object':\n return ['array', 'object']\n default:\n return [typeof value]\n }\n}\n\n/**\n * Laravel's Illuminate\\Testing\\Fluent\\AssertableJson: fluent, scoped assertions over decoded JSON. Inside a scope\n * (has(key, callback), first(), each()) every property must be interacted with, or etc() must be called.\n */\nexport class AssertableJson {\n protected interactedKeys: string[] = []\n\n constructor(\n protected readonly props: Json,\n protected readonly path: string | undefined = undefined,\n ) {}\n\n static fromJson(json: Json): AssertableJson {\n return new AssertableJson(json)\n }\n\n /** A child scope of the same class (subclasses override to keep their extra state out of scopes). */\n protected newScope(props: Json, path: string): AssertableJson {\n return new AssertableJson(props, path)\n }\n\n protected dotPath(key = ''): string {\n if (this.path === undefined) return key\n return key === '' ? this.path : `${this.path}.${key}`\n }\n\n /** The value at `key` in this scope, or the whole scope. */\n protected prop(key?: string): Json {\n if (key !== undefined && this.hasOwnKey(key)) return (this.props as Record<string, unknown>)[key]\n return Arr.get(this.props, key)\n }\n\n /** A literal key of this scope wins over a dot path, like Laravel's Arr::get (keys such as 'items.0.name'). */\n private hasOwnKey(key: string): boolean {\n return typeof this.props === 'object' && this.props !== null && Object.hasOwn(this.props, key)\n }\n\n private exists(key: string): boolean {\n return this.hasOwnKey(key) || Arr.has(this.props, key)\n }\n\n protected interactsWith(key: string | number): void {\n const prop = this.hasOwnKey(String(key)) ? String(key) : String(key).split('.')[0]!\n if (!this.interactedKeys.includes(prop)) this.interactedKeys.push(prop)\n }\n\n /** Every property of the scope was checked (called when a scope ends). */\n interacted(): void {\n const props = this.prop()\n const keys = typeof props === 'object' && props !== null ? Object.keys(props) : []\n const unexpected = keys.filter((key) => !this.interactedKeys.includes(key))\n assert(\n unexpected.length === 0,\n this.path === undefined ? 'Unexpected properties were found on the root level.' : `Unexpected properties were found in scope [${this.path}].`,\n { actual: unexpected, expected: [] },\n )\n }\n\n /** Allow the properties this scope didn't check. */\n etc(): this {\n const props = this.prop()\n this.interactedKeys = typeof props === 'object' && props !== null ? Object.keys(props) : []\n return this\n }\n\n // Has ------------------------------------------------------------------------------------------------------\n\n /** has('key'), has('key', 3), has('key', json => …), has('key', 3, first => …), or has(3) for the root size. */\n has(key: string | number, length?: number | Scope<this>, callback?: Scope<this>): this {\n if (typeof key === 'number' && length === undefined) return this.count(key)\n const name = String(key)\n assert(this.exists(name), `Property [${this.dotPath(name)}] does not exist.`)\n this.interactsWith(name)\n if (callback !== undefined) {\n return this.has(name, (scope: this) => {\n if (typeof length === 'number') scope.count(length)\n scope.first(callback).etc()\n })\n }\n if (typeof length === 'function') return this.scope(name, length)\n if (typeof length === 'number') return this.count(name, length)\n return this\n }\n\n /** hasAll(['a', 'b']) or hasAll({ items: 3 }). */\n hasAll(keys: string | string[] | Record<string, number>): this {\n if (typeof keys === 'string' || Array.isArray(keys)) {\n for (const key of [keys].flat()) this.has(key)\n return this\n }\n for (const [key, length] of Object.entries(keys)) this.has(key, length)\n return this\n }\n\n hasAny(keys: string | string[]): this {\n const list = [keys].flat()\n const present = list.filter((key) => this.exists(key))\n assert(present.length > 0, `None of properties [${list.map((key) => this.dotPath(key)).join(', ')}] exist.`)\n for (const key of present) this.interactsWith(key)\n return this\n }\n\n missing(key: string): this {\n assert(!this.exists(key), `Property [${this.dotPath(key)}] was found while it was expected to be missing.`)\n return this\n }\n\n missingAll(keys: string | string[]): this {\n for (const key of [keys].flat()) this.missing(key)\n return this\n }\n\n /** count(3) checks this scope's size; count('items', 3) a property's. */\n count(key: string | number, length?: number): this {\n if (typeof key === 'number') {\n const size = sizeOf(this.prop())\n assert(size === key, this.path === undefined ? 'Root level does not have the expected size.' : `Property [${this.path}] does not have the expected size.`, { actual: size, expected: key })\n return this\n }\n this.has(key)\n const size = sizeOf(this.prop(key))\n assert(size === length, `Property [${this.dotPath(key)}] does not have the expected size.`, { actual: size, expected: length })\n return this\n }\n\n countBetween(key: string, min: number, max: number): this {\n this.has(key)\n const size = sizeOf(this.prop(key))\n assert(size >= min && size <= max, `Property [${this.dotPath(key)}] size is not between ${min} and ${max}.`, { actual: size })\n return this\n }\n\n // Matching -------------------------------------------------------------------------------------------------\n\n /** where('name', 'Ann'), or where('name', value => value.startsWith('A')). Objects compare ignoring key order. */\n where(key: string, expected: unknown): this {\n this.has(key)\n const actual = this.prop(key)\n if (typeof expected === 'function') {\n assert((expected as (value: unknown) => unknown)(actual), `Property [${this.dotPath(key)}] was marked as invalid using a closure.`)\n return this\n }\n const normalized = toPlain(expected)\n assert(equals(normalized, actual), `Property [${this.dotPath(key)}] does not match the expected value.`, { actual, expected: normalized })\n return this\n }\n\n whereNot(key: string, expected: unknown): this {\n this.has(key)\n const actual = this.prop(key)\n if (typeof expected === 'function') {\n assert(!(expected as (value: unknown) => unknown)(actual), `Property [${this.dotPath(key)}] was marked as invalid using a closure.`)\n return this\n }\n assert(!equals(toPlain(expected), actual), `Property [${this.dotPath(key)}] contains a value that should be missing: [${key}, ${format(expected)}]`)\n return this\n }\n\n whereNull(key: string): this {\n this.has(key)\n const actual = this.prop(key)\n assert(actual === null, `Property [${this.dotPath(key)}] should be null.`, { actual, expected: null })\n return this\n }\n\n whereNotNull(key: string): this {\n this.has(key)\n assert(this.prop(key) !== null, `Property [${this.dotPath(key)}] should not be null.`)\n return this\n }\n\n whereAll(bindings: Record<string, unknown>): this {\n for (const [key, value] of Object.entries(bindings)) this.where(key, value)\n return this\n }\n\n /** whereType('id', 'integer'), whereType('name', 'string|null'), whereType('tags', ['array', 'null']). */\n whereType(key: string, expected: string | string[]): this {\n this.has(key)\n const types = typeof expected === 'string' ? expected.split('|') : expected\n const actual = typeOf(this.prop(key))\n assert(\n types.some((type) => actual.includes(type)),\n `Property [${this.dotPath(key)}] is not of expected type [${types.join('|')}].`,\n { actual: actual[0], expected: types.join('|') },\n )\n return this\n }\n\n whereAllType(bindings: Record<string, string | string[]>): this {\n for (const [key, type] of Object.entries(bindings)) this.whereType(key, type)\n return this\n }\n\n /** The list contains every expected value (or one passing the callback); a string contains the substring. */\n whereContains(key: string, expected: unknown): this {\n this.has(key)\n const actual = this.prop(key)\n if (typeof actual === 'string') {\n assert(actual.includes(String(expected)), `Property [${this.dotPath(key)}] does not contain [${format(expected)}].`)\n return this\n }\n const values = typeof actual === 'object' && actual !== null ? Object.values(actual) : [actual]\n const wanted = Array.isArray(expected) ? expected : [expected]\n const missing = wanted.filter((item) =>\n typeof item === 'function' ? !values.some((value) => (item as (value: unknown) => unknown)(value)) : !values.some((value) => equals(toPlain(item), value)),\n )\n assert(missing.length === 0, `Property [${this.dotPath(key)}] does not contain [${missing.map(format).join(', ')}].`, { actual })\n return this\n }\n\n // Scoping --------------------------------------------------------------------------------------------------\n\n protected scope(key: string, callback: Scope<this>): this {\n const props = this.prop(key)\n const path = this.dotPath(key)\n assert(typeof props === 'object' && props !== null, `Property [${path}] is not scopeable.`)\n const scope = this.newScope(props, path) as this\n callback(scope)\n scope.interacted()\n return this\n }\n\n first(callback: Scope<this>): this {\n const props = this.prop()\n const keys = typeof props === 'object' && props !== null ? Object.keys(props) : []\n if (keys.length === 0) {\n fail(this.path === undefined ? 'Cannot scope directly onto the first element of the root level because it is empty.' : `Cannot scope directly onto the first element of property [${this.path}] because it is empty.`)\n }\n this.interactsWith(keys[0]!)\n return this.scope(keys[0]!, callback)\n }\n\n each(callback: Scope<this>): this {\n const props = this.prop()\n const keys = typeof props === 'object' && props !== null ? Object.keys(props) : []\n if (keys.length === 0) {\n fail(this.path === undefined ? 'Cannot scope directly onto each element of the root level because it is empty.' : `Cannot scope directly onto each element of property [${this.path}] because it is empty.`)\n }\n for (const key of keys) {\n this.interactsWith(key)\n this.scope(key, callback)\n }\n return this\n }\n\n // Helpers --------------------------------------------------------------------------------------------------\n\n when(condition: unknown, callback: (json: this) => unknown, otherwise?: (json: this) => unknown): this {\n if (condition) callback(this)\n else otherwise?.(this)\n return this\n }\n\n dump(key?: string): this {\n console.log(format(this.prop(key)))\n return this\n }\n\n toArray(): Json {\n return this.prop()\n }\n}\n\nfunction sizeOf(value: unknown): number {\n if (Array.isArray(value)) return value.length\n if (typeof value === 'object' && value !== null) return Object.keys(value).length\n if (typeof value === 'string') return value.length\n return 0\n}\n\n/** Expected values go through JSON like the response did: models, collections and dates compare as their JSON. */\nfunction toPlain(value: unknown): unknown {\n return value === undefined ? undefined : (JSON.parse(JSON.stringify(value)) as unknown)\n}\n","import { createHmac } from 'node:crypto'\nimport type { Encrypter } from '@orieljs/contracts'\n\n/** Laravel's CookieValuePrefix: hmac_sha1(name + 'v2', key) + '|' (41 characters), as Auth's EncryptCookies writes it. */\nexport function cookiePrefix(name: string, key: Uint8Array): string {\n return `${createHmac('sha1', key).update(`${name}v2`).digest('hex')}|`\n}\n\n/** What EncryptCookies puts in a browser cookie: encrypt(prefix + value, serialize: false). */\nexport function encryptCookie(encrypter: Encrypter, name: string, value: string): string {\n return encrypter.encrypt(cookiePrefix(name, encrypter.getKey()) + value, false)\n}\n\n/** The plain value of an encrypted cookie, or undefined when it doesn't decrypt or its prefix is wrong. */\nexport function decryptCookie(encrypter: Encrypter, name: string, value: string): string | undefined {\n try {\n const plain = encrypter.decrypt<string>(value, false)\n const prefix = cookiePrefix(name, encrypter.getKey())\n return plain.startsWith(prefix) ? plain.slice(prefix.length) : undefined\n } catch {\n return undefined\n }\n}\n\nexport interface ResponseCookie {\n name: string\n /** URI-decoded, still encrypted if the app encrypted it. */\n value: string\n path?: string\n domain?: string\n maxAge?: number\n expires?: Date\n httpOnly: boolean\n secure: boolean\n sameSite?: string\n}\n\nconst decode = (text: string) => {\n try {\n return decodeURIComponent(text)\n } catch {\n return text\n }\n}\n\nexport function parseSetCookie(header: string): ResponseCookie {\n const [pair = '', ...attributes] = header.split(';')\n const eq = pair.indexOf('=')\n const cookie: ResponseCookie = {\n name: decode(pair.slice(0, eq).trim()),\n value: decode(pair.slice(eq + 1).trim().replace(/^\"(.*)\"$/, '$1')),\n httpOnly: false,\n secure: false,\n }\n for (const attribute of attributes) {\n const at = attribute.indexOf('=')\n const key = (at === -1 ? attribute : attribute.slice(0, at)).trim().toLowerCase()\n const value = at === -1 ? '' : attribute.slice(at + 1).trim()\n if (key === 'path') cookie.path = value\n else if (key === 'domain') cookie.domain = value\n else if (key === 'max-age') cookie.maxAge = Number(value)\n else if (key === 'expires') cookie.expires = new Date(value)\n else if (key === 'httponly') cookie.httpOnly = true\n else if (key === 'secure') cookie.secure = true\n else if (key === 'samesite') cookie.sameSite = value\n }\n return cookie\n}\n\n/** Max-Age <= 0 or an Expires in the past: the server is deleting the cookie. */\nexport function isExpired(cookie: ResponseCookie, now = Date.now()): boolean {\n if (cookie.maxAge !== undefined && !Number.isNaN(cookie.maxAge)) return cookie.maxAge <= 0\n return cookie.expires !== undefined && cookie.expires.getTime() <= now\n}\n\nexport function responseCookies(response: Response): ResponseCookie[] {\n return response.headers.getSetCookie().map(parseSetCookie)\n}\n\nexport function cookieHeader(cookies: Map<string, string>): string {\n return [...cookies].map(([name, value]) => `${encodeURIComponent(name)}=${encodeURIComponent(value)}`).join('; ')\n}\n","import type { AuthFactory, Authenticatable, ExceptionHandler, View, ViewFactory } from '@orieljs/contracts'\n\n/** Forwards every property to `target`, with methods bound to it; `overrides` replace single members. */\nfunction forward<T extends object>(target: T, overrides: Partial<Record<PropertyKey, unknown>>, before?: () => void): T {\n return new Proxy(target, {\n get(object, property) {\n before?.()\n if (Object.hasOwn(overrides, property)) return overrides[property]\n const value: unknown = Reflect.get(object, property, object)\n return typeof value === 'function' ? (value as (...args: unknown[]) => unknown).bind(object) : value\n },\n })\n}\n\n/** The request scope's ViewFactory: records every view made, so TestResponse can assert on it (assertViewIs/Has). */\nexport function recordingViewFactory(factory: ViewFactory, views: View[]): ViewFactory {\n return forward(factory, {\n make(name: string, data?: Record<string, unknown>): View {\n const view = factory.make(name, data)\n views.push(view)\n return view\n },\n })\n}\n\n/**\n * The request scope's ExceptionHandler: records the error it renders (for failure messages and\n * withoutExceptionHandling()), then renders it as usual.\n */\nexport function recordingExceptionHandler(handler: ExceptionHandler, record: (error: unknown) => void): ExceptionHandler {\n return forward(handler, {\n async render(request: unknown, error: unknown): Promise<Response> {\n record(error)\n return handler.render(request, error)\n },\n })\n}\n\n/**\n * The request scope's AuthFactory for actingAs(): the users are put on the scope's guards the first time\n * anything touches auth. That is after the kernel bound HttpRequest, so request.user() sees them too.\n * `onApply` runs when that happens, so the client knows to read the guards back after the request.\n */\nexport function actingAsAuthFactory(\n auth: AuthFactory,\n users: Map<string | undefined, Authenticatable>,\n defaultGuard: string | undefined,\n onApply?: () => void,\n): AuthFactory {\n let applied = false\n const apply = () => {\n if (applied) return\n applied = true\n if (defaultGuard !== undefined) auth.shouldUse(defaultGuard)\n for (const [guard, user] of users) auth.guard(guard).setUser(user)\n onApply?.()\n }\n return forward(auth, {}, apply)\n}\n","import {\n DatabaseManager,\n type Application,\n type ServiceProvider,\n type ServiceProviderClass,\n} from '@orieljs/contracts'\nimport { Container } from '@orieljs/container'\nimport { Application as FoundationApplication } from '@orieljs/foundation'\nimport { applyEnvironment, TESTING_ENVIRONMENT } from '../environment'\n\n/** The test runner's per-test hooks. Pass Vitest's: `{ beforeEach, afterEach }`. */\nexport interface TestHooks {\n beforeEach(fn: () => unknown): void\n afterEach(fn: () => unknown): void\n}\n\n/** A Laravel-style trait (RefreshDatabase, …): setUp runs after the app boots; clean-up goes in beforeApplicationDestroyed. */\nexport interface TestTrait {\n setUp(test: InteractsWithApplication): void | Promise<void>\n}\n\nexport interface BootOptions {\n hooks?: TestHooks\n /** Extra traits for this file, like `use RefreshDatabase;`. */\n uses?: TestTrait[]\n}\n\ntype Callback = () => void | Promise<void>\n\nconst globalHooks = (): TestHooks | undefined => {\n const g = globalThis as { beforeEach?: TestHooks['beforeEach']; afterEach?: TestHooks['afterEach'] }\n return typeof g.beforeEach === 'function' && typeof g.afterEach === 'function'\n ? { beforeEach: g.beforeEach, afterEach: g.afterEach }\n : undefined\n}\n\n/**\n * Laravel's TestCase lifecycle: a brand-new application for every test (createApplication() → boot → traits),\n * and a full teardown after it, so no state survives from one test to the next.\n */\nexport abstract class InteractsWithApplication {\n /** Set once in tests/TestCase.ts: `static override hooks = { beforeEach, afterEach }` (from vitest). */\n static hooks?: TestHooks\n\n /** Traits this test case uses (Laravel's `use RefreshDatabase;`). */\n readonly uses: TestTrait[] = []\n\n private application: Application | undefined\n private extraTraits: TestTrait[] = []\n private destroying: Callback[] = []\n\n /**\n * Creates the test case and registers its setUp/tearDown as beforeEach/afterEach hooks.\n * `const t = TestCase.boot()` at the top of a test file (or inside a describe block).\n */\n static boot<T extends InteractsWithApplication>(this: (new () => T) & { hooks?: TestHooks }, options: BootOptions = {}): T {\n const hooks = options.hooks ?? this.hooks ?? globalHooks()\n if (hooks === undefined) {\n throw new Error(\n 'TestCase.boot() needs the test runner hooks: set `static override hooks = { beforeEach, afterEach }` ' +\n '(imported from vitest) in tests/TestCase.ts, or pass { hooks }.',\n )\n }\n const test = new this()\n test.extraTraits = [...(options.uses ?? [])]\n hooks.beforeEach(() => test.setUp())\n hooks.afterEach(() => test.tearDown())\n return test\n }\n\n /** The current test's application. */\n get app(): Application {\n if (this.application === undefined) {\n throw new Error('There is no application outside a test: use it inside test() (after TestCase.boot()).')\n }\n return this.application\n }\n\n /**\n * A fresh application for one test. tests/TestCase.ts overrides this to call bootstrap/app's factory.\n * The default builds one at basePath() with providers(), for package tests with no skeleton.\n */\n createApplication(): Promise<Application> {\n return FoundationApplication.configure({ basePath: this.basePath() }).withProviders(this.providers()).create()\n }\n\n /** Used by the default createApplication(). */\n protected basePath(): string {\n return process.cwd()\n }\n\n /** Used by the default createApplication(). */\n protected providers(): Array<ServiceProvider | ServiceProviderClass> {\n return []\n }\n\n /** The variables applied (unless already set) before each application is created. */\n protected environment(): Record<string, string> {\n return { ...TESTING_ENVIRONMENT }\n }\n\n /** Adjust the fresh app before it boots, e.g. `app.make(ConfigRepository).set('mail.default', 'array')`. */\n protected defineEnvironment(_app: Application): void | Promise<void> {}\n\n async setUp(): Promise<void> {\n applyEnvironment(this.environment())\n const app = await this.createApplication()\n this.application = app\n app.setRunningInConsole(true)\n await this.defineEnvironment(app)\n await app.boot()\n for (const trait of [...this.uses, ...this.extraTraits]) await trait.setUp(this)\n }\n\n async tearDown(): Promise<void> {\n const app = this.application\n if (app === undefined) return\n try {\n for (const callback of this.destroying) await callback()\n if (app.resolved(DatabaseManager)) await disconnectAll(app.make(DatabaseManager))\n } finally {\n this.destroying = []\n this.application = undefined\n const global: unknown = Container.getInstance()\n if (global === app) Container.setInstance(undefined)\n }\n }\n\n /** Runs in tearDown(), before the application is thrown away (in registration order). */\n beforeApplicationDestroyed(callback: Callback): void {\n this.destroying.push(callback)\n }\n}\n\n/** Closes every database connection the test opened (Database's disconnectAll() when present, else the default). */\nasync function disconnectAll(db: DatabaseManager): Promise<void> {\n const manager = db as DatabaseManager & { disconnectAll?(): Promise<void> }\n if (typeof manager.disconnectAll === 'function') await manager.disconnectAll()\n else await manager.disconnect()\n}\n","import { PendingCommand } from '../Console/PendingCommand'\nimport { InteractsWithDatabase } from './InteractsWithDatabase'\n\n/** Laravel's InteractsWithConsole: `await t.artisan('cmd', { user: 1, '--queue': 'high' }).assertExitCode(0)`. */\nexport abstract class InteractsWithConsole extends InteractsWithDatabase {\n /** The command runs when the returned PendingCommand is awaited; without `await` it never runs. */\n artisan(command: string, parameters: Record<string, unknown> = {}): PendingCommand {\n return new PendingCommand(this.app, command, parameters)\n }\n}\n","import { InteractsWithConsole } from './Concerns/InteractsWithConsole'\n\n/**\n * Laravel's TestCase. Extend it in tests/TestCase.ts (override createApplication() and set `static hooks`),\n * then in each file: `const t = TestCase.boot()`, or `TestCase.boot({ uses: [RefreshDatabase] })`.\n */\nexport abstract class TestCase extends InteractsWithConsole {}\n","import type { Class, Token } from '@orieljs/contracts'\nimport { currentContainer } from '@orieljs/container'\nimport { facade } from '@orieljs/support'\nimport { equals } from '../assert'\n\n/** What an assertion targets: a class (exact constructor), or a name (a string event, a class name or a registry name). */\nexport type Target<T = unknown> = Class<T> | string\n\n/** A count, or a filter over the recorded items. */\nexport type CountOrFilter<A extends unknown[]> = number | ((...args: A) => boolean)\n\n/** Swaps the fake in through the facade machinery (`facade(token).swap(fake)`: an instance on the current container). */\nexport function install<T extends object, F extends T>(token: Token<T>, fake: F): F {\n facade(token).swap(fake)\n return fake\n}\n\n/** The instance currently bound for `token`, if any (the thing a fake wraps). */\nexport function bound<T>(token: Token<T>): T | undefined {\n const container = currentContainer()\n return container !== undefined && container.bound(token) ? container.make(token) : undefined\n}\n\nexport function nameOf(target: Target | object): string {\n if (typeof target === 'string') return target\n if (typeof target === 'function') return target.name\n return (target as object).constructor.name\n}\n\n/** A recorded object (or string event) matches a target: same constructor, or the same (class) name. */\nexport function matches(item: unknown, target: Target): boolean {\n if (typeof target === 'string') return typeof item === 'string' ? item === target : typeof item === 'object' && item !== null && item.constructor.name === target\n return typeof item === 'object' && item !== null && item.constructor === target\n}\n\nexport function matchesAny(item: unknown, targets: Target[]): boolean {\n return targets.some((target) => matches(item, target))\n}\n\n/** A class or instance in an expected list: classes match by constructor, instances by constructor and equal fields. */\nexport function sameJob(actual: object, expected: Target | object): boolean {\n if (typeof expected === 'function' || typeof expected === 'string') return matches(actual, expected as Target)\n return actual.constructor === expected.constructor && equals({ ...actual }, { ...expected })\n}\n\n/** Bus's ShouldQueue marker (the Queueable base class sets it on its prototype); the same Symbol.for key as 06. */\nexport const SHOULD_QUEUE = Symbol.for('oriel:bus.shouldQueue')\nconst QUEUE_OPTIONS = ['connection', 'queue', 'delay', 'tries', 'backoff', 'timeout'] as const\n\ntype Members = Record<PropertyKey, unknown>\n\n/**\n * A verbatim copy of Bus's isQueueable() (06-queue-bus.md; Testing can't import Bus). The rule is read on the\n * instance: the ShouldQueue marker, a value for any ShouldQueue option, or uniqueId()/retryUntil().\n */\nexport function isQueueable(job: unknown): boolean {\n if (typeof job !== 'object' || job === null) return false\n const members = job as Members\n if (members[SHOULD_QUEUE] === true) return true\n if (QUEUE_OPTIONS.some((option) => members[option] !== undefined)) return true\n return typeof members.uniqueId === 'function' || typeof members.retryUntil === 'function'\n}\n","import { EventDispatcher, type Class, type Listener } from '@orieljs/contracts'\nimport { assert } from '../assert'\nimport { bound, install, matchesAny, nameOf, type CountOrFilter, type Target } from './support'\n\n/** One dispatch: the event object (or name) and its payload. */\nexport interface DispatchedEvent {\n event: object | string\n payload: unknown[]\n}\n\ntype EventFilter<E> = (event: E, payload: unknown[]) => boolean\n\n/**\n * Laravel's Event::fake(): records dispatched events instead of running listeners. With a list, only those\n * events are faked and everything else reaches the original dispatcher (so model events keep working).\n */\nexport class EventFake implements EventDispatcher {\n readonly events: DispatchedEvent[] = []\n\n constructor(\n readonly dispatcher: EventDispatcher | undefined,\n private readonly eventsToFake: Target[] = [],\n private eventsToDispatch: Target[] = [],\n ) {}\n\n /** Installs the fake (on the current container) and returns it: `const events = EventFake.fake([OrderShipped])`. */\n static fake(eventsToFake: Target | Target[] = []): EventFake {\n return install(EventDispatcher, new EventFake(EventFake.original(), [eventsToFake].flat()))\n }\n\n /** Fakes every event except these. */\n static fakeExcept(eventsToDispatch: Target | Target[]): EventFake {\n return install(EventDispatcher, new EventFake(EventFake.original(), [], [eventsToDispatch].flat()))\n }\n\n private static original(): EventDispatcher | undefined {\n const current = bound(EventDispatcher)\n return current instanceof EventFake ? current.dispatcher : current\n }\n\n except(events: Target | Target[]): this {\n this.eventsToDispatch = [...this.eventsToDispatch, ...[events].flat()]\n return this\n }\n\n // EventDispatcher -----------------------------------------------------------------------------------------\n\n listen<E>(events: Class<E> | string | Array<Class<E> | string>, listener: Listener<E>): void {\n this.dispatcher?.listen(events, listener)\n }\n\n hasListeners(event: Class<unknown> | string): boolean {\n return this.dispatcher?.hasListeners(event) ?? false\n }\n\n async dispatch(event: object | string, payload: unknown[] = []): Promise<unknown[]> {\n if (this.shouldFake(event)) {\n this.events.push({ event, payload })\n return []\n }\n return this.dispatcher?.dispatch(event, payload) ?? []\n }\n\n /** Faked events return undefined (never false), so halting model events such as `saving` still proceed. */\n async until(event: object | string, payload: unknown[] = []): Promise<unknown> {\n if (this.shouldFake(event)) {\n this.events.push({ event, payload })\n return undefined\n }\n return this.dispatcher?.until(event, payload)\n }\n\n subscribe(subscriber: Class<{ subscribe(events: EventDispatcher): void }>): void {\n this.dispatcher?.subscribe(subscriber)\n }\n\n forget(event: Class<unknown> | string): void {\n this.dispatcher?.forget(event)\n }\n\n // Assertions ------------------------------------------------------------------------------------------------\n\n /** Dispatched at least once; a number asserts the exact count; a function filters (event, payload). */\n assertDispatched<E>(event: Class<E> | string, callback?: CountOrFilter<[E, unknown[]]>): void {\n if (typeof callback === 'number') return this.assertDispatchedTimes(event, callback)\n assert(this.dispatched(event, callback).length > 0, `The expected [${nameOf(event)}] event was not dispatched.`)\n }\n\n assertDispatchedTimes<E>(event: Class<E> | string, times = 1): void {\n const count = this.dispatched(event).length\n assert(count === times, `The expected [${nameOf(event)}] event was dispatched ${count} times instead of ${times} times.`, { actual: count, expected: times })\n }\n\n assertNotDispatched<E>(event: Class<E> | string, callback?: EventFilter<E>): void {\n assert(this.dispatched(event, callback).length === 0, `The unexpected [${nameOf(event)}] event was dispatched.`)\n }\n\n assertNothingDispatched(): void {\n const names = this.events.map(({ event }) => nameOf(event))\n assert(names.length === 0, `${names.length} unexpected events were dispatched:\\n\\n- ${names.join('\\n- ')}`)\n }\n\n /** The original dispatcher has a listener for the event. */\n assertListening(event: Class<unknown> | string): void {\n assert(this.hasListeners(event), `Event [${nameOf(event)}] does not have any listeners.`)\n }\n\n /** The recorded events (objects, or names for string events) that match. */\n dispatched<E>(event: Class<E> | string, callback?: EventFilter<E>): E[] {\n return this.events\n .filter((record) => matchesAny(record.event, [event]) && (callback === undefined || callback(record.event as E, record.payload)))\n .map((record) => record.event as E)\n }\n\n hasDispatched(event: Class<unknown> | string): boolean {\n return this.dispatched(event).length > 0\n }\n\n private shouldFake(event: object | string): boolean {\n if (matchesAny(event, this.eventsToDispatch)) return false\n return this.eventsToFake.length === 0 || matchesAny(event, this.eventsToFake)\n }\n}\n","import { BusDispatcher, type Batch, type Job, type PendingBatch, type PendingBatchOptions, type PendingChain } from '@orieljs/contracts'\nimport { randomUUID } from 'node:crypto'\nimport { assert, fail } from '../assert'\nimport { bound, install, matchesAny, nameOf, sameJob, type CountOrFilter, type Target } from './support'\n\ntype Filter<J> = (job: J) => boolean\n\n/** What a faked Bus.batch([...]).dispatch() recorded (Laravel's PendingBatchFake): the options Bus would store, plus the jobs. */\nexport interface BatchRecord extends PendingBatchOptions {\n readonly id: string\n readonly jobs: Job[]\n}\n\nclass FakeBatch implements Batch {\n constructor(private readonly record: BatchRecord) {}\n get id(): string { return this.record.id }\n get name(): string { return this.record.name }\n get totalJobs(): number { return this.record.jobs.length }\n get pendingJobs(): number { return this.record.jobs.length }\n readonly failedJobs = 0\n private isCancelled = false\n progress(): number { return 0 }\n finished(): boolean { return false }\n cancelled(): boolean { return this.isCancelled }\n async cancel(): Promise<void> { this.isCancelled = true }\n}\n\n/**\n * Laravel's Bus::fake(): records dispatch/dispatchSync/dispatchAfterResponse, chains and batches instead of\n * running or queueing them. With a list, only those jobs are faked; others go to the original dispatcher.\n */\nexport class BusFake implements BusDispatcher {\n readonly commands: Job[] = []\n readonly commandsSync: Job[] = []\n readonly commandsAfterResponse: Job[] = []\n readonly batches: BatchRecord[] = []\n /** The rest of the chain, by the first job (Bus.chain([a, b, c]) records a with [b, c]). */\n readonly chains = new Map<Job, Job[]>()\n\n constructor(\n readonly dispatcher: BusDispatcher | undefined,\n private readonly jobsToFake: Target[] = [],\n private jobsToDispatch: Target[] = [],\n ) {}\n\n static fake(jobsToFake: Target | Target[] = []): BusFake {\n return install(BusDispatcher, new BusFake(BusFake.original(), [jobsToFake].flat()))\n }\n\n static fakeExcept(jobsToDispatch: Target | Target[]): BusFake {\n return install(BusDispatcher, new BusFake(BusFake.original(), [], [jobsToDispatch].flat()))\n }\n\n private static original(): BusDispatcher | undefined {\n const current = bound(BusDispatcher)\n return current instanceof BusFake ? current.dispatcher : current\n }\n\n except(jobs: Target | Target[]): this {\n this.jobsToDispatch = [...this.jobsToDispatch, ...[jobs].flat()]\n return this\n }\n\n // BusDispatcher ----------------------------------------------------------------------------------------\n\n async dispatch(job: Job): Promise<unknown> {\n if (!this.shouldFake(job)) return this.real().dispatch(job)\n this.commands.push(job)\n return undefined\n }\n\n async dispatchSync(job: Job): Promise<unknown> {\n if (!this.shouldFake(job)) return this.real().dispatchSync(job)\n this.commandsSync.push(job)\n return undefined\n }\n\n dispatchAfterResponse(job: Job): void {\n if (!this.shouldFake(job)) return this.real().dispatchAfterResponse(job)\n this.commandsAfterResponse.push(job)\n }\n\n /**\n * Bus's terminating callback flushes whatever BusDispatcher is bound, which is this fake: forward to the real\n * dispatcher so the after-response jobs it didn't fake still run (Laravel runs them). Faked ones never run.\n */\n async flushAfterResponse(): Promise<void> {\n await (this.dispatcher as { flushAfterResponse?(): Promise<void> } | undefined)?.flushAfterResponse?.()\n }\n\n chain(jobs: Job[]): PendingChain {\n const options: { connection?: string; queue?: string } = {}\n const pending: PendingChain = {\n onConnection: (connection) => {\n options.connection = connection\n return pending\n },\n onQueue: (queue) => {\n options.queue = queue\n return pending\n },\n catch: () => pending,\n dispatch: async () => {\n const [first, ...rest] = jobs\n if (first === undefined) return\n if (!this.shouldFake(first)) return this.real().chain(jobs).dispatch()\n if (options.connection !== undefined) first.connection = options.connection\n if (options.queue !== undefined) first.queue = options.queue\n this.commands.push(first)\n this.chains.set(first, rest)\n },\n }\n return pending\n }\n\n batch(jobs: Job[]): PendingBatch {\n const record: BatchRecord = { id: randomUUID(), jobs, name: '', allowFailures: false, then: [], catch: [], finally: [] }\n const batches = this.batches\n const pending: PendingBatch = {\n name(name) { record.name = name; return pending },\n onConnection(connection) { record.connection = connection; return pending },\n onQueue(queue) { record.queue = queue; return pending },\n allowFailures(allow = true) { record.allowFailures = allow; return pending },\n then(job) { record.then.push(job); return pending },\n catch(job) { record.catch.push(job); return pending },\n finally(job) { record.finally.push(job); return pending },\n async dispatch() {\n batches.push(record)\n return new FakeBatch(record)\n },\n }\n return pending\n }\n\n async findBatch(id: string): Promise<Batch | undefined> {\n const record = this.batches.find((batch) => batch.id === id)\n return record === undefined ? undefined : new FakeBatch(record)\n }\n\n // Assertions ---------------------------------------------------------------------------------------------\n\n /** Dispatched in any way (dispatch, dispatchSync or dispatchAfterResponse); a number asserts the count. */\n assertDispatched<J extends Job>(job: Target<J>, callback?: CountOrFilter<[J]>): void {\n if (typeof callback === 'number') return this.assertDispatchedTimes(job, callback)\n const count = this.dispatched(job, callback).length + this.dispatchedSync(job, callback).length + this.dispatchedAfterResponse(job, callback).length\n assert(count > 0, `The expected [${nameOf(job)}] job was not dispatched.`)\n }\n\n assertDispatchedTimes<J extends Job>(job: Target<J>, times = 1): void {\n const count = this.dispatched(job).length + this.dispatchedSync(job).length + this.dispatchedAfterResponse(job).length\n assert(count === times, `The expected [${nameOf(job)}] job was pushed ${count} times instead of ${times} times.`, { actual: count, expected: times })\n }\n\n assertNotDispatched<J extends Job>(job: Target<J>, callback?: Filter<J>): void {\n const count = this.dispatched(job, callback).length + this.dispatchedSync(job, callback).length + this.dispatchedAfterResponse(job, callback).length\n assert(count === 0, `The unexpected [${nameOf(job)}] job was dispatched.`)\n }\n\n assertNothingDispatched(): void {\n const all = [...this.commands, ...this.commandsSync, ...this.commandsAfterResponse].map((job) => nameOf(job))\n assert(all.length === 0, `The following jobs were dispatched unexpectedly:\\n\\n- ${all.join('\\n- ')}`)\n }\n\n assertDispatchedSync<J extends Job>(job: Target<J>, callback?: CountOrFilter<[J]>): void {\n if (typeof callback === 'number') {\n const count = this.dispatchedSync(job).length\n assert(count === callback, `The expected [${nameOf(job)}] job was synchronously pushed ${count} times instead of ${callback} times.`, { actual: count, expected: callback })\n return\n }\n assert(this.dispatchedSync(job, callback).length > 0, `The expected [${nameOf(job)}] job was not dispatched synchronously.`)\n }\n\n assertNotDispatchedSync<J extends Job>(job: Target<J>, callback?: Filter<J>): void {\n assert(this.dispatchedSync(job, callback).length === 0, `The unexpected [${nameOf(job)}] job was dispatched synchronously.`)\n }\n\n assertDispatchedAfterResponse<J extends Job>(job: Target<J>, callback?: CountOrFilter<[J]>): void {\n if (typeof callback === 'number') {\n const count = this.dispatchedAfterResponse(job).length\n assert(count === callback, `The expected [${nameOf(job)}] job was pushed ${count} times instead of ${callback} times.`, { actual: count, expected: callback })\n return\n }\n assert(this.dispatchedAfterResponse(job, callback).length > 0, `The expected [${nameOf(job)}] job was not dispatched after sending the response.`)\n }\n\n assertNotDispatchedAfterResponse<J extends Job>(job: Target<J>, callback?: Filter<J>): void {\n assert(this.dispatchedAfterResponse(job, callback).length === 0, `The unexpected [${nameOf(job)}] job was dispatched after sending the response.`)\n }\n\n /** `[First, Second, new Third(1)]`: a dispatched First whose chain is exactly the rest (classes or equal instances). */\n assertChained(expectedChain: Array<Target | Job>): void {\n const [first, ...rest] = expectedChain\n if (first === undefined) fail('assertChained() needs at least one job.')\n const candidates = this.commands.filter((job) => sameJob(job, first as Target | Job))\n assert(candidates.length > 0, `The expected [${nameOf(first)}] job was not dispatched.`)\n const found = candidates.some((job) => {\n const chain = this.chains.get(job) ?? []\n return chain.length === rest.length && chain.every((link, index) => sameJob(link, rest[index] as Target | Job))\n })\n assert(found, `The expected chain [${expectedChain.map(nameOf).join(', ')}] was not dispatched.`)\n }\n\n assertDispatchedWithoutChain<J extends Job>(job: Target<J>, callback?: Filter<J>): void {\n const jobs = this.dispatched(job, callback)\n assert(jobs.length > 0, `The expected [${nameOf(job)}] job was not dispatched.`)\n assert(jobs.some((dispatched) => (this.chains.get(dispatched) ?? []).length === 0), `The expected [${nameOf(job)}] job was dispatched with a chain.`)\n }\n\n /** A batch was dispatched that passes the check. */\n assertBatched(callback: (batch: BatchRecord) => boolean): void {\n assert(this.batches.some(callback), 'The expected batch was not dispatched.')\n }\n\n assertBatchCount(count: number): void {\n assert(this.batches.length === count, `${this.batches.length} batches were dispatched instead of ${count}.`, { actual: this.batches.length, expected: count })\n }\n\n assertNothingBatched(): void {\n assert(this.batches.length === 0, 'Batched jobs were dispatched unexpectedly.')\n }\n\n dispatched<J extends Job>(job: Target<J>, callback?: Filter<J>): J[] {\n return filter(this.commands, job, callback)\n }\n\n dispatchedSync<J extends Job>(job: Target<J>, callback?: Filter<J>): J[] {\n return filter(this.commandsSync, job, callback)\n }\n\n dispatchedAfterResponse<J extends Job>(job: Target<J>, callback?: Filter<J>): J[] {\n return filter(this.commandsAfterResponse, job, callback)\n }\n\n hasDispatched<J extends Job>(job: Target<J>): boolean {\n return this.dispatched(job).length > 0\n }\n\n private shouldFake(job: Job): boolean {\n if (matchesAny(job, this.jobsToDispatch)) return false\n return this.jobsToFake.length === 0 || matchesAny(job, this.jobsToFake)\n }\n\n private real(): BusDispatcher {\n if (this.dispatcher === undefined) fail('Bus.fake() was given jobs to fake, but there is no real BusDispatcher for the others.')\n return this.dispatcher\n }\n}\n\nfunction filter<J>(jobs: Job[], target: Target<J>, callback?: Filter<J>): J[] {\n return (jobs.filter((job) => matchesAny(job, [target as Target])) as J[]).filter((job) => callback === undefined || callback(job))\n}\n","import { randomUUID } from 'node:crypto'\nimport { QueueManager, type Job, type Queue, type QueueJob, type QueuePayload } from '@orieljs/contracts'\nimport { assert, fail } from '../assert'\nimport { bound, install, matchesAny, nameOf, sameJob, type CountOrFilter, type Target } from './support'\n\n/** The Queue/Bus protocol key where PendingChain stores the rest of a chain on the first job (06-queue-bus.md). */\nconst CHAIN = Symbol.for('oriel:queue.chain')\n\n/** One push: the job (or raw payload), where it went, and when. */\nexport interface PushedJob {\n job: Job | QueuePayload\n raw: boolean\n connection: string | undefined\n queue: string | undefined\n delay: number | undefined\n}\n\ntype Filter<J> = (job: J, queue: string | undefined, connection: string | undefined) => boolean\n\n/**\n * Laravel's Queue::fake(): records push/later/pushRaw (on any connection) instead of queueing. Jobs that Bus\n * dispatches to a queue land here too, because Bus resolves QueueManager when it queues.\n */\nexport class QueueFake implements QueueManager {\n readonly jobs: PushedJob[] = []\n\n constructor(\n readonly manager: QueueManager | undefined,\n private readonly jobsToFake: Target[] = [],\n private jobsToPush: Target[] = [],\n ) {}\n\n static fake(jobsToFake: Target | Target[] = []): QueueFake {\n return install(QueueManager, new QueueFake(QueueFake.original(), [jobsToFake].flat()))\n }\n\n static fakeExcept(jobsToPush: Target | Target[]): QueueFake {\n return install(QueueManager, new QueueFake(QueueFake.original(), [], [jobsToPush].flat()))\n }\n\n private static original(): QueueManager | undefined {\n const current = bound(QueueManager)\n return current instanceof QueueFake ? current.manager : current\n }\n\n except(jobs: Target | Target[]): this {\n this.jobsToPush = [...this.jobsToPush, ...[jobs].flat()]\n return this\n }\n\n // QueueManager ---------------------------------------------------------------------------------------------\n\n /**\n * A recording view of the connection (pushes remember its name). Its size()/clear() only see the jobs pushed\n * through that connection name (no name: the jobs pushed without one, i.e. through the manager or connection()).\n */\n connection(name?: string): Queue {\n return {\n push: (job, queue) => this.record(name, job, queue, undefined),\n later: (delay, job, queue) => this.record(name, job, queue, delay),\n pushRaw: (payload, queue, delay) => this.recordRaw(name, payload, queue, delay),\n pop: (queue) => this.pop(queue),\n size: async (queue) => this.jobs.filter((pushed) => this.on(pushed, queue, { name })).length,\n clear: async (queue) => this.remove(queue, { name }),\n }\n }\n\n push(job: Job, queue?: string): Promise<string> {\n return this.record(undefined, job, queue, undefined)\n }\n\n later(delaySeconds: number, job: Job, queue?: string): Promise<string> {\n return this.record(undefined, job, queue, delaySeconds)\n }\n\n pushRaw(payload: QueuePayload, queue?: string, delaySeconds?: number): Promise<string> {\n return this.recordRaw(undefined, payload, queue, delaySeconds)\n }\n\n async pop(_queue?: string): Promise<QueueJob | undefined> {\n return undefined\n }\n\n /** Jobs on `queue` (every queue when omitted), whatever connection they were pushed on, like Laravel's fake. */\n async size(queue?: string): Promise<number> {\n return this.jobs.filter((pushed) => this.on(pushed, queue)).length\n }\n\n /** Removes the jobs size() counts and returns how many. */\n async clear(queue?: string): Promise<number> {\n return this.remove(queue)\n }\n\n extend(_driver: string, _factory: (config: Record<string, unknown>) => Queue): void {}\n\n // Assertions ---------------------------------------------------------------------------------------------\n\n /** Pushed at least once; a number asserts the count; a filter gets (job, queue, connection). */\n assertPushed<J extends Job>(job: Target<J>, callback?: CountOrFilter<[J, string | undefined, string | undefined]>): void {\n if (typeof callback === 'number') return this.assertPushedTimes(job, callback)\n assert(this.pushed(job, callback).length > 0, `The expected [${nameOf(job)}] job was not pushed.`)\n }\n\n assertPushedTimes<J extends Job>(job: Target<J>, times = 1): void {\n const count = this.pushed(job).length\n assert(count === times, `The expected [${nameOf(job)}] job was pushed ${count} times instead of ${times} times.`, { actual: count, expected: times })\n }\n\n assertPushedOn<J extends Job>(queue: string, job: Target<J>, callback?: Filter<J>): void {\n this.assertPushed(job, (pushed: J, on: string | undefined, connection: string | undefined) => on === queue && (callback === undefined || callback(pushed, on, connection)))\n }\n\n assertNotPushed<J extends Job>(job: Target<J>, callback?: Filter<J>): void {\n assert(this.pushed(job, callback).length === 0, `The unexpected [${nameOf(job)}] job was pushed.`)\n }\n\n assertNothingPushed(): void {\n const names = this.jobs.map((pushed) => this.nameOf(pushed))\n assert(names.length === 0, `The following jobs were pushed unexpectedly:\\n\\n- ${names.join('\\n- ')}`)\n }\n\n assertCount(expected: number): void {\n assert(this.jobs.length === expected, `Expected ${expected} jobs to be pushed, but found ${this.jobs.length} instead.`, { actual: this.jobs.length, expected })\n }\n\n /** The job was pushed with exactly this chain (Bus stores it on the first job under the protocol key). */\n assertPushedWithChain<J extends Job>(job: Target<J>, expectedChain: Array<Target | Job>, callback?: Filter<J>): void {\n const jobs = this.pushed(job, callback)\n assert(jobs.length > 0, `The expected [${nameOf(job)}] job was not pushed.`)\n const found = jobs.some((pushed) => {\n const chain = chainOf(pushed)\n return chain.length === expectedChain.length && chain.every((link, index) => sameJob(link, expectedChain[index] as Target | Job))\n })\n assert(found, `The expected chain was not pushed with [${nameOf(job)}].`)\n }\n\n assertPushedWithoutChain<J extends Job>(job: Target<J>, callback?: Filter<J>): void {\n const jobs = this.pushed(job, callback)\n assert(jobs.length > 0, `The expected [${nameOf(job)}] job was not pushed.`)\n assert(jobs.some((pushed) => chainOf(pushed).length === 0), `The expected [${nameOf(job)}] job was pushed with a chain.`)\n }\n\n /** Pushed jobs matching the target (raw payloads match by their registry name or display name). */\n pushed<J extends Job>(job: Target<J>, callback?: Filter<J>): J[] {\n return this.jobs\n .filter((pushed) => this.targets(pushed, job) && (callback === undefined || callback(pushed.job as J, pushed.queue, pushed.connection)))\n .map((pushed) => pushed.job as J)\n }\n\n hasPushed<J extends Job>(job: Target<J>): boolean {\n return this.pushed(job).length > 0\n }\n\n // Internals ----------------------------------------------------------------------------------------------\n\n private async record(connection: string | undefined, job: Job, queue: string | undefined, delay: number | undefined): Promise<string> {\n if (!this.shouldFake(job)) {\n const real = this.real().connection(connection)\n return delay === undefined ? real.push(job, queue) : real.later(delay, job, queue)\n }\n this.jobs.push({ job, raw: false, connection, queue, delay })\n return randomUUID()\n }\n\n private async recordRaw(connection: string | undefined, payload: QueuePayload, queue: string | undefined, delay: number | undefined): Promise<string> {\n this.jobs.push({ job: payload, raw: true, connection, queue, delay })\n return payload.uuid\n }\n\n /** The job is on `queue` (any when undefined) and, when `connection` is given, was pushed on that connection name. */\n private on(pushed: PushedJob, queue: string | undefined, connection?: { name: string | undefined }): boolean {\n return (queue === undefined || pushed.queue === queue) && (connection === undefined || pushed.connection === connection.name)\n }\n\n private remove(queue: string | undefined, connection?: { name: string | undefined }): number {\n const before = this.jobs.length\n const kept = this.jobs.filter((pushed) => !this.on(pushed, queue, connection))\n this.jobs.splice(0, this.jobs.length, ...kept)\n return before - kept.length\n }\n\n private targets(pushed: PushedJob, target: Target): boolean {\n if (!pushed.raw) return matchesAny(pushed.job, [target])\n const payload = pushed.job as QueuePayload\n const name = nameOf(target)\n return payload.job === name || payload.displayName === name\n }\n\n private nameOf(pushed: PushedJob): string {\n return pushed.raw ? (pushed.job as QueuePayload).displayName : nameOf(pushed.job)\n }\n\n private shouldFake(job: Job): boolean {\n if (matchesAny(job, this.jobsToPush)) return false\n return this.jobsToFake.length === 0 || matchesAny(job, this.jobsToFake)\n }\n\n private real(): QueueManager {\n if (this.manager === undefined) fail('Queue.fake() was given jobs to fake, but there is no real QueueManager for the others.')\n return this.manager\n }\n}\n\nfunction chainOf(job: Job): Job[] {\n const chain = (job as unknown as Record<symbol, { jobs?: Job[] } | undefined>)[CHAIN]\n return chain?.jobs ?? []\n}\n","import { MailManager, type Address, type Mailable, type Mailer, type MailRecipient, type MailTransport, type PendingMail, type SentMessage } from '@orieljs/contracts'\nimport { assert } from '../assert'\nimport { bound, install, isQueueable, matchesAny, nameOf, type CountOrFilter, type Target } from './support'\n\n/** A mailable the fake saw, with its resolved recipients (PendingMail's, else the envelope's) and subject. */\nexport class MailRecord<M extends Mailable = Mailable> {\n constructor(\n readonly mailable: M,\n readonly mailer: string | undefined,\n readonly to: Address[],\n readonly cc: Address[],\n readonly bcc: Address[],\n readonly subject: string | undefined,\n readonly queued: boolean,\n readonly delay: number | undefined,\n ) {}\n\n hasTo(address: MailRecipient): boolean {\n return includes(this.to, address)\n }\n\n hasCc(address: MailRecipient): boolean {\n return includes(this.cc, address)\n }\n\n hasBcc(address: MailRecipient): boolean {\n return includes(this.bcc, address)\n }\n\n hasSubject(subject: string): boolean {\n return this.subject === subject\n }\n}\n\ntype Filter<M extends Mailable> = (mailable: M, mail: MailRecord<M>) => boolean\ninterface Overrides {\n to: Address[]\n cc: Address[]\n bcc: Address[]\n}\n\n/**\n * Laravel's Mail::fake(): records what would have been sent or queued. Queueable mailables (the Queue/Bus\n * protocol's rule) sent with send() count as queued, like the real Mailer. Nothing is rendered or delivered.\n */\nexport class MailFake implements MailManager {\n readonly records: MailRecord[] = []\n\n constructor(readonly manager: MailManager | undefined = undefined) {}\n\n static fake(): MailFake {\n const current = bound(MailManager)\n return install(MailManager, new MailFake(current instanceof MailFake ? current.manager : current))\n }\n\n // MailManager ----------------------------------------------------------------------------------------------\n\n mailer(name?: string): Mailer {\n return {\n to: (recipients) => this.pending(name, recipients),\n send: (mailable) => this.sendVia(name, mailable, empty()),\n queue: (mailable) => this.queueVia(name, mailable, empty(), undefined),\n }\n }\n\n to(recipients: MailRecipient | MailRecipient[]): PendingMail {\n return this.pending(undefined, recipients)\n }\n\n send(mailable: Mailable): Promise<SentMessage | undefined> {\n return this.sendVia(undefined, mailable, empty())\n }\n\n queue(mailable: Mailable): Promise<void> {\n return this.queueVia(undefined, mailable, empty(), undefined)\n }\n\n extend(_transport: string, _factory: (config: Record<string, unknown>) => MailTransport): void {}\n\n // Assertions ---------------------------------------------------------------------------------------------\n\n /** Sent (not queued) at least once; a number asserts the count; a filter gets (mailable, record). */\n assertSent<M extends Mailable>(mailable: Target<M>, callback?: CountOrFilter<[M, MailRecord<M>]>): void {\n if (typeof callback === 'number') return this.assertSentTimes(mailable, callback)\n const hint = this.queued(mailable).length > 0 ? '\\n\\nThe mailable was queued: did you mean assertQueued()?' : ''\n assert(this.sent(mailable, callback).length > 0, `The expected [${nameOf(mailable)}] mailable was not sent.${hint}`)\n }\n\n assertSentTimes<M extends Mailable>(mailable: Target<M>, times = 1): void {\n const count = this.sent(mailable).length\n assert(count === times, `The expected [${nameOf(mailable)}] mailable was sent ${count} times instead of ${times} times.`, { actual: count, expected: times })\n }\n\n assertNotSent<M extends Mailable>(mailable: Target<M>, callback?: Filter<M>): void {\n assert(this.sent(mailable, callback).length === 0, `The unexpected [${nameOf(mailable)}] mailable was sent.`)\n }\n\n assertNothingSent(): void {\n const names = this.records.filter((record) => !record.queued).map((record) => nameOf(record.mailable))\n assert(names.length === 0, `The following mailables were sent unexpectedly:\\n\\n- ${names.join('\\n- ')}`)\n }\n\n assertSentCount(count: number): void {\n const actual = this.records.filter((record) => !record.queued).length\n assert(actual === count, `The total number of mailables sent was ${actual} instead of ${count}.`, { actual, expected: count })\n }\n\n assertQueued<M extends Mailable>(mailable: Target<M>, callback?: CountOrFilter<[M, MailRecord<M>]>): void {\n if (typeof callback === 'number') {\n const count = this.queued(mailable).length\n assert(count === callback, `The expected [${nameOf(mailable)}] mailable was queued ${count} times instead of ${callback} times.`, { actual: count, expected: callback })\n return\n }\n assert(this.queued(mailable, callback).length > 0, `The expected [${nameOf(mailable)}] mailable was not queued.`)\n }\n\n assertNotQueued<M extends Mailable>(mailable: Target<M>, callback?: Filter<M>): void {\n assert(this.queued(mailable, callback).length === 0, `The unexpected [${nameOf(mailable)}] mailable was queued.`)\n }\n\n assertNothingQueued(): void {\n const names = this.records.filter((record) => record.queued).map((record) => nameOf(record.mailable))\n assert(names.length === 0, `The following mailables were queued unexpectedly:\\n\\n- ${names.join('\\n- ')}`)\n }\n\n assertQueuedCount(count: number): void {\n const actual = this.records.filter((record) => record.queued).length\n assert(actual === count, `The total number of mailables queued was ${actual} instead of ${count}.`, { actual, expected: count })\n }\n\n /** Sent or queued. */\n assertOutgoingCount(count: number): void {\n assert(this.records.length === count, `The total number of outgoing mailables was ${this.records.length} instead of ${count}.`, { actual: this.records.length, expected: count })\n }\n\n assertNothingOutgoing(): void {\n this.assertNothingSent()\n this.assertNothingQueued()\n }\n\n sent<M extends Mailable>(mailable: Target<M>, callback?: Filter<M>): M[] {\n return this.matching(mailable, false, callback)\n }\n\n queued<M extends Mailable>(mailable: Target<M>, callback?: Filter<M>): M[] {\n return this.matching(mailable, true, callback)\n }\n\n hasSent(mailable: Target<Mailable>): boolean {\n return this.sent(mailable).length > 0\n }\n\n hasQueued(mailable: Target<Mailable>): boolean {\n return this.queued(mailable).length > 0\n }\n\n // Internals ----------------------------------------------------------------------------------------------\n\n private pending(mailer: string | undefined, recipients: MailRecipient | MailRecipient[]): PendingMail {\n const overrides: Overrides = { to: addresses(recipients), cc: [], bcc: [] }\n const pending: PendingMail = {\n cc: (cc) => {\n overrides.cc.push(...addresses(cc))\n return pending\n },\n bcc: (bcc) => {\n overrides.bcc.push(...addresses(bcc))\n return pending\n },\n send: (mailable) => this.sendVia(mailer, mailable, overrides),\n queue: (mailable) => this.queueVia(mailer, mailable, overrides, undefined),\n later: (delay, mailable) => this.queueVia(mailer, mailable, overrides, delay),\n }\n return pending\n }\n\n private async sendVia(mailer: string | undefined, mailable: Mailable, overrides: Overrides): Promise<undefined> {\n await this.record(mailer, mailable, overrides, isQueueable(mailable), undefined)\n return undefined\n }\n\n private async queueVia(mailer: string | undefined, mailable: Mailable, overrides: Overrides, delay: number | undefined): Promise<void> {\n await this.record(mailer, mailable, overrides, true, delay)\n }\n\n private async record(mailer: string | undefined, mailable: Mailable, overrides: Overrides, queued: boolean, delay: number | undefined): Promise<void> {\n const envelope = await mailable.envelope()\n const to = overrides.to.length > 0 ? overrides.to : addresses(envelope.to ?? [])\n const cc = [...addresses(envelope.cc ?? []), ...overrides.cc]\n const bcc = [...addresses(envelope.bcc ?? []), ...overrides.bcc]\n this.records.push(new MailRecord(mailable, mailer, to, cc, bcc, envelope.subject, queued, delay))\n }\n\n private matching<M extends Mailable>(mailable: Target<M>, queued: boolean, callback?: Filter<M>): M[] {\n return (this.records as unknown as Array<MailRecord<M>>)\n .filter((record) => record.queued === queued && matchesAny(record.mailable, [mailable]) && (callback === undefined || callback(record.mailable, record)))\n .map((record) => record.mailable)\n }\n}\n\nfunction empty(): Overrides {\n return { to: [], cc: [], bcc: [] }\n}\n\n/** MailRecipient(s) → Address[] (strings, Address objects, or anything with email + name, such as a User model). */\nexport function addresses(recipients: MailRecipient | MailRecipient[]): Address[] {\n return [recipients].flat().map((recipient) => {\n if (typeof recipient === 'string') return { address: recipient }\n if ('address' in recipient) return recipient.name === undefined ? { address: recipient.address } : { address: recipient.address, name: recipient.name }\n return recipient.name === undefined ? { address: recipient.email } : { address: recipient.email, name: recipient.name }\n })\n}\n\nfunction includes(list: Address[], recipient: MailRecipient): boolean {\n const [wanted] = addresses(recipient)\n return list.some((address) => address.address === wanted!.address && (wanted!.name === undefined || address.name === wanted!.name))\n}\n","import { randomUUID } from 'node:crypto'\nimport { NotificationDispatcher, type Class, type Notifiable, type Notification, type NotificationChannel } from '@orieljs/contracts'\nimport { assert } from '../assert'\nimport { bound, install, matchesAny, nameOf, type CountOrFilter, type Target } from './support'\n\n/** One delivery the fake recorded: to whom, what, and on which channels (the notification's via()). */\nexport interface SentNotification {\n notifiable: Notifiable\n notification: Notification\n channels: string[]\n}\n\ntype Filter<N extends Notification> = (notification: N, channels: string[], notifiable: Notifiable) => boolean\n\n/** Notification.route('mail', 'a@b.c'): an on-demand notifiable (Laravel's AnonymousNotifiable). */\nexport class AnonymousNotifiable implements Notifiable {\n readonly routes = new Map<string, unknown>()\n\n constructor(private readonly dispatcher: NotificationDispatcher) {}\n\n route(channel: string, route: unknown): this {\n this.routes.set(channel, route)\n return this\n }\n\n routeNotificationFor(channel: string): unknown {\n return this.routes.get(channel)\n }\n\n notify(notification: Notification): Promise<void> {\n return this.dispatcher.send(this, notification)\n }\n}\n\n/**\n * 07's toNotifiableList() (Testing can't import Notifications): an array as is; one notifiable when it has\n * routeNotificationFor() (an iterable model is still one notifiable); else any iterable (a Collection, a Set).\n */\nfunction toNotifiableList(notifiables: Notifiable | Iterable<Notifiable>): Notifiable[] {\n if (Array.isArray(notifiables)) return notifiables as Notifiable[]\n if (typeof (notifiables as Partial<Notifiable>).routeNotificationFor === 'function') return [notifiables as Notifiable]\n if (typeof notifiables === 'object' && notifiables !== null && Symbol.iterator in notifiables) {\n return [...(notifiables as Iterable<Notifiable>)]\n }\n return [notifiables as Notifiable]\n}\n\n/** Models are the same notifiable when class and key match (Laravel keys its record by class and getKey()). */\nfunction sameNotifiable(a: Notifiable, b: Notifiable): boolean {\n if (a === b) return true\n const keyOf = (n: Notifiable) => {\n const model = n as Notifiable & { getKey?: () => unknown }\n return typeof model.getKey === 'function' ? model.getKey() : undefined\n }\n const key = keyOf(a)\n return key !== undefined && a.constructor === b.constructor && key === keyOf(b)\n}\n\n/**\n * Laravel's Notification::fake(): records notifications (send, sendNow, on-demand routes) instead of\n * delivering or queueing them. The Notifiable mixin's notify() resolves the dispatcher per call, so it lands here.\n */\nexport class NotificationFake implements NotificationDispatcher {\n readonly notifications: SentNotification[] = []\n\n constructor(readonly dispatcher: NotificationDispatcher | undefined = undefined) {}\n\n static fake(): NotificationFake {\n const current = bound(NotificationDispatcher)\n return install(NotificationDispatcher, new NotificationFake(current instanceof NotificationFake ? current.dispatcher : current))\n }\n\n // NotificationDispatcher -------------------------------------------------------------------------------------\n\n async send(notifiables: Notifiable | Iterable<Notifiable>, notification: Notification): Promise<void> {\n this.record(notifiables, notification)\n }\n\n async sendNow(notifiables: Notifiable | Iterable<Notifiable>, notification: Notification, channels?: string[]): Promise<void> {\n this.record(notifiables, notification, channels)\n }\n\n route(channel: string, route: unknown): AnonymousNotifiable {\n return new AnonymousNotifiable(this).route(channel, route)\n }\n\n /** The Notifications provider calls this in boot(); a fake has no channels to register. */\n extend(_channel: string, _factory: () => NotificationChannel): void {}\n\n // Assertions ---------------------------------------------------------------------------------------------\n\n /** Sent to the notifiable(s); a number asserts the count; a filter gets (notification, channels, notifiable). */\n assertSentTo<N extends Notification>(notifiable: Notifiable | Iterable<Notifiable>, notification: Target<N>, callback?: CountOrFilter<[N, string[], Notifiable]>): void {\n for (const one of toNotifiableList(notifiable)) {\n if (typeof callback === 'number') {\n this.assertSentToTimes(one, notification, callback)\n continue\n }\n assert(this.sent(one, notification, callback).length > 0, `The expected [${nameOf(notification)}] notification was not sent.`)\n }\n }\n\n assertSentToTimes<N extends Notification>(notifiable: Notifiable, notification: Target<N>, times = 1): void {\n const count = this.sent(notifiable, notification).length\n assert(count === times, `Expected [${nameOf(notification)}] to be sent ${times} times, but was sent ${count} times.`, { actual: count, expected: times })\n }\n\n assertNotSentTo<N extends Notification>(notifiable: Notifiable | Iterable<Notifiable>, notification: Target<N>, callback?: Filter<N>): void {\n for (const one of toNotifiableList(notifiable)) {\n assert(this.sent(one, notification, callback).length === 0, `The unexpected [${nameOf(notification)}] notification was sent.`)\n }\n }\n\n /** Sent through Notification.route(...) (an anonymous notifiable). */\n assertSentOnDemand<N extends Notification>(notification: Target<N>, callback?: CountOrFilter<[N, string[], AnonymousNotifiable]>): void {\n const matching = this.notifications.filter(\n (record) =>\n record.notifiable instanceof AnonymousNotifiable &&\n matchesAny(record.notification, [notification]) &&\n (typeof callback !== 'function' || callback(record.notification as N, record.channels, record.notifiable)),\n )\n if (typeof callback === 'number') {\n assert(matching.length === callback, `Expected [${nameOf(notification)}] to be sent on demand ${callback} times, but was sent ${matching.length} times.`)\n return\n }\n assert(matching.length > 0, `The expected [${nameOf(notification)}] notification was not sent on demand.`)\n }\n\n assertNothingSent(): void {\n const names = this.notifications.map((record) => nameOf(record.notification))\n assert(names.length === 0, `Notifications were sent unexpectedly:\\n\\n- ${names.join('\\n- ')}`)\n }\n\n assertNothingSentTo(notifiable: Notifiable): void {\n const count = this.notifications.filter((record) => sameNotifiable(record.notifiable, notifiable)).length\n assert(count === 0, 'Notifications were sent unexpectedly.')\n }\n\n /** Sent this many times in total, to anyone. */\n assertSentTimes(notification: Target<Notification>, times: number): void {\n const count = this.notifications.filter((record) => matchesAny(record.notification, [notification])).length\n assert(count === times, `Expected [${nameOf(notification)}] to be sent ${times} times, but was sent ${count} times.`, { actual: count, expected: times })\n }\n\n assertCount(expected: number): void {\n const actual = this.notifications.length\n assert(actual === expected, `Expected ${expected} notifications to be sent, but ${actual} were sent.`, { actual, expected })\n }\n\n sent<N extends Notification>(notifiable: Notifiable, notification: Target<N> | Class<N>, callback?: Filter<N>): N[] {\n return this.notifications\n .filter(\n (record) =>\n sameNotifiable(record.notifiable, notifiable) &&\n matchesAny(record.notification, [notification as Target]) &&\n (callback === undefined || callback(record.notification as N, record.channels, record.notifiable)),\n )\n .map((record) => record.notification as N)\n }\n\n hasSent(notifiable: Notifiable, notification: Target<Notification>): boolean {\n return this.sent(notifiable, notification).length > 0\n }\n\n private record(notifiables: Notifiable | Iterable<Notifiable>, notification: Notification, channels?: string[]): void {\n notification.id ??= randomUUID()\n for (const notifiable of toNotifiableList(notifiables)) {\n this.notifications.push({ notifiable, notification, channels: channels ?? notification.via(notifiable) })\n }\n }\n}\n","import { randomBytes } from 'node:crypto'\nimport { ConfigRepository, FilesystemManager, type ErrorKind, type Filesystem, type OrielError, type PutOptions, type UploadedFile } from '@orieljs/contracts'\nimport { assert, fail } from '../assert'\nimport { bound, install } from './support'\n\n/**\n * The fake disk's failures, named and worded like Filesystem's PathTraversalError and FileNotFoundError (10).\n * Not an HTTP condition: kind 'Server', so the app reports them and renders a 500, as with a real disk.\n */\nclass FakeDiskError extends Error implements OrielError {\n readonly kind: ErrorKind = 'Server'\n readonly status = 500\n constructor(name: 'PathTraversalError' | 'FileNotFoundError', message: string, readonly path: string) {\n super(message)\n this.name = name\n }\n}\n\ninterface StoredFile {\n bytes: Uint8Array\n visibility: 'public' | 'private'\n mimeType: string | undefined\n modified: Date\n}\n\nconst MIME: Record<string, string> = {\n txt: 'text/plain', html: 'text/html', css: 'text/css', js: 'text/javascript', json: 'application/json', csv: 'text/csv',\n pdf: 'application/pdf', zip: 'application/zip', png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif',\n webp: 'image/webp', svg: 'image/svg+xml', mp3: 'audio/mpeg', mp4: 'video/mp4',\n}\n\nexport function guessMimeType(path: string): string | undefined {\n const extension = path.split('.').pop()?.toLowerCase() ?? ''\n return MIME[extension]\n}\n\n/** Laravel's hashName(): 40 random alphanumerics plus the extension. */\nfunction hashName(file: UploadedFile): string {\n const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'\n const name = [...randomBytes(40)].map((byte) => alphabet[byte % alphabet.length]).join('')\n const extension = file.extension()\n return extension === '' ? name : `${name}.${extension}`\n}\n\n/** Disk-relative path without leading/trailing slashes; a `..` that would climb above the root is rejected. */\nfunction normalize(path: string): string {\n const parts: string[] = []\n for (const segment of path.replaceAll('\\\\', '/').split('/')) {\n if (segment === '' || segment === '.') continue\n if (segment !== '..') parts.push(segment)\n else if (parts.pop() === undefined) {\n throw new FakeDiskError('PathTraversalError', `Path traversal detected: \"${path}\" resolves outside the disk root.`, path)\n }\n }\n return parts.join('/')\n}\n\nconst within = (path: string, directory: string) => directory === '' || path.startsWith(`${directory}/`)\n\n/**\n * An in-memory disk implementing the Filesystem contract, with Laravel's fake-disk assertions. (Laravel's fake\n * writes to storage/framework/testing/disks; this one keeps files in memory, so there's nothing to clean up.)\n */\nexport class FakeDisk implements Filesystem {\n /** Stored files by normalized path. */\n readonly stored = new Map<string, StoredFile>()\n /** Directories made explicitly (others exist because files are in them). */\n readonly made = new Set<string>()\n\n constructor(readonly name: string, private readonly urlPrefix = `/storage`) {}\n\n async exists(path: string): Promise<boolean> {\n const key = normalize(path)\n return this.stored.has(key) || this.isDirectory(key)\n }\n\n async missing(path: string): Promise<boolean> {\n return !(await this.exists(path))\n }\n\n async get(path: string): Promise<string> {\n return new TextDecoder().decode(this.read(path).bytes)\n }\n\n async getBytes(path: string): Promise<Uint8Array> {\n return this.read(path).bytes.slice()\n }\n\n async readStream(path: string): Promise<ReadableStream<Uint8Array>> {\n const bytes = this.read(path).bytes.slice()\n return new ReadableStream({\n start(controller) {\n controller.enqueue(bytes)\n controller.close()\n },\n })\n }\n\n async put(path: string, contents: string | Uint8Array | ReadableStream<Uint8Array>, options: PutOptions = {}): Promise<boolean> {\n const key = normalize(path)\n const bytes = typeof contents === 'string' ? new TextEncoder().encode(contents) : contents instanceof Uint8Array ? contents.slice() : await collect(contents)\n this.stored.set(key, { bytes, visibility: options.visibility ?? 'private', mimeType: options.mimeType ?? guessMimeType(key), modified: new Date() })\n return true\n }\n\n putFile(directory: string, file: UploadedFile, options: PutOptions = {}): Promise<string> {\n return this.putFileAs(directory, file, hashName(file), options)\n }\n\n async putFileAs(directory: string, file: UploadedFile, name: string, options: PutOptions = {}): Promise<string> {\n const path = normalize(`${directory}/${name}`)\n await this.put(path, new Uint8Array(await file.arrayBuffer()), { ...options, mimeType: options.mimeType ?? file.mimeType })\n return path\n }\n\n async delete(paths: string | string[]): Promise<boolean> {\n for (const path of [paths].flat()) this.stored.delete(normalize(path))\n return true\n }\n\n async copy(from: string, to: string): Promise<boolean> {\n const file = this.read(from)\n this.stored.set(normalize(to), { ...file, bytes: file.bytes.slice(), modified: new Date() })\n return true\n }\n\n async move(from: string, to: string): Promise<boolean> {\n await this.copy(from, to)\n this.stored.delete(normalize(from))\n return true\n }\n\n async size(path: string): Promise<number> {\n return this.read(path).bytes.byteLength\n }\n\n async lastModified(path: string): Promise<Date> {\n return this.read(path).modified\n }\n\n async mimeType(path: string): Promise<string | undefined> {\n return this.read(path).mimeType\n }\n\n url(path: string): string {\n return `${this.urlPrefix}/${normalize(path)}`\n }\n\n async temporaryUrl(path: string, expiresAt: Date): Promise<string> {\n return `${this.url(path)}?expiration=${Math.floor(expiresAt.getTime() / 1000)}`\n }\n\n async files(directory = '', recursive = false): Promise<string[]> {\n const dir = normalize(directory)\n return [...this.stored.keys()].filter((path) => within(path, dir) && (recursive || !path.slice(dir === '' ? 0 : dir.length + 1).includes('/'))).sort()\n }\n\n async directories(directory = '', recursive = false): Promise<string[]> {\n const dir = normalize(directory)\n const all = new Set<string>([...this.made])\n for (const path of this.stored.keys()) {\n const parts = path.split('/').slice(0, -1)\n for (let i = 1; i <= parts.length; i++) all.add(parts.slice(0, i).join('/'))\n }\n return [...all].filter((path) => within(path, dir) && path !== dir && (recursive || !path.slice(dir === '' ? 0 : dir.length + 1).includes('/'))).sort()\n }\n\n async makeDirectory(path: string): Promise<boolean> {\n this.made.add(normalize(path))\n return true\n }\n\n async deleteDirectory(path: string): Promise<boolean> {\n const dir = normalize(path)\n for (const file of [...this.stored.keys()]) if (within(file, dir)) this.stored.delete(file)\n for (const directory of [...this.made]) if (directory === dir || within(directory, dir)) this.made.delete(directory)\n return true\n }\n\n /** A virtual absolute path (the files only exist in memory). */\n path(path: string): string {\n return `/fake-disks/${this.name}/${normalize(path)}`\n }\n\n // Assertions (Laravel's FilesystemAdapter test helpers) -----------------------------------------------------\n\n /** The file(s) exist; with `content`, the (single) file has exactly that content. */\n async assertExists(path: string | string[], content?: string): Promise<this> {\n for (const one of [path].flat()) {\n assert(this.stored.has(normalize(one)), `Unable to find a file or directory at path [${one}].`)\n if (content !== undefined) {\n const actual = await this.get(one)\n assert(actual === content, `File or directory [${one}] was found, but content [${actual}] does not match [${content}].`, { actual, expected: content })\n }\n }\n return this\n }\n\n async assertMissing(path: string | string[]): Promise<this> {\n for (const one of [path].flat()) assert(!this.stored.has(normalize(one)), `Found unexpected file or directory at path [${one}].`)\n return this\n }\n\n async assertDirectoryEmpty(path: string): Promise<this> {\n const files = await this.files(path, true)\n assert(files.length === 0, `Directory [${path}] is not empty.`, { actual: files })\n return this\n }\n\n async assertCount(path: string, count: number, recursive = false): Promise<this> {\n const actual = (await this.files(path, recursive)).length\n assert(actual === count, `Expected [${count}] files at [${path}], but found [${actual}].`, { actual, expected: count })\n return this\n }\n\n private read(path: string): StoredFile {\n const file = this.stored.get(normalize(path))\n if (file === undefined) throw new FakeDiskError('FileNotFoundError', `File not found at path: ${path}`, path)\n return file\n }\n\n private isDirectory(key: string): boolean {\n return this.made.has(key) || [...this.stored.keys()].some((path) => key !== '' && path.startsWith(`${key}/`))\n }\n}\n\nasync function collect(stream: ReadableStream<Uint8Array>): Promise<Uint8Array> {\n const chunks: Uint8Array[] = []\n for await (const chunk of stream) chunks.push(chunk)\n const out = new Uint8Array(chunks.reduce((total, chunk) => total + chunk.byteLength, 0))\n let offset = 0\n for (const chunk of chunks) {\n out.set(chunk, offset)\n offset += chunk.byteLength\n }\n return out\n}\n\n/**\n * Laravel's Storage::fake('avatars'): swaps the FilesystemManager for one whose faked disks live in memory\n * (other disks still reach the real manager). Returns the fake disk.\n */\nexport class StorageFake implements FilesystemManager {\n readonly disks = new Map<string, FakeDisk>()\n\n constructor(readonly manager: FilesystemManager | undefined, private readonly defaultDisk: string) {}\n\n static fake(disk?: string): FakeDisk {\n const current = bound(FilesystemManager)\n const config = bound(ConfigRepository)\n const fake = current instanceof StorageFake ? current : install(FilesystemManager, new StorageFake(current, config?.get<string>('filesystems.default', 'local') ?? 'local'))\n const name = disk ?? fake.defaultDisk\n const faked = new FakeDisk(name)\n fake.disks.set(name, faked)\n return faked\n }\n\n disk(name?: string): Filesystem {\n const disk = name ?? this.defaultDisk\n const faked = this.disks.get(disk)\n if (faked !== undefined) return faked\n if (this.manager === undefined) fail(`Disk [${disk}] is not faked and there is no real FilesystemManager.`)\n return this.manager.disk(disk)\n }\n\n extend(driver: string, factory: (config: Record<string, unknown>) => Filesystem): void {\n this.manager?.extend(driver, factory)\n }\n\n exists(path: string) { return this.disk().exists(path) }\n missing(path: string) { return this.disk().missing(path) }\n get(path: string) { return this.disk().get(path) }\n getBytes(path: string) { return this.disk().getBytes(path) }\n readStream(path: string) { return this.disk().readStream(path) }\n put(path: string, contents: string | Uint8Array | ReadableStream<Uint8Array>, options?: PutOptions) { return this.disk().put(path, contents, options) }\n putFile(directory: string, file: UploadedFile, options?: PutOptions) { return this.disk().putFile(directory, file, options) }\n putFileAs(directory: string, file: UploadedFile, name: string, options?: PutOptions) { return this.disk().putFileAs(directory, file, name, options) }\n delete(paths: string | string[]) { return this.disk().delete(paths) }\n copy(from: string, to: string) { return this.disk().copy(from, to) }\n move(from: string, to: string) { return this.disk().move(from, to) }\n size(path: string) { return this.disk().size(path) }\n lastModified(path: string) { return this.disk().lastModified(path) }\n mimeType(path: string) { return this.disk().mimeType(path) }\n url(path: string) { return this.disk().url(path) }\n temporaryUrl(path: string, expiresAt: Date) { return this.disk().temporaryUrl(path, expiresAt) }\n files(directory?: string, recursive?: boolean) { return this.disk().files(directory, recursive) }\n directories(directory?: string, recursive?: boolean) { return this.disk().directories(directory, recursive) }\n makeDirectory(path: string) { return this.disk().makeDirectory(path) }\n deleteDirectory(path: string) { return this.disk().deleteDirectory(path) }\n path(path: string) { return this.disk().path(path) }\n}\n","import { deflateSync } from 'node:zlib'\nimport { guessMimeType } from './Fakes/StorageFake'\n\nconst CRC_TABLE = Array.from({ length: 256 }, (_, n) => {\n let c = n\n for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1\n return c >>> 0\n})\n\nfunction crc32(bytes: Uint8Array): number {\n let crc = 0xffffffff\n for (const byte of bytes) crc = CRC_TABLE[(crc ^ byte) & 0xff]! ^ (crc >>> 8)\n return (crc ^ 0xffffffff) >>> 0\n}\n\nfunction chunk(type: string, data: Uint8Array): Uint8Array {\n const out = new Uint8Array(12 + data.length)\n const view = new DataView(out.buffer)\n view.setUint32(0, data.length)\n out.set(new TextEncoder().encode(type), 4)\n out.set(data, 8)\n view.setUint32(8 + data.length, crc32(out.subarray(4, 8 + data.length)))\n return out\n}\n\n/** A valid white RGB PNG of the given size. */\nfunction png(width: number, height: number): Uint8Array {\n const header = new Uint8Array(13)\n const view = new DataView(header.buffer)\n view.setUint32(0, width)\n view.setUint32(4, height)\n header.set([8, 2, 0, 0, 0], 8) // 8-bit, truecolor, deflate, no filter, no interlace\n const rows = new Uint8Array((width * 3 + 1) * height).fill(255)\n for (let y = 0; y < height; y++) rows[y * (width * 3 + 1)] = 0 // filter byte per row\n const parts = [new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10]), chunk('IHDR', header), chunk('IDAT', deflateSync(rows)), chunk('IEND', new Uint8Array())]\n const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0))\n let offset = 0\n for (const part of parts) {\n out.set(part, offset)\n offset += part.length\n }\n return out\n}\n\n/** Laravel's UploadedFile::fake(): File objects to post as multipart uploads (t.post(uri, { avatar: file })). */\nexport const FakeFile = {\n /** A file of `kilobytes` KiB (zero bytes), typed by `mimeType` or the extension. */\n create(name: string, kilobytes = 0, mimeType?: string): File {\n return new File([new Uint8Array(Math.round(kilobytes * 1024))], name, { type: mimeType ?? guessMimeType(name) ?? 'application/octet-stream' })\n },\n\n /** A real PNG image of the given size (typed by the name's extension, like Laravel's image()). */\n image(name: string, width = 10, height = 10): File {\n return new File([png(width, height)], name, { type: guessMimeType(name) ?? 'image/png' })\n },\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AEAA,SAAS,YAAY,oBAAoB;AACzC,SAAS,YAAY;AACrB,SAAS,aAAa;ACFtB,SAAS,cAAAA,aAAY,mBAAmB;AACxC,SAAS,QAAAC,aAAY;AACrB,SAAS,qBAAqB;AHCvB,IAAM,aAAN,MAA6C;EAClD,YAA6B,QAAiC,CAAC,GAAG;AAArC,SAAA,QAAA;EAAsC;EAAtC;EAE7B,IAAI,KAAsB;AACxB,WAAO,IAAI,IAAI,KAAK,OAAO,GAAG;EAChC;EAEA,IAAiB,KAAa,cAAqB;AACjD,WAAO,IAAI,IAAI,KAAK,OAAO,KAAK,YAAY;EAC9C;EAIA,IAAI,aAA+C,OAAuB;AACxE,UAAM,UAAU,OAAO,gBAAgB,WAAW,CAAC,CAAC,aAAa,KAAK,CAAU,IAAI,OAAO,QAAQ,WAAW;AAC9G,eAAW,CAAC,GAAG,CAAC,KAAK,QAAS,KAAI,IAAI,KAAK,OAAO,GAAG,CAAC;EACxD;EAEA,KAAK,KAAa,OAAsB;AACtC,UAAM,UAAU,KAAK,IAAe,KAAK,CAAC,CAAC;AAC3C,SAAK,IAAI,KAAK,CAAC,GAAI,MAAM,QAAQ,OAAO,IAAI,UAAU,CAAC,OAAO,GAAI,KAAK,CAAC;EAC1E;EAEA,MAA+B;AAC7B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AC,CAAC,GAAG,MAAM,EAAE,MAAM,YAAY,cAAc,IAAI,KAAK,2BAA2B,CAAC;EAC/I;;EAGA,MAAM,MAAc,QAAQ,IAAI,SAAS,IAAU;AACjD,WAAO,IAAI,KAAK,CAAC,IAAI,OAAO,MAAM,CAAC,GAAG,MAAM,EAAE,MAAM,cAAc,IAAI,KAAK,YAAY,CAAC;EAC1F;AACF;","names":["existsSync","join","join","join","existsSync","readFileSync","join","join","existsSync","readFileSync","chunk","ConfigRepository","attributes","Application","ApplicationToken","ClassRegistry","existsSync","join","randomUUID","randomUUID","randomBytes","ConsoleKernel","env","clonePlain","size","ConfigRepository","existsSync","join","Arr","format","target","Encrypter","Application","DatabaseManager","AuthFactory","randomUUID","randomBytes","chunk"]}