/** * Browser Model Loader * * Dynamically imports all model definitions from app/Models/ and creates * browser-compatible models that use fetch() for API calls. * * This eliminates the need for code generation - models are loaded at runtime. */ import { createBrowserModel } from 'bun-query-builder/browser' /** * Minimal shape of a model attribute as far as the browser model * loader is concerned. The full server-side attribute has * `factory`, validation rules, casters, etc. — none of which are * meaningful client-side, so we strip them off in * {@link extractBrowserAttributes}. */ export interface BrowserAttributeDefinition { fillable?: boolean hidden?: boolean guarded?: boolean nullable?: boolean } /** * `useApi` trait shape — declares the REST URI the browser model * should call into. When omitted, the loader skips the model * (browser code can't reach a model that has no API surface). */ export interface BrowserUseApiTrait { uri: string [extra: string]: unknown } /** * Subset of model-traits the browser loader inspects. Server-side * traits like `useAudit`, `observe`, etc. aren't meaningful client- * side — only the four below influence browser-side behaviour. */ export interface BrowserModelTraits { useApi?: BrowserUseApiTrait useUuid?: boolean useTimestamps?: boolean useSoftDeletes?: boolean [extra: string]: unknown } /** * Shape of a `defineModel(...)`-returned module's default export * that the browser loader cares about. Mirrors a tight subset of * `StacksModelDefinition` from `@stacksjs/orm` — typed locally so * the browser package doesn't pull the full ORM types in. */ export interface BrowserModelDefinition { name: string table?: string primaryKey?: string traits?: BrowserModelTraits attributes?: Record [extra: string]: unknown } /** * Shape of a model returned by `createBrowserModel`. Methods are * declared loosely (the underlying bun-query-builder API surface * is broader and changes) — we only check `.all` / `.find` exist * in {@link getBrowserModelNames} for discovery. */ export interface BrowserModel { all: (...args: unknown[]) => unknown find: (id: string | number, ...args: unknown[]) => unknown [extra: string]: unknown } /** * Window augmentation for the framework's `StacksBrowser` global * (stacksjs/stacks#1894 T-9). Pre-fix every access went through * `(window)` — typos in model names silently returned * `undefined`. The augmented index signature still permits any * model name at runtime; what it adds is the existence + shape of * the StacksBrowser bag itself. */ declare global { interface Window { /* * A bag of models AND of the browser auto-imports, because both write to * it: `auto-init` seeds it with `getBrowserAutoImports()` and then * `loadBrowserModels()` registers models into the same object. * * So `Record` was never true of it - the * query builder and composables sitting in there are not models - and the * registration below already had to cast around its own declaration. * `unknown` is what the bag holds; `isBrowserModel` is what turns an entry * back into a model, and it is the same duck-type test * `getBrowserModelNames` was already applying. */ StacksBrowser?: Record } } /** An entry in the bag that is a model, rather than one of the utilities. */ function isBrowserModel(value: unknown): value is BrowserModel { return value != null && typeof (value as BrowserModel).all === 'function' && typeof (value as BrowserModel).find === 'function' } /** * Model definitions to register, when someone supplies them. * * This used to be an `import.meta.glob` read behind `typeof * import.meta.glob === 'function'`. That guard could never run: `import.meta` * outside a module is a PARSE error, so the file failed before reaching it. * Since this package is transpiled file-by-file rather than bundled, the token * travelled into application bundles, and any page emitted as a classic script * died on it — every feature on the page, not only models. * * The glob now lives in `./model-glob`, which is the only place that can throw * and the only place that needs to. Vite consumers pass it in: * * import { modelModules } from '@stacksjs/browser/model-glob' * * loadBrowserModels(modelModules) * * Everyone else gets an empty map and a page that parses. */ const registeredModules: Record = {} /** * Add model definitions for `loadBrowserModels()` to pick up. * * Additive rather than replacing, so several sources can contribute and a * second call cannot silently drop the first one's models. */ export function registerModelModules(modules: Record): void { Object.assign(registeredModules, modules) } /** * Load all models and register them on window.StacksBrowser */ export function loadBrowserModels(modules?: Record): void { if (typeof window === 'undefined') return if (modules) registerModelModules(modules) const modelModules = registeredModules // Ensure StacksBrowser exists if (!window.StacksBrowser) { window.StacksBrowser = {} } for (const [path, module] of Object.entries(modelModules)) { const definition = module.default // Skip if no default export or no name if (!definition || !definition.name) { console.warn(`[model-loader] Skipping ${path}: no valid model definition`) continue } // Skip if no useApi trait (model doesn't have API routes) if (!definition.traits?.useApi?.uri) { continue } try { // Create browser model from definition const browserModel = createBrowserModel({ name: definition.name, table: definition.table ?? definition.name.toLowerCase(), primaryKey: definition.primaryKey || 'id', traits: { useUuid: definition.traits?.useUuid ?? false, useTimestamps: definition.traits?.useTimestamps ?? true, useSoftDeletes: definition.traits?.useSoftDeletes ?? false, useApi: definition.traits?.useApi, }, attributes: extractBrowserAttributes(definition.attributes ?? {}), } as const) // Register on StacksBrowser window.StacksBrowser[definition.name] = browserModel } catch (error) { console.error(`[model-loader] Failed to create browser model for ${definition.name}:`, error) } } } /** * Extract browser-relevant attributes from full model definition. * Strips out server-only properties like validation rules and factories. */ function extractBrowserAttributes( attributes: Record, ): Record { const browserAttrs: Record = {} for (const [name, attr] of Object.entries(attributes)) { browserAttrs[name] = { fillable: attr.fillable ?? false, hidden: attr.hidden ?? false, guarded: attr.guarded ?? false, nullable: attr.nullable ?? false, } } return browserAttrs } /** * Get a loaded model by name */ export function getBrowserModel(name: string): BrowserModel | null { if (typeof window === 'undefined') return null const entry = window.StacksBrowser?.[name] return isBrowserModel(entry) ? entry : null } /** * Get all loaded model names */ export function getBrowserModelNames(): string[] { if (typeof window === 'undefined') return [] const stacksBrowser = window.StacksBrowser if (!stacksBrowser) return [] return Object.keys(stacksBrowser).filter(key => isBrowserModel(stacksBrowser[key])) }