@wildo-ai/zod-decorators 1.1.1 → 1.1.3

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.
@@ -71,6 +71,36 @@ export declare function resolveMimeTypes(allowedMimeTypes: string[] | FileMimeTy
71
71
  *
72
72
  * Creates a file schema with metadata for detection and form component rendering.
73
73
  *
74
+ * ## Where a file field may be declared
75
+ *
76
+ * **The resource's primary scope must be application, organization or user.** A resource scoped to
77
+ * an ANONYMOUS visitor cannot carry a file field — a file's own scope is one of those three, so
78
+ * there is nothing to attribute the bytes to, and the upload refuses that scope by name rather than
79
+ * pretending to support it.
80
+ *
81
+ * **Within the schema, a file field may nest inside objects, arrays and DISCRIMINATED unions.** It
82
+ * may NOT sit inside a record, a map, a set, a tuple, or a plain (non-discriminated) union — the
83
+ * walker that finds file fields refuses those shapes. Where variants are needed, use a discriminated
84
+ * union.
85
+ *
86
+ * **A field carried on several branches of a discriminated union must declare IDENTICAL options on
87
+ * every branch.** Differing options at one path are a conflict the framework refuses rather than
88
+ * choosing between, so a branch that quietly widens `maxSize` or changes `allowedMimeTypes` fails
89
+ * the schema instead of silently winning.
90
+ *
91
+ * ## Uploading is not attaching
92
+ *
93
+ * The generated upload route creates a FILE ROW. Attaching it to a business record is that record's
94
+ * own write, with its own authority. So an uploaded-but-never-submitted file is a real state a
95
+ * caller can produce; the cleanup sweep is what handles it.
96
+ *
97
+ * ## Declaring `imageConstraints.aspectRatio` turns the cropper on
98
+ *
99
+ * That option is the switch for the browser-side crop step — nothing else is wired. It applies to
100
+ * single-file fields only: a `multiple` field keeps the plain upload path. Vector images and
101
+ * formats the browser cannot decode bypass the cropper and upload the original, so the server-side
102
+ * constraint stays the authority.
103
+ *
74
104
  * @param options - Configuration options for file field
75
105
  * @returns A Zod object schema with metadata for file detection
76
106
  */
@@ -1 +1 @@
1
- {"version":3,"file":"zod-file.d.ts","sourceRoot":"","sources":["../../../src/zod-file.ts"],"names":[],"mappings":"AA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C,EAAE,mBAAmB,CAAC;CAChC,GAAG,yBAAyB,CA4B5B"}
@@ -131,6 +131,36 @@ function assertGeneratedPdfFileOptions(params) {
131
131
  *
132
132
  * Creates a file schema with metadata for detection and form component rendering.
133
133
  *
134
+ * ## Where a file field may be declared
135
+ *
136
+ * **The resource's primary scope must be application, organization or user.** A resource scoped to
137
+ * an ANONYMOUS visitor cannot carry a file field — a file's own scope is one of those three, so
138
+ * there is nothing to attribute the bytes to, and the upload refuses that scope by name rather than
139
+ * pretending to support it.
140
+ *
141
+ * **Within the schema, a file field may nest inside objects, arrays and DISCRIMINATED unions.** It
142
+ * may NOT sit inside a record, a map, a set, a tuple, or a plain (non-discriminated) union — the
143
+ * walker that finds file fields refuses those shapes. Where variants are needed, use a discriminated
144
+ * union.
145
+ *
146
+ * **A field carried on several branches of a discriminated union must declare IDENTICAL options on
147
+ * every branch.** Differing options at one path are a conflict the framework refuses rather than
148
+ * choosing between, so a branch that quietly widens `maxSize` or changes `allowedMimeTypes` fails
149
+ * the schema instead of silently winning.
150
+ *
151
+ * ## Uploading is not attaching
152
+ *
153
+ * The generated upload route creates a FILE ROW. Attaching it to a business record is that record's
154
+ * own write, with its own authority. So an uploaded-but-never-submitted file is a real state a
155
+ * caller can produce; the cleanup sweep is what handles it.
156
+ *
157
+ * ## Declaring `imageConstraints.aspectRatio` turns the cropper on
158
+ *
159
+ * That option is the switch for the browser-side crop step — nothing else is wired. It applies to
160
+ * single-file fields only: a `multiple` field keeps the plain upload path. Vector images and
161
+ * formats the browser cannot decode bypass the cropper and upload the original, so the server-side
162
+ * constraint stays the authority.
163
+ *
134
164
  * @param options - Configuration options for file field
135
165
  * @returns A Zod object schema with metadata for file detection
136
166
  */
@@ -157,11 +187,15 @@ export function createFileSchema(options = {}) {
157
187
  console.warn('[z_file] filePathBinding.fileName is set on a multiple file field — fileName is ignored for multiple uploads. ' +
158
188
  'Use filePathBinding.multipleFilePolicy.fileNameTemplate instead.');
159
189
  }
160
- const implicitOrExplicitS3 = !storageAccepted || storageAccepted.includes(FileStorageAccepted.WILDO_MANAGED);
161
- const localIncluded = storageAccepted?.includes(FileStorageAccepted.LOCAL_DIRECTORY);
162
- if (filePathBinding.includeApplicationId === false && implicitOrExplicitS3 && !localIncluded) {
163
- console.warn('[z_file] filePathBinding.includeApplicationId is false with WILDO_MANAGED storage. ' +
164
- 'S3 keys will not be scoped by applicationId — ensure cross-app collision is acceptable.');
190
+ // Warned for EVERY provider, not only WILDO_MANAGED. The condition used to exempt a field that
191
+ // named LOCAL_DIRECTORY, because that provider defaulted to `false` anyway and the warning would
192
+ // have fired on its own default. Both providers now default to `true` and both honour `false`
193
+ // identically, so `false` is an explicit opt-out of the tenant-scoped key shape wherever it is
194
+ // authored — and that is the thing worth saying out loud.
195
+ if (filePathBinding.includeApplicationId === false) {
196
+ console.warn('[z_file] filePathBinding.includeApplicationId is false. Storage keys for this field will carry ' +
197
+ 'NO applications/<appId>/files/<resource>/<scope>/<scopeId>/ prefix, so per-tenant listing, ' +
198
+ 'erasure sweeps and prefix-confined credentials cannot address them — ensure that is intended.');
165
199
  }
166
200
  }
167
201
  // Resolve MIME type groups to actual MIME types
@@ -1 +1 @@
1
- {"version":3,"file":"zod-file.js","sourceRoot":"","sources":["../../../src/zod-file.ts"],"names":[],"mappings":"AACA,+EAA+E;AAC/E,qBAAqB;AACrB,+EAA+E;AAG/E,OAAO,EAEL,eAAe,EAIf,kBAAkB,EAElB,UAAU,EACV,iBAAiB,EACjB,uBAAuB,EACvB,oBAAoB,EAGpB,mBAAmB,EAMnB,oBAAoB,EAEpB,YAAY,EAEb,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,mBAAmB,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AAC3E,OAAO,EAAE,yBAAyB,EAAE,MAAM,0BAA0B,CAAC;AAKrE;;;GAGG;AACH,MAAM,uBAAuB,GAAG,IAAI,GAAG,E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C,OAAO,CAAC,CAAC,CAAC,oBAAoB,CAAC,QAAQ;KACpF,CAAC;IAEF,MAAM,0BAA0B,GAAG,qBAAqB,KAAK,uBAAuB,CAAC,IAAI,CAAC;IAC1F,MAAM,wBAAwB,GAAG,mBAAmB,CAAC,MAAM,KAAK,oBAAoB,CAAC,OAAO,CAAC;IAE7F,IAAI,YAAY,IAAI,CAAC,CAAC,0BAA0B,IAAI,CAAC,wBAAwB,CAAC,EAAE,CAAC;QAC/E,OAAO,EAAE,YAAY,EAAE,qBAAqB,EAAE,UAAU,EAAE,mBAAmB,EAAE,aAAa,EAAE,QAAQ,EAAE,KAAK,EAAE,CAAC;IAClH,CAAC;IAED,OAAO;QACL,YAAY,EAAE,0BAA0B,CAAC,CAAC,CAAC,uBAAuB,CAAC,IAAI,CAAC,CAAC,CAAC,qBAAqB;QAC/F,UAAU,EAAE,wBAAwB,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,oBAAoB,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,mBAAmB;QACtG,aAAa;QACb,QAAQ,EAAE,IAAI;QACd,iBAAiB,EACf,oBAAoB,aAAa,GAAG,QAAQ,CAAC,CAAC,CAAC,KAAK,QAAQ,GAAG,CAAC,CAAC,CAAC,EAAE,IAAI;cACtE,GAAG,0BAA0B,CAAC,CAAC,CAAC,gBAAgB,qBAAqB,SAAS,CAAC,CAAC,CAAC,EAAE,EAAE;cACrF,GAAG,0BAA0B,IAAI,wBAAwB,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE;cACvE,GAAG,wBAAwB,CAAC,CAAC,CAAC,+BAA+B,CAAC,CAAC,CAAC,EAAE,EAAE;KACzE,CAAC;AACJ,CAAC","sourcesContent":["\n// ============================================================================\n// FILE SCHEMA HELPER\n// ============================================================================\n\n\nimport {\n DecoratorInput,\n SCHEMA_METADATA,\n CustomFieldMetadata,\n FileSchemaMetadata,\n FileSchemaOptions,\n FileMimeTypeGroups,\n FileMimeTypeGroup,\n FileNature,\n FileDisplayNature,\n FileDisplayPresentation,\n FileActivationPolicy,\n type FileActivationConfig,\n type FileUIDisplayParams,\n FileStorageAccepted,\n FileNatureConstraints_Image,\n FileNatureConstraints_Video,\n FileNatureConstraints_Audio,\n FileNatureConstraints_Document,\n FileGenerationConfig,\n FileGenerationSource,\n RagSourceConfiguration,\n ZodDecorator,\n ZodDecorator_ParamsType\n} from \"./zod-decorators.types\";\nimport { z } from \"zod\";\nimport { addChainableMethods, addDecorators } from \"./zod.module-override\";\nimport { UnifiedFileFormatRegistry } from \"./files/unified-registry\";\n\n// Minimal console declaration — avoids pulling in 'dom' or '@types/node' into this shared lib\ndeclare const console: { warn(...args: unknown[]): void };\n\n/**\n * Deduplicated warning tracker for unsupported storage providers.\n * Prevents console spam when the same schema is created multiple times (e.g., in tests or HMR).\n */\nconst _warnedStorageProviders = new Set<string>();\nconst _supportedProviders = new Set([FileStorageAccepted.WILDO_MANAGED, FileStorageAccepted.LOCAL_DIRECTORY]);\nconst GENERATED_PDF_MIME_TYPES = ['application/pdf'] as const;\nconst GENERATION_METADATA_KEYS = new Set(['source', 'templateId']);\n\n/**\n * Single file value type - represents a single file reference stored in the database.\n * The actual file is stored in a file storage system, this object references it.\n */\nexport interface SingleFileValue {\n /** File ID (foreign key to file storage) */\n fileId: string;\n /** Last update timestamp */\n updatedAt: Date;\n\n}\n\n/**\n * Multiple files value type - represents multiple file references stored in the database.\n */\nexport interface MultipleFileValue {\n /** File IDs (foreign keys to file storage) */\n fileIds: string[];\n /** Last update timestamp */\n updatedAt: Date;\n}\n\n/**\n * File value type - can be single or multiple depending on schema configuration.\n */\nexport type FileValue = SingleFileValue | MultipleFileValue;\n\n/**\n * Zod schema for SingleFileValue.\n */\nexport const SingleFileValueSchema: z.ZodObject<{ fileId: z.ZodString; updatedAt: z.ZodDate }> = z.object({\n fileId: z.string().min(1),\n updatedAt: z.date(),\n});\n\n/**\n * Zod schema for MultipleFileValue.\n */\nexport const MultipleFileValueSchema: z.ZodObject<{ fileIds: z.ZodArray<z.ZodString>; updatedAt: z.ZodDate }> = z.object({\n fileIds: z.array(z.string().min(1)),\n updatedAt: z.date(),\n});\n\n\n/**\n * Resolve MIME type groups to actual MIME types.\n * Handles both single group names and arrays of groups/MIME types.\n */\nexport function resolveMimeTypes(\n allowedMimeTypes: string[] | FileMimeTypeGroup | FileMimeTypeGroup[] | undefined\n): string[] | undefined {\n if (!allowedMimeTypes) return undefined;\n\n // If it's a single group name\n if (typeof allowedMimeTypes === 'string') {\n if (allowedMimeTypes in FileMimeTypeGroups) {\n return [...FileMimeTypeGroups[allowedMimeTypes as FileMimeTypeGroup]];\n }\n // Single MIME type\n return [allowedMimeTypes];\n }\n\n // If it's an array\n if (Array.isArray(allowedMimeTypes)) {\n const resolved: string[] = [];\n for (const item of allowedMimeTypes) {\n if (item in FileMimeTypeGroups) {\n // It's a group name\n resolved.push(...FileMimeTypeGroups[item as FileMimeTypeGroup]);\n } else {\n // It's a MIME type\n resolved.push(item);\n }\n }\n // Remove duplicates\n return [...new Set(resolved)];\n }\n\n return undefined;\n}\n\nfunction assertValidFileGenerationConfig(generation: FileGenerationConfig): void {\n const rawGeneration = generation as unknown as Record<string, unknown> | undefined;\n if (!rawGeneration || typeof rawGeneration !== 'object' || Array.isArray(rawGeneration)) {\n throw new Error('[z_file] generation must be an object.');\n }\n\n const extraKeys = Object.keys(rawGeneration).filter((key) => !GENERATION_METADATA_KEYS.has(key));\n if (extraKeys.length > 0) {\n throw new Error(\n `[z_file] generation contains unsupported key(s): ${extraKeys.join(', ')}. ` +\n 'Use only { source: FileGenerationSource.PDF_TEMPLATE, templateId }.'\n );\n }\n\n if (rawGeneration.source !== FileGenerationSource.PDF_TEMPLATE) {\n throw new Error('[z_file] generation.source must be FileGenerationSource.PDF_TEMPLATE.');\n }\n\n if (typeof rawGeneration.templateId !== 'string' || rawGeneration.templateId.trim().length === 0) {\n throw new Error('[z_file] generation.templateId must be a non-empty string.');\n }\n}\n\nfunction assertGeneratedPdfFileOptions(params: {\n generation?: FileGenerationConfig;\n multiple: boolean;\n resolvedMimeTypes?: string[];\n overridable: boolean;\n ragSource?: RagSourceConfiguration;\n scanPolicy?: unknown;\n}): void {\n if (!params.generation) return;\n\n assertValidFileGenerationConfig(params.generation);\n\n if (params.multiple) {\n throw new Error('[z_file] PDF template generation supports single-file fields only.');\n }\n\n if (params.overridable === false) {\n throw new Error('[z_file] PDF template generation requires overridable to remain true so framework REGENERATE can replace the generated file.');\n }\n\n // Re-expression of the pre-Phase-0 `rag` refusal against the shared decorator: a PDF-template\n // output is framework-RENDERED presentation of resource data the corpus can already reach at the\n // source fields — chunking the rendering would index the same facts twice, keyed to a file the\n // next REGENERATE silently replaces.\n if (params.ragSource) {\n throw new Error('[z_file] PDF template generation cannot be combined with RAG ingestion options.');\n }\n\n if (params.scanPolicy) {\n throw new Error('[z_file] PDF template generation cannot be combined with upload scanPolicy options.');\n }\n\n if (\n params.resolvedMimeTypes !== undefined &&\n (params.resolvedMimeTypes.length !== 1 || params.resolvedMimeTypes[0] !== GENERATED_PDF_MIME_TYPES[0])\n ) {\n throw new Error('[z_file] PDF template generation requires allowedMimeTypes to resolve exactly to application/pdf.');\n }\n}\n\n/**\n * z_file() - Creates file schemas for file uploads.\n *\n * File values are stored as: { fileId: string, updatedAt: Date }\n * - fileId: Reference to the file in storage (foreign key, indexed)\n * - updatedAt: When the file was last updated\n *\n * @example\n * ```typescript\n * import { z_file } from '@wildo-ai/zod-decorators';\n *\n * const avatar = z_file();\n * const document = z_file({ allowedMimeTypes: 'Documents' });\n * const images = z_file({\n * allowedMimeTypes: 'Images',\n * maxSize: 5 * 1024 * 1024, // 5MB\n * overridable: true\n * });\n *\n * // With decorators (chainable)\n * z_file().fileUI({ edit: { editMode: FileEditMode.DROPZONE } })\n * z_file({ allowedMimeTypes: ['Images', 'PDF'] }).isHidden({ edit: true })\n * ```\n */\n\n/**\n * @wildo_source:part:start zod.decorators.file-schema\n *\n * Creates a file schema with metadata for detection and form component rendering.\n *\n * @param options - Configuration options for file field\n * @returns A Zod object schema with metadata for file detection\n */\nexport function createFileSchema(\n options: FileSchemaOptions = {}\n): DecoratedFileSchema | DecoratedMultipleFileSchema {\n const {\n overridable = true,\n allowedMimeTypes,\n maxSize,\n minSize,\n multiple = false,\n maxFiles,\n nature,\n storageAccepted,\n filePathBinding,\n generation,\n imageConstraints,\n videoConstraints,\n audioConstraints,\n documentConstraints,\n ragSource,\n textExtraction,\n scanPolicy,\n onParentDelete = 'cascade',\n sharable,\n sharableDefaults,\n } = options;\n\n // Warn at schema creation if non-WILDO_MANAGED storage providers are configured (not yet supported)\n // Uses deduplication to avoid console spam during tests or HMR\n if (storageAccepted && storageAccepted.some(s => !_supportedProviders.has(s))) {\n const unsupported = storageAccepted.filter(s => !_supportedProviders.has(s));\n const warnKey = unsupported.sort().join(',');\n if (!_warnedStorageProviders.has(warnKey)) {\n _warnedStorageProviders.add(warnKey);\n console.warn(\n `[z_file] storageAccepted contains unsupported providers: ${unsupported.join(', ')}. ` +\n `Only '${FileStorageAccepted.WILDO_MANAGED}' and '${FileStorageAccepted.LOCAL_DIRECTORY}' are currently implemented. ` +\n `External storage providers (OneDrive, Google Drive, Dropbox) will be ignored until their integrations are available.`\n );\n }\n }\n\n if (filePathBinding) {\n if (filePathBinding.multipleFilePolicy && !multiple) {\n console.warn(\n '[z_file] filePathBinding.multipleFilePolicy is set but multiple is false — multipleFilePolicy will be ignored. ' +\n 'Either set multiple: true or remove multipleFilePolicy.'\n );\n }\n if (filePathBinding.fileName && multiple) {\n console.warn(\n '[z_file] filePathBinding.fileName is set on a multiple file field — fileName is ignored for multiple uploads. ' +\n 'Use filePathBinding.multipleFilePolicy.fileNameTemplate instead.'\n );\n }\n const implicitOrExplicitS3 = !storageAccepted || storageAccepted.includes(FileStorageAccepted.WILDO_MANAGED);\n const localIncluded = storageAccepted?.includes(FileStorageAccepted.LOCAL_DIRECTORY);\n if (filePathBinding.includeApplicationId === false && implicitOrExplicitS3 && !localIncluded) {\n console.warn(\n '[z_file] filePathBinding.includeApplicationId is false with WILDO_MANAGED storage. ' +\n 'S3 keys will not be scoped by applicationId — ensure cross-app collision is acceptable.'\n );\n }\n }\n\n // Resolve MIME type groups to actual MIME types\n const resolvedMimeTypes = resolveMimeTypes(allowedMimeTypes);\n assertGeneratedPdfFileOptions({ generation, multiple, resolvedMimeTypes, overridable, ragSource, scanPolicy });\n const effectiveMimeTypes = generation ? [...GENERATED_PDF_MIME_TYPES] : resolvedMimeTypes;\n\n // Create the file object schema based on single/multiple\n const fileSchema = multiple\n ? z.object({\n fileIds: z.array(z.string().min(1)),\n updatedAt: z.date(),\n })\n : z.object({\n fileId: z.string().min(1),\n updatedAt: z.date(),\n });\n\n // No longer stored in metadata — consumers derive accept from allowedMimeTypes via buildAcceptAttribute()\n\n // Store file metadata in SCHEMA_METADATA.fileConfig\n const fileMetadata: FileSchemaMetadata = {\n isFile: true,\n overridable,\n ...(effectiveMimeTypes !== undefined && { allowedMimeTypes: effectiveMimeTypes }),\n ...(maxSize !== undefined && { maxSize }),\n ...(minSize !== undefined && { minSize }),\n multiple,\n ...(maxFiles !== undefined && { maxFiles }),\n ...(nature !== undefined && { nature }),\n ...(storageAccepted !== undefined && { storageAccepted }),\n ...(filePathBinding !== undefined && { filePathBinding }),\n ...(generation !== undefined && { generation }),\n ...(imageConstraints !== undefined && { imageConstraints }),\n ...(videoConstraints !== undefined && { videoConstraints }),\n ...(audioConstraints !== undefined && { audioConstraints }),\n ...(documentConstraints !== undefined && { documentConstraints }),\n // Text-provider config only — the RAG declaration itself is NOT stored here (single source of\n // truth is the RAG_SOURCE decorator registered below; read it with `getRagSourceConfig`).\n ...(textExtraction !== undefined && { textExtraction }),\n ...(scanPolicy !== undefined && { scanPolicy }),\n onParentDelete,\n ...(sharable !== undefined && { sharable }),\n ...(sharableDefaults !== undefined && { sharableDefaults }),\n };\n\n // Initialize or extend SCHEMA_METADATA with file config\n const existingMetadata: CustomFieldMetadata = (fileSchema as any)[SCHEMA_METADATA] || {};\n (fileSchema as any)[SCHEMA_METADATA] = {\n ...existingMetadata,\n fileConfig: fileMetadata,\n };\n\n // Add chainable decorator methods to the file schema instance\n addChainableMethods(fileSchema);\n\n // Map the file-side `ragSource` option onto the SHARED RAG_SOURCE decorator — the same one\n // `z.string().ragSource()` registers — so `RagSourceFieldDetection` sees one uniform declaration\n // regardless of text provider. Registered through `addDecorators` (the escape-hatch door) because\n // the fluent `.ragSource()` is deliberately not installed on ZodObject; the shared chokepoint\n // still validates the config and enforces the refused companions identically.\n if (ragSource !== undefined) {\n addDecorators(fileSchema, [{ ref: ZodDecorator.RAG_SOURCE, params: ragSource }]);\n }\n\n if (multiple) {\n return fileSchema as unknown as DecoratedMultipleFileSchema;\n }\n return fileSchema as unknown as DecoratedFileSchema;\n}\n\n/**\n * File schemas declare NO decorator surface of their own.\n *\n * They used to, via a `FileSchemaDecoratorMethods<TSelf>` mixin that re-declared `isDBIndexed`,\n * `isHidden`, `isNotEditable` and `showWhen` with the return narrowed to the file schema — necessary\n * only because the `ZodObject` module augmentation did not carry them. It now does (2026-08-12), and\n * re-declaring them made both interfaces below fail TS2320: an interface may not extend two types\n * whose same-named member differs, and `TSelf` is not `DecoratedPrimitiveZodType<this>`.\n *\n * Removing the mixin costs nothing, because `DecoratedPrimitiveZodType<T>` is `T & { … }` — an\n * INTERSECTION. `z_file().isHidden()` still returns something assignable to `DecoratedFileSchema`,\n * and the full decorator surface is now available rather than the four this mixin listed.\n */\n\n/**\n * Return type for single file schemas - includes decorator methods.\n * IS_DB_INDEXED will index the fileId field for query optimization.\n *\n * Uses `interface` instead of `type` to allow self-referencing without circular alias errors.\n */\nexport interface DecoratedFileSchema extends z.ZodObject<{\n fileId: z.ZodString;\n updatedAt: z.ZodDate;\n}> {}\n\n/**\n * Return type for multiple file schemas - includes decorator methods.\n * IS_DB_INDEXED will index the fileIds array for query optimization.\n *\n * Uses `interface` instead of `type` to allow self-referencing without circular alias errors.\n */\nexport interface DecoratedMultipleFileSchema extends z.ZodObject<{\n fileIds: z.ZodArray<z.ZodString>;\n updatedAt: z.ZodDate;\n}> {}\n\n/**\n * Creates a file schema for file uploads with reference storage.\n * Named z_file to indicate it's a Zod helper function exported standalone.\n *\n * Single file values are stored as: { fileId: string, updatedAt: Date }\n * Multiple file values are stored as: { fileIds: string[], updatedAt: Date }\n *\n * @example\n * ```typescript\n * import { z_file } from '@wildo-ai/zod-decorators';\n *\n * // Simple usage - single file, any type\n * z_file()\n *\n * // With MIME type groups (shortcuts)\n * z_file({ allowedMimeTypes: 'Images' })\n * z_file({ allowedMimeTypes: 'PDF' })\n * z_file({ allowedMimeTypes: ['Images', 'Video'] })\n * z_file({ allowedMimeTypes: 'Documents' }) // PDF + Office\n *\n * // With specific MIME types\n * z_file({ allowedMimeTypes: ['image/png', 'image/jpeg'] })\n *\n * // With size constraints\n * z_file({ maxSize: 10 * 1024 * 1024 }) // 10MB max\n *\n * // Multiple files (uses fileIds instead of fileId)\n * z_file({ multiple: true, maxFiles: 5 })\n *\n * // Non-overridable (append-only)\n * z_file({ overridable: false })\n *\n * // RAG corpus source — registers the shared RAG_SOURCE decorator on the returned schema\n * // (chunking config), with the file-side text-provider knobs beside it (OCR opt-in).\n * z_file({ allowedMimeTypes: 'Documents', ragSource: {}, textExtraction: { ocr: true } })\n *\n * // With decorators\n * z_file().fileUI({ edit: { editMode: FileEditMode.DROPZONE } })\n * z_file().isHidden({ display: true })\n * ```\n */\nexport function z_file(options?: FileSchemaOptions): DecoratedFileSchema | DecoratedMultipleFileSchema {\n return createFileSchema(options);\n}\n/** @wildo_source:part:end zod.decorators.file-schema */\n\n// ============================================================================\n// UTILITY FUNCTIONS\n// ============================================================================\n\n/**\n * Format file size for display.\n */\nexport function formatFileSize(bytes: number): string {\n if (!Number.isFinite(bytes)) return '—';\n if (bytes === 0) return '0 B';\n if (bytes < 0) return '-' + formatFileSize(Math.abs(bytes));\n\n const units = ['B', 'KB', 'MB', 'GB', 'TB'];\n const k = 1024;\n const i = Math.floor(Math.log(bytes) / Math.log(k));\n\n return `${parseFloat((bytes / Math.pow(k, i)).toFixed(2))} ${units[i]}`;\n}\n\n/**\n * Build enhanced accept attribute string from MIME types.\n * Includes both MIME types and extensions for better browser compatibility.\n * Format: \"image/*,.jpg,.jpeg,.png\" or \"application/pdf,.pdf\"\n *\n * @param mimeTypes - Array of MIME type strings\n * @returns Accept attribute string with MIME types and extensions\n */\nexport function buildAcceptAttribute(mimeTypes: string[]): string {\n if (!mimeTypes || mimeTypes.length === 0) return '';\n\n const parts = new Set<string>();\n const extensions = new Set<string>();\n\n for (const mimeType of mimeTypes) {\n // Add MIME type\n parts.add(mimeType);\n\n // Get extensions for this MIME type\n const mimeExtensions = UnifiedFileFormatRegistry.getExtensions(mimeType);\n for (const ext of mimeExtensions) {\n if (ext) {\n extensions.add(`.${ext}`);\n }\n }\n\n // Also check if it's a wildcard MIME type (e.g., image/*)\n // In that case, get all extensions for that nature\n if (mimeType.endsWith('/*')) {\n const formatType = UnifiedFileFormatRegistry.getFormatTypeFromMimeType(mimeType);\n\n if (formatType && formatType.type === 'nature') {\n const natureExtensions = UnifiedFileFormatRegistry.getExtensionsForNature(formatType.nature);\n for (const ext of natureExtensions) {\n if (ext) {\n extensions.add(`.${ext}`);\n }\n }\n }\n }\n }\n\n // Combine MIME types and extensions\n const allParts = [...parts, ...extensions];\n return allParts.join(',');\n}\n\n/**\n * Get file extension from filename.\n * Uses UnifiedFileFormatRegistry for consistency.\n */\nexport function getFileExtension(filename: string): string {\n return UnifiedFileFormatRegistry.getFileExtension(filename);\n}\n\n/**\n * Check if a MIME type is allowed based on allowed types.\n */\nexport function isMimeTypeAllowed(mimeType: string, allowedMimeTypes?: string[]): boolean {\n if (!allowedMimeTypes || allowedMimeTypes.length === 0) return true;\n\n // Check exact match\n if (allowedMimeTypes.includes(mimeType)) return true;\n\n // Check wildcard match (e.g., \"image/*\")\n const [type] = mimeType.split('/');\n if (allowedMimeTypes.includes(`${type}/*`)) return true;\n\n return false;\n}\n\n/**\n * Get a human-readable description of allowed file types.\n * Uses UnifiedFileFormatRegistry for better format detection.\n */\nexport function getAcceptDescription(allowedMimeTypes?: string[]): string {\n if (!allowedMimeTypes || allowedMimeTypes.length === 0) return 'All files';\n\n const types = new Set<string>();\n\n for (const mime of allowedMimeTypes) {\n // Use registry to detect format type\n const formatType = UnifiedFileFormatRegistry.getFormatTypeFromMimeType(mime);\n\n if (formatType) {\n if (formatType.type === 'nature') {\n // Map FileNature to human-readable names\n const natureNames: Record<string, string> = {\n [FileNature.IMAGE]: 'Images',\n [FileNature.VIDEO]: 'Videos',\n [FileNature.AUDIO]: 'Audio files',\n [FileNature.PDF]: 'PDF',\n [FileNature.OFFICE]: 'Office documents',\n [FileNature.ARCHIVE]: 'Archives',\n };\n const name = natureNames[formatType.nature];\n if (name) {\n types.add(name);\n continue;\n }\n } else if (formatType.type === 'agent') {\n // Map agent formats to human-readable names\n const agentNames: Record<string, string> = {\n 'text': 'Text files',\n 'markdown': 'Markdown',\n 'json': 'JSON',\n 'typescript': 'TypeScript',\n 'typescript_react': 'TypeScript React',\n 'yaml': 'YAML',\n };\n const name = agentNames[formatType.format] || formatType.format.replace(/_/g, ' ').replace(/\\b\\w/g, l => l.toUpperCase());\n types.add(name);\n continue;\n }\n }\n\n // Fallback: use MIME type patterns\n if (mime === 'application/pdf') {\n types.add('PDF');\n } else if (mime.startsWith('image/')) {\n types.add('Images');\n } else if (mime.startsWith('video/')) {\n types.add('Videos');\n } else if (mime.startsWith('audio/')) {\n types.add('Audio');\n } else if (mime.includes('document') || mime.includes('word') || mime.includes('excel') || mime.includes('powerpoint')) {\n types.add('Office documents');\n } else {\n // Get extension-like description\n const ext = mime.split('/').pop()?.toUpperCase();\n if (ext) types.add(ext);\n }\n }\n\n return Array.from(types).join(', ') || 'Selected file types';\n}\n\n/**\n * Get file nature from schema metadata.\n * @param schema - Zod schema (must be a file schema)\n * @returns FileNature or undefined if not set\n */\nexport function getFileNature(schema: z.ZodTypeAny): FileNature | undefined {\n const metadata = (schema as any)[SCHEMA_METADATA] as CustomFieldMetadata | undefined;\n return metadata?.fileConfig?.nature;\n}\n\n/**\n * Get storage accepted from schema metadata.\n * @param schema - Zod schema (must be a file schema)\n * @returns Array of FileStorageAccepted or undefined if not set\n */\nexport function getStorageAccepted(schema: z.ZodTypeAny): FileStorageAccepted[] | undefined {\n const metadata = (schema as any)[SCHEMA_METADATA] as CustomFieldMetadata | undefined;\n return metadata?.fileConfig?.storageAccepted;\n}\n\n/**\n * Get file constraints from schema metadata.\n * @param schema - Zod schema (must be a file schema)\n * @returns Object with all constraint properties or undefined if not set\n */\nexport function getFileConstraints(schema: z.ZodTypeAny): {\n imageConstraints?: FileNatureConstraints_Image;\n videoConstraints?: FileNatureConstraints_Video;\n audioConstraints?: FileNatureConstraints_Audio;\n documentConstraints?: FileNatureConstraints_Document;\n} | undefined {\n const metadata = (schema as any)[SCHEMA_METADATA] as CustomFieldMetadata | undefined;\n const fileConfig = metadata?.fileConfig;\n if (!fileConfig) return undefined;\n\n const hasConstraints =\n fileConfig.imageConstraints ||\n fileConfig.videoConstraints ||\n fileConfig.audioConstraints ||\n fileConfig.documentConstraints;\n\n if (!hasConstraints) return undefined;\n\n return {\n ...(fileConfig.imageConstraints && { imageConstraints: fileConfig.imageConstraints }),\n ...(fileConfig.videoConstraints && { videoConstraints: fileConfig.videoConstraints }),\n ...(fileConfig.audioConstraints && { audioConstraints: fileConfig.audioConstraints }),\n ...(fileConfig.documentConstraints && { documentConstraints: fileConfig.documentConstraints }),\n };\n}\n\n// ============================================================================\n// DISPLAY NATURE RESOLUTION\n// ============================================================================\n\n/**\n * Mapping from schema-level `FileNature` to rendering-level `FileDisplayNature`.\n *\n * PDF and OFFICE both render as DOCUMENT.\n * ARCHIVE and ALL are GENERIC (no specialized renderer).\n */\nconst FILE_NATURE_TO_DISPLAY_NATURE: Record<FileNature, FileDisplayNature> = {\n [FileNature.IMAGE]: FileDisplayNature.IMAGE,\n [FileNature.VIDEO]: FileDisplayNature.VIDEO,\n [FileNature.AUDIO]: FileDisplayNature.AUDIO,\n [FileNature.PDF]: FileDisplayNature.DOCUMENT,\n [FileNature.OFFICE]: FileDisplayNature.DOCUMENT,\n [FileNature.ARCHIVE]: FileDisplayNature.GENERIC,\n [FileNature.ALL]: FileDisplayNature.GENERIC,\n};\n\n/**\n * Detect `FileDisplayNature` from a MIME type string.\n *\n * Used as a fallback when no `FileNature` is declared in schema metadata.\n */\nfunction detectDisplayNatureFromMimeType(mimeType: string): FileDisplayNature {\n if (mimeType.startsWith('image/')) return FileDisplayNature.IMAGE;\n if (mimeType.startsWith('video/')) return FileDisplayNature.VIDEO;\n if (mimeType.startsWith('audio/')) return FileDisplayNature.AUDIO;\n if (\n mimeType === 'application/pdf' ||\n mimeType.includes('document') || mimeType.includes('word') ||\n mimeType.includes('spreadsheet') || mimeType.includes('excel') ||\n mimeType.includes('presentation') || mimeType.includes('powerpoint')\n ) return FileDisplayNature.DOCUMENT;\n return FileDisplayNature.GENERIC;\n}\n\n/**\n * Resolve the rendering-level display nature for a file.\n *\n * Resolution priority:\n * 1. `schemaNature` (from `z_file({ nature: ... })` metadata) → mapped via `FILE_NATURE_TO_DISPLAY_NATURE`\n * 2. `mimeType` (from file metadata or browser File object) → detected via MIME prefix matching\n * 3. `FileDisplayNature.GENERIC` (fallback)\n *\n * @param schemaNature - The `FileNature` declared in schema metadata (from `getFileMetadata(schema)?.nature`)\n * @param mimeType - The MIME type of the actual file\n * @returns The `FileDisplayNature` to use for rendering\n *\n * @example\n * ```typescript\n * const displayNature = resolveFileDisplayNature(fileSchemaMetadata?.nature, metadata.mimeType)\n * // FileDisplayNature.IMAGE | .VIDEO | .AUDIO | .DOCUMENT | .GENERIC\n * ```\n */\nexport function resolveFileDisplayNature(\n schemaNature?: FileNature,\n mimeType?: string,\n): FileDisplayNature {\n // Priority 1: Schema-declared nature\n if (schemaNature) {\n return FILE_NATURE_TO_DISPLAY_NATURE[schemaNature] ?? FileDisplayNature.GENERIC;\n }\n // Priority 2: MIME type detection\n if (mimeType) {\n return detectDisplayNatureFromMimeType(mimeType);\n }\n // Priority 3: Fallback\n return FileDisplayNature.GENERIC;\n}\n\n// ============================================================================\n// DISPLAY POLICY RESOLUTION (presentation × activation, + the availability guard)\n// ============================================================================\n\n/**\n * Whether the engine can RENDER a file of this nature/MIME (i.e. whether\n * `THUMBNAIL` / `FULL` presentation and `OVERLAY` activation are satisfiable).\n *\n * Nature alone is not always enough: `DOCUMENT` covers PDF *and* Office, and only\n * PDF has a viewer — so the MIME decides when it is known. Extend this (and only\n * this) when a new displayer ships; every guard tier reads it, so availability can\n * never drift between the static and runtime answers.\n */\nexport function fileNatureHasDisplayer(\n displayNature: FileDisplayNature,\n mimeType?: string,\n): boolean {\n switch (displayNature) {\n case FileDisplayNature.IMAGE:\n case FileDisplayNature.VIDEO:\n case FileDisplayNature.AUDIO:\n return true;\n case FileDisplayNature.DOCUMENT:\n // PDF renders (PDF.js); Office documents have no viewer yet. With no MIME\n // known (the static tier on a declared PDF nature) the answer is yes,\n // because `FileNature.PDF` maps here only for PDFs.\n return mimeType === undefined || mimeType === 'application/pdf';\n case FileDisplayNature.GENERIC:\n return false;\n }\n}\n\n/**\n * Whether a DECLARED schema nature can satisfy a display-requiring policy, decided\n * WITHOUT a MIME type. This is the static (registry-build) tier of the guard.\n *\n * Returns `undefined` for `FileNature.ALL` — genuinely undecidable before the file\n * exists, so the static tier must admit it and the runtime tier decides. Any other\n * nature yields a definite answer, which is what lets a misauthored\n * `ARCHIVE` + `FULL` fail at build instead of rendering nothing at runtime.\n */\nexport function declaredFileNatureCanDisplay(schemaNature: FileNature): boolean | undefined {\n if (schemaNature === FileNature.ALL) return undefined;\n return fileNatureHasDisplayer(FILE_NATURE_TO_DISPLAY_NATURE[schemaNature] ?? FileDisplayNature.GENERIC);\n}\n\n/** Outcome of {@link resolveFileDisplayPolicy}. */\nexport interface ResolvedFileDisplayPolicy {\n /** Effective resting presentation after the availability guard. */\n presentation: FileDisplayPresentation;\n /** Effective activation after the availability guard. */\n activation: FileActivationConfig;\n /** The nature the effective policy was resolved against. */\n displayNature: FileDisplayNature;\n /** True when the authored policy could not be satisfied and was degraded. */\n degraded: boolean;\n /** Human-readable cause, for the dev-only warning. Set iff `degraded`. */\n degradationReason?: string;\n}\n\n/**\n * Resolve the effective file display policy — the RUNTIME tier of the guard.\n *\n * Defaults, when nothing is authored: `CARD` presentation, and an activation derived\n * from the nature (`OVERLAY` when a displayer exists, `DOWNLOAD` otherwise) — so a\n * file is always useful without any authoring, and a document does not mount a\n * viewer just by being on the page.\n *\n * Degradation is deterministic, never a crash and never a dead control:\n * `FULL`/`THUMBNAIL` → `CARD`, `OVERLAY` → `DOWNLOAD`. It only fires when the file's\n * actual nature has no displayer — which is only reachable when the schema declared\n * an open nature (`FileNature.ALL`), because a narrow declared nature that cannot\n * display was already refused at registry build.\n *\n * `CUSTOM` is never degraded: it targets an operation, not a displayer, so displayer\n * availability is irrelevant to it.\n */\nexport function resolveFileDisplayPolicy(params: {\n schemaNature?: FileNature;\n mimeType?: string;\n authored?: FileUIDisplayParams;\n}): ResolvedFileDisplayPolicy {\n const { schemaNature, mimeType, authored } = params;\n const displayNature = resolveFileDisplayNature(schemaNature, mimeType);\n const hasDisplayer = fileNatureHasDisplayer(displayNature, mimeType);\n\n const requestedPresentation = authored?.presentation ?? FileDisplayPresentation.CARD;\n const requestedActivation: FileActivationConfig = authored?.activation ?? {\n policy: hasDisplayer ? FileActivationPolicy.OVERLAY : FileActivationPolicy.DOWNLOAD,\n };\n\n const presentationNeedsDisplayer = requestedPresentation !== FileDisplayPresentation.CARD;\n const activationNeedsDisplayer = requestedActivation.policy === FileActivationPolicy.OVERLAY;\n\n if (hasDisplayer || (!presentationNeedsDisplayer && !activationNeedsDisplayer)) {\n return { presentation: requestedPresentation, activation: requestedActivation, displayNature, degraded: false };\n }\n\n return {\n presentation: presentationNeedsDisplayer ? FileDisplayPresentation.CARD : requestedPresentation,\n activation: activationNeedsDisplayer ? { policy: FileActivationPolicy.DOWNLOAD } : requestedActivation,\n displayNature,\n degraded: true,\n degradationReason:\n `no displayer for ${displayNature}${mimeType ? ` (${mimeType})` : ''}: `\n + `${presentationNeedsDisplayer ? `presentation ${requestedPresentation} → card` : ''}`\n + `${presentationNeedsDisplayer && activationNeedsDisplayer ? ', ' : ''}`\n + `${activationNeedsDisplayer ? 'activation overlay → download' : ''}`,\n };\n}\n"]}
1
+ {"version":3,"file":"zod-file.js","sourceRoot":"","sources":["../../../src/zod-file.ts"],"names":[],"mappings":"AACA,+EAA+E;AAC/E,qBAAqB;AACrB,+EAA+E;AAG/E,OAAO,EAEL,eAAe,EAIf,kBAAkB,EAElB,UAAU,EACV,iBAAiB,EACjB,uBAAuB,EACvB,oBAAoB,EAGpB,mBAAmB,EAMnB,oBAAoB,EAEpB,YAAY,EAEb,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,mBAAmB,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AAC3E,OAAO,EAAE,yBAAyB,EAAE,MAAM,0BAA0B,CAAC;AAKrE;;;GAGG;AACH,MAAM,uBAAuB,GAAG,IAAI,GAAG,EAAU,CAAC;AAClD,MAAM,mBAAmB,GAAG,IAAI,GAAG,CAAC,CAAC,mBAAmB,CAAC,aAAa,EAAE,mBAAmB,CAAC,eAAe,CAAC,CAAC,CAAC;AAC9G,MAAM,wBAAwB,GAAG,CAAC,iBAAiB,CAAU,CAAC;AAC9D,MAAM,wBAAwB,GAAG,IAAI,GAAG,CAAC,CAAC,QAAQ,EAAE,YAAY,CAAC,CAAC,CAAC;AA6BnE;;GAEG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAA+D,CAAC,CAAC,MAAM,CAAC;IACxG,MAAM,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC;IACzB,SAAS,EAA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/F,UAAU,EAAE,wBAAwB,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,oBAAoB,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,mBAAmB;QACtG,aAAa;QACb,QAAQ,EAAE,IAAI;QACd,iBAAiB,EACf,oBAAoB,aAAa,GAAG,QAAQ,CAAC,CAAC,CAAC,KAAK,QAAQ,GAAG,CAAC,CAAC,CAAC,EAAE,IAAI;cACtE,GAAG,0BAA0B,CAAC,CAAC,CAAC,gBAAgB,qBAAqB,SAAS,CAAC,CAAC,CAAC,EAAE,EAAE;cACrF,GAAG,0BAA0B,IAAI,wBAAwB,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE;cACvE,GAAG,wBAAwB,CAAC,CAAC,CAAC,+BAA+B,CAAC,CAAC,CAAC,EAAE,EAAE;KACzE,CAAC;AACJ,CAAC","sourcesContent":["\n// ============================================================================\n// FILE SCHEMA HELPER\n// ============================================================================\n\n\nimport {\n DecoratorInput,\n SCHEMA_METADATA,\n CustomFieldMetadata,\n FileSchemaMetadata,\n FileSchemaOptions,\n FileMimeTypeGroups,\n FileMimeTypeGroup,\n FileNature,\n FileDisplayNature,\n FileDisplayPresentation,\n FileActivationPolicy,\n type FileActivationConfig,\n type FileUIDisplayParams,\n FileStorageAccepted,\n FileNatureConstraints_Image,\n FileNatureConstraints_Video,\n FileNatureConstraints_Audio,\n FileNatureConstraints_Document,\n FileGenerationConfig,\n FileGenerationSource,\n RagSourceConfiguration,\n ZodDecorator,\n ZodDecorator_ParamsType\n} from \"./zod-decorators.types\";\nimport { z } from \"zod\";\nimport { addChainableMethods, addDecorators } from \"./zod.module-override\";\nimport { UnifiedFileFormatRegistry } from \"./files/unified-registry\";\n\n// Minimal console declaration — avoids pulling in 'dom' or '@types/node' into this shared lib\ndeclare const console: { warn(...args: unknown[]): void };\n\n/**\n * Deduplicated warning tracker for unsupported storage providers.\n * Prevents console spam when the same schema is created multiple times (e.g., in tests or HMR).\n */\nconst _warnedStorageProviders = new Set<string>();\nconst _supportedProviders = new Set([FileStorageAccepted.WILDO_MANAGED, FileStorageAccepted.LOCAL_DIRECTORY]);\nconst GENERATED_PDF_MIME_TYPES = ['application/pdf'] as const;\nconst GENERATION_METADATA_KEYS = new Set(['source', 'templateId']);\n\n/**\n * Single file value type - represents a single file reference stored in the database.\n * The actual file is stored in a file storage system, this object references it.\n */\nexport interface SingleFileValue {\n /** File ID (foreign key to file storage) */\n fileId: string;\n /** Last update timestamp */\n updatedAt: Date;\n\n}\n\n/**\n * Multiple files value type - represents multiple file references stored in the database.\n */\nexport interface MultipleFileValue {\n /** File IDs (foreign keys to file storage) */\n fileIds: string[];\n /** Last update timestamp */\n updatedAt: Date;\n}\n\n/**\n * File value type - can be single or multiple depending on schema configuration.\n */\nexport type FileValue = SingleFileValue | MultipleFileValue;\n\n/**\n * Zod schema for SingleFileValue.\n */\nexport const SingleFileValueSchema: z.ZodObject<{ fileId: z.ZodString; updatedAt: z.ZodDate }> = z.object({\n fileId: z.string().min(1),\n updatedAt: z.date(),\n});\n\n/**\n * Zod schema for MultipleFileValue.\n */\nexport const MultipleFileValueSchema: z.ZodObject<{ fileIds: z.ZodArray<z.ZodString>; updatedAt: z.ZodDate }> = z.object({\n fileIds: z.array(z.string().min(1)),\n updatedAt: z.date(),\n});\n\n\n/**\n * Resolve MIME type groups to actual MIME types.\n * Handles both single group names and arrays of groups/MIME types.\n */\nexport function resolveMimeTypes(\n allowedMimeTypes: string[] | FileMimeTypeGroup | FileMimeTypeGroup[] | undefined\n): string[] | undefined {\n if (!allowedMimeTypes) return undefined;\n\n // If it's a single group name\n if (typeof allowedMimeTypes === 'string') {\n if (allowedMimeTypes in FileMimeTypeGroups) {\n return [...FileMimeTypeGroups[allowedMimeTypes as FileMimeTypeGroup]];\n }\n // Single MIME type\n return [allowedMimeTypes];\n }\n\n // If it's an array\n if (Array.isArray(allowedMimeTypes)) {\n const resolved: string[] = [];\n for (const item of allowedMimeTypes) {\n if (item in FileMimeTypeGroups) {\n // It's a group name\n resolved.push(...FileMimeTypeGroups[item as FileMimeTypeGroup]);\n } else {\n // It's a MIME type\n resolved.push(item);\n }\n }\n // Remove duplicates\n return [...new Set(resolved)];\n }\n\n return undefined;\n}\n\nfunction assertValidFileGenerationConfig(generation: FileGenerationConfig): void {\n const rawGeneration = generation as unknown as Record<string, unknown> | undefined;\n if (!rawGeneration || typeof rawGeneration !== 'object' || Array.isArray(rawGeneration)) {\n throw new Error('[z_file] generation must be an object.');\n }\n\n const extraKeys = Object.keys(rawGeneration).filter((key) => !GENERATION_METADATA_KEYS.has(key));\n if (extraKeys.length > 0) {\n throw new Error(\n `[z_file] generation contains unsupported key(s): ${extraKeys.join(', ')}. ` +\n 'Use only { source: FileGenerationSource.PDF_TEMPLATE, templateId }.'\n );\n }\n\n if (rawGeneration.source !== FileGenerationSource.PDF_TEMPLATE) {\n throw new Error('[z_file] generation.source must be FileGenerationSource.PDF_TEMPLATE.');\n }\n\n if (typeof rawGeneration.templateId !== 'string' || rawGeneration.templateId.trim().length === 0) {\n throw new Error('[z_file] generation.templateId must be a non-empty string.');\n }\n}\n\nfunction assertGeneratedPdfFileOptions(params: {\n generation?: FileGenerationConfig;\n multiple: boolean;\n resolvedMimeTypes?: string[];\n overridable: boolean;\n ragSource?: RagSourceConfiguration;\n scanPolicy?: unknown;\n}): void {\n if (!params.generation) return;\n\n assertValidFileGenerationConfig(params.generation);\n\n if (params.multiple) {\n throw new Error('[z_file] PDF template generation supports single-file fields only.');\n }\n\n if (params.overridable === false) {\n throw new Error('[z_file] PDF template generation requires overridable to remain true so framework REGENERATE can replace the generated file.');\n }\n\n // Re-expression of the pre-Phase-0 `rag` refusal against the shared decorator: a PDF-template\n // output is framework-RENDERED presentation of resource data the corpus can already reach at the\n // source fields — chunking the rendering would index the same facts twice, keyed to a file the\n // next REGENERATE silently replaces.\n if (params.ragSource) {\n throw new Error('[z_file] PDF template generation cannot be combined with RAG ingestion options.');\n }\n\n if (params.scanPolicy) {\n throw new Error('[z_file] PDF template generation cannot be combined with upload scanPolicy options.');\n }\n\n if (\n params.resolvedMimeTypes !== undefined &&\n (params.resolvedMimeTypes.length !== 1 || params.resolvedMimeTypes[0] !== GENERATED_PDF_MIME_TYPES[0])\n ) {\n throw new Error('[z_file] PDF template generation requires allowedMimeTypes to resolve exactly to application/pdf.');\n }\n}\n\n/**\n * z_file() - Creates file schemas for file uploads.\n *\n * File values are stored as: { fileId: string, updatedAt: Date }\n * - fileId: Reference to the file in storage (foreign key, indexed)\n * - updatedAt: When the file was last updated\n *\n * @example\n * ```typescript\n * import { z_file } from '@wildo-ai/zod-decorators';\n *\n * const avatar = z_file();\n * const document = z_file({ allowedMimeTypes: 'Documents' });\n * const images = z_file({\n * allowedMimeTypes: 'Images',\n * maxSize: 5 * 1024 * 1024, // 5MB\n * overridable: true\n * });\n *\n * // With decorators (chainable)\n * z_file().fileUI({ edit: { editMode: FileEditMode.DROPZONE } })\n * z_file({ allowedMimeTypes: ['Images', 'PDF'] }).isHidden({ edit: true })\n * ```\n */\n\n/**\n * @wildo_source:part:start zod.decorators.file-schema\n *\n * Creates a file schema with metadata for detection and form component rendering.\n *\n * ## Where a file field may be declared\n *\n * **The resource's primary scope must be application, organization or user.** A resource scoped to\n * an ANONYMOUS visitor cannot carry a file field — a file's own scope is one of those three, so\n * there is nothing to attribute the bytes to, and the upload refuses that scope by name rather than\n * pretending to support it.\n *\n * **Within the schema, a file field may nest inside objects, arrays and DISCRIMINATED unions.** It\n * may NOT sit inside a record, a map, a set, a tuple, or a plain (non-discriminated) union — the\n * walker that finds file fields refuses those shapes. Where variants are needed, use a discriminated\n * union.\n *\n * **A field carried on several branches of a discriminated union must declare IDENTICAL options on\n * every branch.** Differing options at one path are a conflict the framework refuses rather than\n * choosing between, so a branch that quietly widens `maxSize` or changes `allowedMimeTypes` fails\n * the schema instead of silently winning.\n *\n * ## Uploading is not attaching\n *\n * The generated upload route creates a FILE ROW. Attaching it to a business record is that record's\n * own write, with its own authority. So an uploaded-but-never-submitted file is a real state a\n * caller can produce; the cleanup sweep is what handles it.\n *\n * ## Declaring `imageConstraints.aspectRatio` turns the cropper on\n *\n * That option is the switch for the browser-side crop step — nothing else is wired. It applies to\n * single-file fields only: a `multiple` field keeps the plain upload path. Vector images and\n * formats the browser cannot decode bypass the cropper and upload the original, so the server-side\n * constraint stays the authority.\n *\n * @param options - Configuration options for file field\n * @returns A Zod object schema with metadata for file detection\n */\nexport function createFileSchema(\n options: FileSchemaOptions = {}\n): DecoratedFileSchema | DecoratedMultipleFileSchema {\n const {\n overridable = true,\n allowedMimeTypes,\n maxSize,\n minSize,\n multiple = false,\n maxFiles,\n nature,\n storageAccepted,\n filePathBinding,\n generation,\n imageConstraints,\n videoConstraints,\n audioConstraints,\n documentConstraints,\n ragSource,\n textExtraction,\n scanPolicy,\n onParentDelete = 'cascade',\n sharable,\n sharableDefaults,\n } = options;\n\n // Warn at schema creation if non-WILDO_MANAGED storage providers are configured (not yet supported)\n // Uses deduplication to avoid console spam during tests or HMR\n if (storageAccepted && storageAccepted.some(s => !_supportedProviders.has(s))) {\n const unsupported = storageAccepted.filter(s => !_supportedProviders.has(s));\n const warnKey = unsupported.sort().join(',');\n if (!_warnedStorageProviders.has(warnKey)) {\n _warnedStorageProviders.add(warnKey);\n console.warn(\n `[z_file] storageAccepted contains unsupported providers: ${unsupported.join(', ')}. ` +\n `Only '${FileStorageAccepted.WILDO_MANAGED}' and '${FileStorageAccepted.LOCAL_DIRECTORY}' are currently implemented. ` +\n `External storage providers (OneDrive, Google Drive, Dropbox) will be ignored until their integrations are available.`\n );\n }\n }\n\n if (filePathBinding) {\n if (filePathBinding.multipleFilePolicy && !multiple) {\n console.warn(\n '[z_file] filePathBinding.multipleFilePolicy is set but multiple is false — multipleFilePolicy will be ignored. ' +\n 'Either set multiple: true or remove multipleFilePolicy.'\n );\n }\n if (filePathBinding.fileName && multiple) {\n console.warn(\n '[z_file] filePathBinding.fileName is set on a multiple file field — fileName is ignored for multiple uploads. ' +\n 'Use filePathBinding.multipleFilePolicy.fileNameTemplate instead.'\n );\n }\n // Warned for EVERY provider, not only WILDO_MANAGED. The condition used to exempt a field that\n // named LOCAL_DIRECTORY, because that provider defaulted to `false` anyway and the warning would\n // have fired on its own default. Both providers now default to `true` and both honour `false`\n // identically, so `false` is an explicit opt-out of the tenant-scoped key shape wherever it is\n // authored — and that is the thing worth saying out loud.\n if (filePathBinding.includeApplicationId === false) {\n console.warn(\n '[z_file] filePathBinding.includeApplicationId is false. Storage keys for this field will carry ' +\n 'NO applications/<appId>/files/<resource>/<scope>/<scopeId>/ prefix, so per-tenant listing, ' +\n 'erasure sweeps and prefix-confined credentials cannot address them — ensure that is intended.'\n );\n }\n }\n\n // Resolve MIME type groups to actual MIME types\n const resolvedMimeTypes = resolveMimeTypes(allowedMimeTypes);\n assertGeneratedPdfFileOptions({ generation, multiple, resolvedMimeTypes, overridable, ragSource, scanPolicy });\n const effectiveMimeTypes = generation ? [...GENERATED_PDF_MIME_TYPES] : resolvedMimeTypes;\n\n // Create the file object schema based on single/multiple\n const fileSchema = multiple\n ? z.object({\n fileIds: z.array(z.string().min(1)),\n updatedAt: z.date(),\n })\n : z.object({\n fileId: z.string().min(1),\n updatedAt: z.date(),\n });\n\n // No longer stored in metadata — consumers derive accept from allowedMimeTypes via buildAcceptAttribute()\n\n // Store file metadata in SCHEMA_METADATA.fileConfig\n const fileMetadata: FileSchemaMetadata = {\n isFile: true,\n overridable,\n ...(effectiveMimeTypes !== undefined && { allowedMimeTypes: effectiveMimeTypes }),\n ...(maxSize !== undefined && { maxSize }),\n ...(minSize !== undefined && { minSize }),\n multiple,\n ...(maxFiles !== undefined && { maxFiles }),\n ...(nature !== undefined && { nature }),\n ...(storageAccepted !== undefined && { storageAccepted }),\n ...(filePathBinding !== undefined && { filePathBinding }),\n ...(generation !== undefined && { generation }),\n ...(imageConstraints !== undefined && { imageConstraints }),\n ...(videoConstraints !== undefined && { videoConstraints }),\n ...(audioConstraints !== undefined && { audioConstraints }),\n ...(documentConstraints !== undefined && { documentConstraints }),\n // Text-provider config only — the RAG declaration itself is NOT stored here (single source of\n // truth is the RAG_SOURCE decorator registered below; read it with `getRagSourceConfig`).\n ...(textExtraction !== undefined && { textExtraction }),\n ...(scanPolicy !== undefined && { scanPolicy }),\n onParentDelete,\n ...(sharable !== undefined && { sharable }),\n ...(sharableDefaults !== undefined && { sharableDefaults }),\n };\n\n // Initialize or extend SCHEMA_METADATA with file config\n const existingMetadata: CustomFieldMetadata = (fileSchema as any)[SCHEMA_METADATA] || {};\n (fileSchema as any)[SCHEMA_METADATA] = {\n ...existingMetadata,\n fileConfig: fileMetadata,\n };\n\n // Add chainable decorator methods to the file schema instance\n addChainableMethods(fileSchema);\n\n // Map the file-side `ragSource` option onto the SHARED RAG_SOURCE decorator — the same one\n // `z.string().ragSource()` registers — so `RagSourceFieldDetection` sees one uniform declaration\n // regardless of text provider. Registered through `addDecorators` (the escape-hatch door) because\n // the fluent `.ragSource()` is deliberately not installed on ZodObject; the shared chokepoint\n // still validates the config and enforces the refused companions identically.\n if (ragSource !== undefined) {\n addDecorators(fileSchema, [{ ref: ZodDecorator.RAG_SOURCE, params: ragSource }]);\n }\n\n if (multiple) {\n return fileSchema as unknown as DecoratedMultipleFileSchema;\n }\n return fileSchema as unknown as DecoratedFileSchema;\n}\n\n/**\n * File schemas declare NO decorator surface of their own.\n *\n * They used to, via a `FileSchemaDecoratorMethods<TSelf>` mixin that re-declared `isDBIndexed`,\n * `isHidden`, `isNotEditable` and `showWhen` with the return narrowed to the file schema — necessary\n * only because the `ZodObject` module augmentation did not carry them. It now does (2026-08-12), and\n * re-declaring them made both interfaces below fail TS2320: an interface may not extend two types\n * whose same-named member differs, and `TSelf` is not `DecoratedPrimitiveZodType<this>`.\n *\n * Removing the mixin costs nothing, because `DecoratedPrimitiveZodType<T>` is `T & { … }` — an\n * INTERSECTION. `z_file().isHidden()` still returns something assignable to `DecoratedFileSchema`,\n * and the full decorator surface is now available rather than the four this mixin listed.\n */\n\n/**\n * Return type for single file schemas - includes decorator methods.\n * IS_DB_INDEXED will index the fileId field for query optimization.\n *\n * Uses `interface` instead of `type` to allow self-referencing without circular alias errors.\n */\nexport interface DecoratedFileSchema extends z.ZodObject<{\n fileId: z.ZodString;\n updatedAt: z.ZodDate;\n}> {}\n\n/**\n * Return type for multiple file schemas - includes decorator methods.\n * IS_DB_INDEXED will index the fileIds array for query optimization.\n *\n * Uses `interface` instead of `type` to allow self-referencing without circular alias errors.\n */\nexport interface DecoratedMultipleFileSchema extends z.ZodObject<{\n fileIds: z.ZodArray<z.ZodString>;\n updatedAt: z.ZodDate;\n}> {}\n\n/**\n * Creates a file schema for file uploads with reference storage.\n * Named z_file to indicate it's a Zod helper function exported standalone.\n *\n * Single file values are stored as: { fileId: string, updatedAt: Date }\n * Multiple file values are stored as: { fileIds: string[], updatedAt: Date }\n *\n * @example\n * ```typescript\n * import { z_file } from '@wildo-ai/zod-decorators';\n *\n * // Simple usage - single file, any type\n * z_file()\n *\n * // With MIME type groups (shortcuts)\n * z_file({ allowedMimeTypes: 'Images' })\n * z_file({ allowedMimeTypes: 'PDF' })\n * z_file({ allowedMimeTypes: ['Images', 'Video'] })\n * z_file({ allowedMimeTypes: 'Documents' }) // PDF + Office\n *\n * // With specific MIME types\n * z_file({ allowedMimeTypes: ['image/png', 'image/jpeg'] })\n *\n * // With size constraints\n * z_file({ maxSize: 10 * 1024 * 1024 }) // 10MB max\n *\n * // Multiple files (uses fileIds instead of fileId)\n * z_file({ multiple: true, maxFiles: 5 })\n *\n * // Non-overridable (append-only)\n * z_file({ overridable: false })\n *\n * // RAG corpus source — registers the shared RAG_SOURCE decorator on the returned schema\n * // (chunking config), with the file-side text-provider knobs beside it (OCR opt-in).\n * z_file({ allowedMimeTypes: 'Documents', ragSource: {}, textExtraction: { ocr: true } })\n *\n * // With decorators\n * z_file().fileUI({ edit: { editMode: FileEditMode.DROPZONE } })\n * z_file().isHidden({ display: true })\n * ```\n */\nexport function z_file(options?: FileSchemaOptions): DecoratedFileSchema | DecoratedMultipleFileSchema {\n return createFileSchema(options);\n}\n/** @wildo_source:part:end zod.decorators.file-schema */\n\n// ============================================================================\n// UTILITY FUNCTIONS\n// ============================================================================\n\n/**\n * Format file size for display.\n */\nexport function formatFileSize(bytes: number): string {\n if (!Number.isFinite(bytes)) return '—';\n if (bytes === 0) return '0 B';\n if (bytes < 0) return '-' + formatFileSize(Math.abs(bytes));\n\n const units = ['B', 'KB', 'MB', 'GB', 'TB'];\n const k = 1024;\n const i = Math.floor(Math.log(bytes) / Math.log(k));\n\n return `${parseFloat((bytes / Math.pow(k, i)).toFixed(2))} ${units[i]}`;\n}\n\n/**\n * Build enhanced accept attribute string from MIME types.\n * Includes both MIME types and extensions for better browser compatibility.\n * Format: \"image/*,.jpg,.jpeg,.png\" or \"application/pdf,.pdf\"\n *\n * @param mimeTypes - Array of MIME type strings\n * @returns Accept attribute string with MIME types and extensions\n */\nexport function buildAcceptAttribute(mimeTypes: string[]): string {\n if (!mimeTypes || mimeTypes.length === 0) return '';\n\n const parts = new Set<string>();\n const extensions = new Set<string>();\n\n for (const mimeType of mimeTypes) {\n // Add MIME type\n parts.add(mimeType);\n\n // Get extensions for this MIME type\n const mimeExtensions = UnifiedFileFormatRegistry.getExtensions(mimeType);\n for (const ext of mimeExtensions) {\n if (ext) {\n extensions.add(`.${ext}`);\n }\n }\n\n // Also check if it's a wildcard MIME type (e.g., image/*)\n // In that case, get all extensions for that nature\n if (mimeType.endsWith('/*')) {\n const formatType = UnifiedFileFormatRegistry.getFormatTypeFromMimeType(mimeType);\n\n if (formatType && formatType.type === 'nature') {\n const natureExtensions = UnifiedFileFormatRegistry.getExtensionsForNature(formatType.nature);\n for (const ext of natureExtensions) {\n if (ext) {\n extensions.add(`.${ext}`);\n }\n }\n }\n }\n }\n\n // Combine MIME types and extensions\n const allParts = [...parts, ...extensions];\n return allParts.join(',');\n}\n\n/**\n * Get file extension from filename.\n * Uses UnifiedFileFormatRegistry for consistency.\n */\nexport function getFileExtension(filename: string): string {\n return UnifiedFileFormatRegistry.getFileExtension(filename);\n}\n\n/**\n * Check if a MIME type is allowed based on allowed types.\n */\nexport function isMimeTypeAllowed(mimeType: string, allowedMimeTypes?: string[]): boolean {\n if (!allowedMimeTypes || allowedMimeTypes.length === 0) return true;\n\n // Check exact match\n if (allowedMimeTypes.includes(mimeType)) return true;\n\n // Check wildcard match (e.g., \"image/*\")\n const [type] = mimeType.split('/');\n if (allowedMimeTypes.includes(`${type}/*`)) return true;\n\n return false;\n}\n\n/**\n * Get a human-readable description of allowed file types.\n * Uses UnifiedFileFormatRegistry for better format detection.\n */\nexport function getAcceptDescription(allowedMimeTypes?: string[]): string {\n if (!allowedMimeTypes || allowedMimeTypes.length === 0) return 'All files';\n\n const types = new Set<string>();\n\n for (const mime of allowedMimeTypes) {\n // Use registry to detect format type\n const formatType = UnifiedFileFormatRegistry.getFormatTypeFromMimeType(mime);\n\n if (formatType) {\n if (formatType.type === 'nature') {\n // Map FileNature to human-readable names\n const natureNames: Record<string, string> = {\n [FileNature.IMAGE]: 'Images',\n [FileNature.VIDEO]: 'Videos',\n [FileNature.AUDIO]: 'Audio files',\n [FileNature.PDF]: 'PDF',\n [FileNature.OFFICE]: 'Office documents',\n [FileNature.ARCHIVE]: 'Archives',\n };\n const name = natureNames[formatType.nature];\n if (name) {\n types.add(name);\n continue;\n }\n } else if (formatType.type === 'agent') {\n // Map agent formats to human-readable names\n const agentNames: Record<string, string> = {\n 'text': 'Text files',\n 'markdown': 'Markdown',\n 'json': 'JSON',\n 'typescript': 'TypeScript',\n 'typescript_react': 'TypeScript React',\n 'yaml': 'YAML',\n };\n const name = agentNames[formatType.format] || formatType.format.replace(/_/g, ' ').replace(/\\b\\w/g, l => l.toUpperCase());\n types.add(name);\n continue;\n }\n }\n\n // Fallback: use MIME type patterns\n if (mime === 'application/pdf') {\n types.add('PDF');\n } else if (mime.startsWith('image/')) {\n types.add('Images');\n } else if (mime.startsWith('video/')) {\n types.add('Videos');\n } else if (mime.startsWith('audio/')) {\n types.add('Audio');\n } else if (mime.includes('document') || mime.includes('word') || mime.includes('excel') || mime.includes('powerpoint')) {\n types.add('Office documents');\n } else {\n // Get extension-like description\n const ext = mime.split('/').pop()?.toUpperCase();\n if (ext) types.add(ext);\n }\n }\n\n return Array.from(types).join(', ') || 'Selected file types';\n}\n\n/**\n * Get file nature from schema metadata.\n * @param schema - Zod schema (must be a file schema)\n * @returns FileNature or undefined if not set\n */\nexport function getFileNature(schema: z.ZodTypeAny): FileNature | undefined {\n const metadata = (schema as any)[SCHEMA_METADATA] as CustomFieldMetadata | undefined;\n return metadata?.fileConfig?.nature;\n}\n\n/**\n * Get storage accepted from schema metadata.\n * @param schema - Zod schema (must be a file schema)\n * @returns Array of FileStorageAccepted or undefined if not set\n */\nexport function getStorageAccepted(schema: z.ZodTypeAny): FileStorageAccepted[] | undefined {\n const metadata = (schema as any)[SCHEMA_METADATA] as CustomFieldMetadata | undefined;\n return metadata?.fileConfig?.storageAccepted;\n}\n\n/**\n * Get file constraints from schema metadata.\n * @param schema - Zod schema (must be a file schema)\n * @returns Object with all constraint properties or undefined if not set\n */\nexport function getFileConstraints(schema: z.ZodTypeAny): {\n imageConstraints?: FileNatureConstraints_Image;\n videoConstraints?: FileNatureConstraints_Video;\n audioConstraints?: FileNatureConstraints_Audio;\n documentConstraints?: FileNatureConstraints_Document;\n} | undefined {\n const metadata = (schema as any)[SCHEMA_METADATA] as CustomFieldMetadata | undefined;\n const fileConfig = metadata?.fileConfig;\n if (!fileConfig) return undefined;\n\n const hasConstraints =\n fileConfig.imageConstraints ||\n fileConfig.videoConstraints ||\n fileConfig.audioConstraints ||\n fileConfig.documentConstraints;\n\n if (!hasConstraints) return undefined;\n\n return {\n ...(fileConfig.imageConstraints && { imageConstraints: fileConfig.imageConstraints }),\n ...(fileConfig.videoConstraints && { videoConstraints: fileConfig.videoConstraints }),\n ...(fileConfig.audioConstraints && { audioConstraints: fileConfig.audioConstraints }),\n ...(fileConfig.documentConstraints && { documentConstraints: fileConfig.documentConstraints }),\n };\n}\n\n// ============================================================================\n// DISPLAY NATURE RESOLUTION\n// ============================================================================\n\n/**\n * Mapping from schema-level `FileNature` to rendering-level `FileDisplayNature`.\n *\n * PDF and OFFICE both render as DOCUMENT.\n * ARCHIVE and ALL are GENERIC (no specialized renderer).\n */\nconst FILE_NATURE_TO_DISPLAY_NATURE: Record<FileNature, FileDisplayNature> = {\n [FileNature.IMAGE]: FileDisplayNature.IMAGE,\n [FileNature.VIDEO]: FileDisplayNature.VIDEO,\n [FileNature.AUDIO]: FileDisplayNature.AUDIO,\n [FileNature.PDF]: FileDisplayNature.DOCUMENT,\n [FileNature.OFFICE]: FileDisplayNature.DOCUMENT,\n [FileNature.ARCHIVE]: FileDisplayNature.GENERIC,\n [FileNature.ALL]: FileDisplayNature.GENERIC,\n};\n\n/**\n * Detect `FileDisplayNature` from a MIME type string.\n *\n * Used as a fallback when no `FileNature` is declared in schema metadata.\n */\nfunction detectDisplayNatureFromMimeType(mimeType: string): FileDisplayNature {\n if (mimeType.startsWith('image/')) return FileDisplayNature.IMAGE;\n if (mimeType.startsWith('video/')) return FileDisplayNature.VIDEO;\n if (mimeType.startsWith('audio/')) return FileDisplayNature.AUDIO;\n if (\n mimeType === 'application/pdf' ||\n mimeType.includes('document') || mimeType.includes('word') ||\n mimeType.includes('spreadsheet') || mimeType.includes('excel') ||\n mimeType.includes('presentation') || mimeType.includes('powerpoint')\n ) return FileDisplayNature.DOCUMENT;\n return FileDisplayNature.GENERIC;\n}\n\n/**\n * Resolve the rendering-level display nature for a file.\n *\n * Resolution priority:\n * 1. `schemaNature` (from `z_file({ nature: ... })` metadata) → mapped via `FILE_NATURE_TO_DISPLAY_NATURE`\n * 2. `mimeType` (from file metadata or browser File object) → detected via MIME prefix matching\n * 3. `FileDisplayNature.GENERIC` (fallback)\n *\n * @param schemaNature - The `FileNature` declared in schema metadata (from `getFileMetadata(schema)?.nature`)\n * @param mimeType - The MIME type of the actual file\n * @returns The `FileDisplayNature` to use for rendering\n *\n * @example\n * ```typescript\n * const displayNature = resolveFileDisplayNature(fileSchemaMetadata?.nature, metadata.mimeType)\n * // FileDisplayNature.IMAGE | .VIDEO | .AUDIO | .DOCUMENT | .GENERIC\n * ```\n */\nexport function resolveFileDisplayNature(\n schemaNature?: FileNature,\n mimeType?: string,\n): FileDisplayNature {\n // Priority 1: Schema-declared nature\n if (schemaNature) {\n return FILE_NATURE_TO_DISPLAY_NATURE[schemaNature] ?? FileDisplayNature.GENERIC;\n }\n // Priority 2: MIME type detection\n if (mimeType) {\n return detectDisplayNatureFromMimeType(mimeType);\n }\n // Priority 3: Fallback\n return FileDisplayNature.GENERIC;\n}\n\n// ============================================================================\n// DISPLAY POLICY RESOLUTION (presentation × activation, + the availability guard)\n// ============================================================================\n\n/**\n * Whether the engine can RENDER a file of this nature/MIME (i.e. whether\n * `THUMBNAIL` / `FULL` presentation and `OVERLAY` activation are satisfiable).\n *\n * Nature alone is not always enough: `DOCUMENT` covers PDF *and* Office, and only\n * PDF has a viewer — so the MIME decides when it is known. Extend this (and only\n * this) when a new displayer ships; every guard tier reads it, so availability can\n * never drift between the static and runtime answers.\n */\nexport function fileNatureHasDisplayer(\n displayNature: FileDisplayNature,\n mimeType?: string,\n): boolean {\n switch (displayNature) {\n case FileDisplayNature.IMAGE:\n case FileDisplayNature.VIDEO:\n case FileDisplayNature.AUDIO:\n return true;\n case FileDisplayNature.DOCUMENT:\n // PDF renders (PDF.js); Office documents have no viewer yet. With no MIME\n // known (the static tier on a declared PDF nature) the answer is yes,\n // because `FileNature.PDF` maps here only for PDFs.\n return mimeType === undefined || mimeType === 'application/pdf';\n case FileDisplayNature.GENERIC:\n return false;\n }\n}\n\n/**\n * Whether a DECLARED schema nature can satisfy a display-requiring policy, decided\n * WITHOUT a MIME type. This is the static (registry-build) tier of the guard.\n *\n * Returns `undefined` for `FileNature.ALL` — genuinely undecidable before the file\n * exists, so the static tier must admit it and the runtime tier decides. Any other\n * nature yields a definite answer, which is what lets a misauthored\n * `ARCHIVE` + `FULL` fail at build instead of rendering nothing at runtime.\n */\nexport function declaredFileNatureCanDisplay(schemaNature: FileNature): boolean | undefined {\n if (schemaNature === FileNature.ALL) return undefined;\n return fileNatureHasDisplayer(FILE_NATURE_TO_DISPLAY_NATURE[schemaNature] ?? FileDisplayNature.GENERIC);\n}\n\n/** Outcome of {@link resolveFileDisplayPolicy}. */\nexport interface ResolvedFileDisplayPolicy {\n /** Effective resting presentation after the availability guard. */\n presentation: FileDisplayPresentation;\n /** Effective activation after the availability guard. */\n activation: FileActivationConfig;\n /** The nature the effective policy was resolved against. */\n displayNature: FileDisplayNature;\n /** True when the authored policy could not be satisfied and was degraded. */\n degraded: boolean;\n /** Human-readable cause, for the dev-only warning. Set iff `degraded`. */\n degradationReason?: string;\n}\n\n/**\n * Resolve the effective file display policy — the RUNTIME tier of the guard.\n *\n * Defaults, when nothing is authored: `CARD` presentation, and an activation derived\n * from the nature (`OVERLAY` when a displayer exists, `DOWNLOAD` otherwise) — so a\n * file is always useful without any authoring, and a document does not mount a\n * viewer just by being on the page.\n *\n * Degradation is deterministic, never a crash and never a dead control:\n * `FULL`/`THUMBNAIL` → `CARD`, `OVERLAY` → `DOWNLOAD`. It only fires when the file's\n * actual nature has no displayer — which is only reachable when the schema declared\n * an open nature (`FileNature.ALL`), because a narrow declared nature that cannot\n * display was already refused at registry build.\n *\n * `CUSTOM` is never degraded: it targets an operation, not a displayer, so displayer\n * availability is irrelevant to it.\n */\nexport function resolveFileDisplayPolicy(params: {\n schemaNature?: FileNature;\n mimeType?: string;\n authored?: FileUIDisplayParams;\n}): ResolvedFileDisplayPolicy {\n const { schemaNature, mimeType, authored } = params;\n const displayNature = resolveFileDisplayNature(schemaNature, mimeType);\n const hasDisplayer = fileNatureHasDisplayer(displayNature, mimeType);\n\n const requestedPresentation = authored?.presentation ?? FileDisplayPresentation.CARD;\n const requestedActivation: FileActivationConfig = authored?.activation ?? {\n policy: hasDisplayer ? FileActivationPolicy.OVERLAY : FileActivationPolicy.DOWNLOAD,\n };\n\n const presentationNeedsDisplayer = requestedPresentation !== FileDisplayPresentation.CARD;\n const activationNeedsDisplayer = requestedActivation.policy === FileActivationPolicy.OVERLAY;\n\n if (hasDisplayer || (!presentationNeedsDisplayer && !activationNeedsDisplayer)) {\n return { presentation: requestedPresentation, activation: requestedActivation, displayNature, degraded: false };\n }\n\n return {\n presentation: presentationNeedsDisplayer ? FileDisplayPresentation.CARD : requestedPresentation,\n activation: activationNeedsDisplayer ? { policy: FileActivationPolicy.DOWNLOAD } : requestedActivation,\n displayNature,\n degraded: true,\n degradationReason:\n `no displayer for ${displayNature}${mimeType ? ` (${mimeType})` : ''}: `\n + `${presentationNeedsDisplayer ? `presentation ${requestedPresentation} → card` : ''}`\n + `${presentationNeedsDisplayer && activationNeedsDisplayer ? ', ' : ''}`\n + `${activationNeedsDisplayer ? 'activation overlay → download' : ''}`,\n };\n}\n"]}
@@ -138,6 +138,57 @@ export type DecoratedMoneySchema = z.ZodObject<{
138
138
  */
139
139
  export declare function z_money(options?: MoneySchemaOptions): DecoratedMoneySchema;
140
140
  /** @wildo_source:part:end zod.factories.money */
141
+ /**
142
+ * Why an amount could not be expressed in its currency's smallest unit.
143
+ *
144
+ * A named vocabulary rather than three bare strings, because each member has a DIFFERENT remedy and
145
+ * an operator reading a sync log needs to know which one they are looking at: an unknown minor unit
146
+ * is a catalogue problem, a precision loss is an authoring problem, and an unsafe magnitude is a
147
+ * limit of the provider's own number type.
148
+ */
149
+ export declare enum MoneyMinorUnitConversionFailure {
150
+ /** The currency has no minor unit (`XDR`, `XXX`) or is not one this vocabulary knows. */
151
+ UNKNOWN_MINOR_UNIT = "unknown_minor_unit",
152
+ /** Converting down would discard a fraction of the provider's smallest unit. */
153
+ PRECISION_LOSS = "precision_loss",
154
+ /** The converted amount cannot be represented exactly as a JavaScript number. */
155
+ UNSAFE_MAGNITUDE = "unsafe_magnitude"
156
+ }
157
+ /** Thrown by {@link toCurrencyMinorUnitAmountOrThrow}; carries the reason so a caller can branch. */
158
+ export declare class MoneyMinorUnitConversionError extends Error {
159
+ readonly reason: MoneyMinorUnitConversionFailure;
160
+ constructor(reason: MoneyMinorUnitConversionFailure, message: string);
161
+ }
162
+ /**
163
+ * Convert a {@link MoneyValue} to the amount a payment provider expects: an integer in the CURRENCY's
164
+ * smallest unit.
165
+ *
166
+ * Wildo stores money at an AUTHORED scale (`decimals` on the value); a provider reads it at the
167
+ * currency's own scale. Those are two different numbers whenever they disagree, and until 2026-09-08
168
+ * the billing boundary sent the stored amount straight through — so a price authored at any scale
169
+ * other than the currency's was charged at the wrong magnitude, by a factor of 10 per decimal place
170
+ * of disagreement.
171
+ *
172
+ * **All arithmetic is `bigint`.** The stored amount already is one, and the whole reason it is a
173
+ * bigint rather than a number is that money must not round; converting through a float to save a cast
174
+ * would give that back at exactly the boundary where it costs money.
175
+ *
176
+ * **Scaling UP is always exact. Scaling DOWN refuses on a remainder rather than rounding** — a price
177
+ * of 1.005 in a currency whose smallest unit is a cent is not 1.00 and not 1.01, it is a price the
178
+ * provider cannot express, and silently picking one is how a catalogue and an invoice come to
179
+ * disagree by a cent per unit forever.
180
+ *
181
+ * **Throws rather than returning a result union**, and the reason is the compiler rather than taste:
182
+ * this repository compiles with `strict: false` (`engine/tsconfig.common.json`), which disables the
183
+ * discriminant narrowing a `{ ok: true } | { ok: false }` result depends on — so every caller would
184
+ * need a cast to read the failure, at every boundary. A typed error narrows by `instanceof`, which
185
+ * works regardless. Callers that must not throw resolve the scale directly with
186
+ * `currencyMinorUnitDecimals` and decide for themselves.
187
+ *
188
+ * @param subject what the message names ("price p_1 tier 2 flat amount"), so an operator reading a
189
+ * sync log knows which amount could not be expressed without opening the catalogue.
190
+ */
191
+ export declare function toCurrencyMinorUnitAmountOrThrow(value: MoneyValue, subject: string): number;
141
192
  /**
142
193
  * Convert a decimal amount to bigint representation.
143
194
  *
@@ -1 +1 @@
1
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,EAAE,MAAM,CAAC;CACtB,GACL,MAAM,CA8BR"}
@@ -4,7 +4,7 @@
4
4
  import { SCHEMA_METADATA, ZodDecorator } from "./zod-decorators.types.js";
5
5
  import { z } from "zod";
6
6
  import { addChainableMethods } from "./zod.module-override.js";
7
- import { CurrencySchema } from "./currencies.shared.schemas.js";
7
+ import { CurrencySchema, currencyMinorUnitDecimals } from "./currencies.shared.schemas.js";
8
8
  /**
9
9
  * Zod schema for MoneyValue.
10
10
  */
@@ -130,6 +130,86 @@ export function z_money(options) {
130
130
  // ============================================================================
131
131
  // MONEY UTILITY FUNCTIONS
132
132
  // ============================================================================
133
+ /**
134
+ * Why an amount could not be expressed in its currency's smallest unit.
135
+ *
136
+ * A named vocabulary rather than three bare strings, because each member has a DIFFERENT remedy and
137
+ * an operator reading a sync log needs to know which one they are looking at: an unknown minor unit
138
+ * is a catalogue problem, a precision loss is an authoring problem, and an unsafe magnitude is a
139
+ * limit of the provider's own number type.
140
+ */
141
+ export var MoneyMinorUnitConversionFailure;
142
+ (function (MoneyMinorUnitConversionFailure) {
143
+ /** The currency has no minor unit (`XDR`, `XXX`) or is not one this vocabulary knows. */
144
+ MoneyMinorUnitConversionFailure["UNKNOWN_MINOR_UNIT"] = "unknown_minor_unit";
145
+ /** Converting down would discard a fraction of the provider's smallest unit. */
146
+ MoneyMinorUnitConversionFailure["PRECISION_LOSS"] = "precision_loss";
147
+ /** The converted amount cannot be represented exactly as a JavaScript number. */
148
+ MoneyMinorUnitConversionFailure["UNSAFE_MAGNITUDE"] = "unsafe_magnitude";
149
+ })(MoneyMinorUnitConversionFailure || (MoneyMinorUnitConversionFailure = {}));
150
+ /** Thrown by {@link toCurrencyMinorUnitAmountOrThrow}; carries the reason so a caller can branch. */
151
+ export class MoneyMinorUnitConversionError extends Error {
152
+ reason;
153
+ constructor(reason, message) {
154
+ super(message);
155
+ this.reason = reason;
156
+ this.name = 'MoneyMinorUnitConversionError';
157
+ }
158
+ }
159
+ /**
160
+ * Convert a {@link MoneyValue} to the amount a payment provider expects: an integer in the CURRENCY's
161
+ * smallest unit.
162
+ *
163
+ * Wildo stores money at an AUTHORED scale (`decimals` on the value); a provider reads it at the
164
+ * currency's own scale. Those are two different numbers whenever they disagree, and until 2026-09-08
165
+ * the billing boundary sent the stored amount straight through — so a price authored at any scale
166
+ * other than the currency's was charged at the wrong magnitude, by a factor of 10 per decimal place
167
+ * of disagreement.
168
+ *
169
+ * **All arithmetic is `bigint`.** The stored amount already is one, and the whole reason it is a
170
+ * bigint rather than a number is that money must not round; converting through a float to save a cast
171
+ * would give that back at exactly the boundary where it costs money.
172
+ *
173
+ * **Scaling UP is always exact. Scaling DOWN refuses on a remainder rather than rounding** — a price
174
+ * of 1.005 in a currency whose smallest unit is a cent is not 1.00 and not 1.01, it is a price the
175
+ * provider cannot express, and silently picking one is how a catalogue and an invoice come to
176
+ * disagree by a cent per unit forever.
177
+ *
178
+ * **Throws rather than returning a result union**, and the reason is the compiler rather than taste:
179
+ * this repository compiles with `strict: false` (`engine/tsconfig.common.json`), which disables the
180
+ * discriminant narrowing a `{ ok: true } | { ok: false }` result depends on — so every caller would
181
+ * need a cast to read the failure, at every boundary. A typed error narrows by `instanceof`, which
182
+ * works regardless. Callers that must not throw resolve the scale directly with
183
+ * `currencyMinorUnitDecimals` and decide for themselves.
184
+ *
185
+ * @param subject what the message names ("price p_1 tier 2 flat amount"), so an operator reading a
186
+ * sync log knows which amount could not be expressed without opening the catalogue.
187
+ */
188
+ export function toCurrencyMinorUnitAmountOrThrow(value, subject) {
189
+ const target = currencyMinorUnitDecimals(value.currency);
190
+ if (target === undefined) {
191
+ throw new MoneyMinorUnitConversionError(MoneyMinorUnitConversionFailure.UNKNOWN_MINOR_UNIT, `Cannot express ${subject} for a payment provider: currency '${value.currency}' has no minor unit this framework can resolve. Cryptocurrencies are in this position deliberately — their decimals are protocol conventions, not a fiat provider's minor unit.`);
192
+ }
193
+ let converted;
194
+ if (value.decimals === target) {
195
+ converted = value.amount;
196
+ }
197
+ else if (value.decimals < target) {
198
+ converted = value.amount * 10n ** BigInt(target - value.decimals);
199
+ }
200
+ else {
201
+ const divisor = 10n ** BigInt(value.decimals - target);
202
+ if (value.amount % divisor !== 0n) {
203
+ throw new MoneyMinorUnitConversionError(MoneyMinorUnitConversionFailure.PRECISION_LOSS, `Cannot express ${subject} for a payment provider: amount ${value.amount} at scale ${value.decimals} cannot be written in ${value.currency}'s smallest unit (scale ${target}) without discarding a fraction of it. Author the amount at scale ${target}, or at a scale whose extra digits are zero.`);
204
+ }
205
+ converted = value.amount / divisor;
206
+ }
207
+ const asNumber = Number(converted);
208
+ if (!Number.isSafeInteger(asNumber)) {
209
+ throw new MoneyMinorUnitConversionError(MoneyMinorUnitConversionFailure.UNSAFE_MAGNITUDE, `Cannot express ${subject} for a payment provider: amount ${converted} in ${value.currency}'s smallest unit exceeds the range a JavaScript number represents exactly, so handing it over would silently change its value.`);
210
+ }
211
+ return asNumber;
212
+ }
133
213
  /**
134
214
  * Convert a decimal amount to bigint representation.
135
215
  *