@tailor-platform/sdk 2.5.0 → 2.6.0

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.
Files changed (65) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/bin/tailor.mjs +3 -2
  3. package/dist/application-CNeOcaLc.mjs +1 -0
  4. package/dist/application-CmXOqTaK.mjs +192 -0
  5. package/dist/application-CmXOqTaK.mjs.map +1 -0
  6. package/dist/cli/commands/api/index.d.mts +1 -1
  7. package/dist/cli/commands/executor/trigger.d.mts +1 -1
  8. package/dist/cli/commands/workflow/start.d.mts +1 -1
  9. package/dist/cli/commands/workspace/list.d.mts +1 -1
  10. package/dist/cli/lib.d.mts +5 -1
  11. package/dist/cli/lib.mjs +1 -1
  12. package/dist/cli/lib.mjs.map +1 -1
  13. package/dist/cli/main.d.mts +2 -0
  14. package/dist/cli/main.mjs +58 -58
  15. package/dist/cli/main.mjs.map +1 -1
  16. package/dist/cli/shared/args.d.mts +65 -1
  17. package/dist/cli/shared/command.d.mts +11 -0
  18. package/dist/cli/shared/context.d.mts +1 -1
  19. package/dist/cli/shared/logger.d.mts +64 -0
  20. package/dist/cli/shared/script-executor.d.mts +1 -1
  21. package/dist/completion/zsh-worker.zsh +1 -1
  22. package/dist/configure/index.mjs +1 -1
  23. package/dist/configure/index.mjs.map +1 -1
  24. package/dist/configure/services/tailordb/schema.d.mts +18 -0
  25. package/dist/configure/services/tailordb/types.d.mts +1 -1
  26. package/dist/{crashreport-B-_HTKLr.mjs → crashreport-BN28xp5B.mjs} +2 -2
  27. package/dist/{crashreport-B-_HTKLr.mjs.map → crashreport-BN28xp5B.mjs.map} +1 -1
  28. package/dist/crashreport-By23O2k-.mjs +1 -0
  29. package/dist/{errors-DSEXKRVD.mjs → errors-DLsQ_-ol.mjs} +2 -2
  30. package/dist/{errors-DSEXKRVD.mjs.map → errors-DLsQ_-ol.mjs.map} +1 -1
  31. package/dist/es-builtins-n3wBv4Sv.mjs +2 -0
  32. package/dist/es-builtins-n3wBv4Sv.mjs.map +1 -0
  33. package/dist/{logger-BcGy-u7G.mjs → logger-CCjs1DuH.mjs} +4 -4
  34. package/dist/logger-CCjs1DuH.mjs.map +1 -0
  35. package/dist/{register-ts-hook-Drnaproy.mjs → register-ts-hook-oDA2JLp2.mjs} +65 -65
  36. package/dist/register-ts-hook-oDA2JLp2.mjs.map +1 -0
  37. package/dist/schema-AYG4OhXY.mjs +2 -0
  38. package/dist/{schema-Ze_dI5VX.mjs.map → schema-AYG4OhXY.mjs.map} +1 -1
  39. package/dist/{service-DlgaUO4V.mjs → service-CLPMoj9n.mjs} +2 -2
  40. package/dist/{service-DlgaUO4V.mjs.map → service-CLPMoj9n.mjs.map} +1 -1
  41. package/dist/service-D7iXk0BT.mjs +1 -0
  42. package/dist/{service-BVe9u2Rt.mjs → service-YqDsHmlK.mjs} +3 -3
  43. package/dist/service-YqDsHmlK.mjs.map +1 -0
  44. package/dist/shared/src/color.d.mts +5 -0
  45. package/dist/tailor-proto/src/tailor/v1/workspace_pb.d.mts +1 -1
  46. package/dist/vitest/environment.mjs +1 -1
  47. package/dist/vitest/environment.mjs.map +1 -1
  48. package/dist/wait-point-registry-B-ESkTZX.mjs +2 -0
  49. package/dist/wait-point-registry-B-ESkTZX.mjs.map +1 -0
  50. package/docs/github-actions.md +4 -3
  51. package/docs/migration/v2.md +5 -1
  52. package/docs/migration/v3.md +39 -0
  53. package/docs/services/tailordb.md +9 -7
  54. package/package.json +5 -4
  55. package/dist/application-DFOUovmN.mjs +0 -1
  56. package/dist/application-D_4vg1KR.mjs +0 -192
  57. package/dist/application-D_4vg1KR.mjs.map +0 -1
  58. package/dist/crashreport-BmsRIdpy.mjs +0 -1
  59. package/dist/logger-BcGy-u7G.mjs.map +0 -1
  60. package/dist/register-ts-hook-Drnaproy.mjs.map +0 -1
  61. package/dist/schema-Ze_dI5VX.mjs +0 -2
  62. package/dist/service-BVe9u2Rt.mjs.map +0 -1
  63. package/dist/service-CpZELSBa.mjs +0 -1
  64. package/dist/wait-point-registry-BrkwfyjS.mjs +0 -2
  65. package/dist/wait-point-registry-BrkwfyjS.mjs.map +0 -1
@@ -0,0 +1,2 @@
1
+ import{t as e}from"./brand-C8nMKhJC.mjs";import{cloneDeep as t}from"es-toolkit";const n={uuid:/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,date:/^(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})$/,time:/^(?<hour>[01]\d|2[0-3]):(?<minute>[0-5]\d)$/,datetime:/^(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})[Tt](?<hour>[01]\d|2[0-3]):(?<minute>[0-5]\d):(?<second>[0-5]\d|60)(\.(?<fraction>\d+))?(?<offset>[Zz]|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/,decimal:/^-?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/};function validateBaseValue(e){let{field:t,value:r,pathArray:i,issues:a}=e,o=i.length>0?i:void 0,s=a.length;switch(t.type){case`string`:typeof r!=`string`&&a.push({message:`Expected a string: received ${String(r)}`,path:o});break;case`integer`:(typeof r!=`number`||!Number.isInteger(r))&&a.push({message:`Expected an integer: received ${String(r)}`,path:o});break;case`float`:(typeof r!=`number`||!Number.isFinite(r))&&a.push({message:`Expected a number: received ${String(r)}`,path:o});break;case`boolean`:typeof r!=`boolean`&&a.push({message:`Expected a boolean: received ${String(r)}`,path:o});break;case`uuid`:(typeof r!=`string`||!n.uuid.test(r))&&a.push({message:`Expected a valid UUID: received ${String(r)}`,path:o});break;case`date`:(typeof r!=`string`||!n.date.test(r))&&a.push({message:`Expected to match "yyyy-MM-dd" format: received ${String(r)}`,path:o});break;case`datetime`:(typeof r!=`string`||!n.datetime.test(r))&&a.push({message:`Expected to match ISO format: received ${String(r)}`,path:o});break;case`time`:(typeof r!=`string`||!n.time.test(r))&&a.push({message:`Expected to match "HH:mm" format: received ${String(r)}`,path:o});break;case`decimal`:(typeof r!=`string`||!n.decimal.test(r))&&a.push({message:`Expected a decimal string: received ${String(r)}`,path:o});break;case`enum`:if(t._metadata.allowedValues){let e=t._metadata.allowedValues.map(e=>e.value);(typeof r!=`string`||!e.includes(r))&&a.push({message:`Must be one of [${e.join(`, `)}]: received ${String(r)}`,path:o})}break;case`nested`:{if(typeof r!=`object`||!r||Array.isArray(r)||r instanceof Date)return a.push({message:`Expected an object: received ${String(r)}`,path:o}),!1;let n=!0;for(let[a,o]of Object.entries(t.fields)){let t=r[a];validateBaseField({...e,field:o,value:t,pathArray:i.concat(a)})||(n=!1)}return n}}return a.length===s}function validateCustomValue(e,t){let{value:n,pathArray:r,issues:i}=e,a=r.length>0?r:void 0;for(let e of t){let t=e({value:n});typeof t==`string`&&i.push({message:t,path:a})}}function validateBaseField(e){let{field:t,value:n,pathArray:r,issues:i}=e,a=r.length>0?r:void 0,o=n==null;if(t._metadata.required&&o)return i.push({message:`Required field is missing`,path:a}),!1;if(!t._metadata.required&&o)return!0;let s=!0;if(t._metadata.array){if(!Array.isArray(n))return i.push({message:`Expected an array`,path:a}),!1;for(let t=0;t<n.length;t++)validateBaseValue({...e,value:n[t],pathArray:r.concat(`[${t}]`)})||(s=!1)}else s=validateBaseValue(e);return s}function validateCustomField(e){let{field:t,value:n,pathArray:r}=e;if(n==null)return;if(t.type===`nested`){let i=t._metadata.array?n:[n];for(let n=0;n<i.length;n++){let a=i[n],o=t._metadata.array?r.concat(`[${n}]`):r;for(let[n,r]of Object.entries(t.fields))validateCustomField({...e,field:r,value:a[n],pathArray:o.concat(n)})}}let i=t._metadata.validate;i?.length&&validateCustomValue(e,i)}function parseInternal(e){let{value:t}=e,n=[],r={...e,issues:n};return validateBaseField(r)&&validateCustomField(r),n.length>0?{issues:n}:{value:t??null}}function parseInputFields(e){let{fields:t,...n}=e;return parseInternal({...n,field:{type:`nested`,fields:t,_metadata:{required:!0}},pathArray:[]})}function mapAllowedValues(e){return e.map(e=>typeof e==`string`?{value:e,description:``}:{...e,description:e.description??``})}function createTailorDBField(e,t,n,r){return createTailorDBFieldRuntime(e,t,n,r)}function createTailorDBFieldRuntime(e,n,r,i){let a={required:!0},o;n&&(n.optional===!0&&(a.required=!1),n.array===!0&&(a.array=!0)),i&&(a.allowedValues=mapAllowedValues(i));function parseInternal$1(e){return parseInternal({...e,field:s})}function cloneWith(e){let t=s.clone();return Object.assign(t._metadata,e),t}let s={type:e,fields:r??{},_defined:void 0,_output:void 0,_metadata:a,get metadata(){return{...this._metadata}},get rawRelation(){return o?{...o,toward:{...o.toward}}:void 0},description(e){return cloneWith({description:e})},typeName(e){return cloneWith({typeName:e})},validate(...e){return cloneWith({validate:e})},parse(e){return parseInternal$1({value:e.value,data:e.data,invoker:e.invoker,pathArray:[]})},relation(e){let t=s.clone(),n=e.toward,r=`table`in n?n.table:n.type,i=r===`self`?`self`:r.name;return t._setRawRelation({type:e.type,toward:{table:i,as:e.toward.as,key:e.toward.key},backward:e.backward}),t},index(){return cloneWith({index:!0})},unique(){return cloneWith({unique:!0,index:!0})},vector(){return cloneWith({vector:!0})},default(e){return cloneWith({default:e})},hooks(e){return cloneWith({hooks:e})},serial(e){return cloneWith({serial:e})},clone(a){if(this._metadata.validate?.length&&a?.array!==void 0&&a.array!==(this._metadata.array===!0))throw Error(`Cannot change the array option on a field with custom validation`);let s=r;if(r){let e={};for(let[t,n]of Object.entries(r))e[t]=n.clone();s=e}let c=createTailorDBFieldRuntime(e,n,s,i);return Object.assign(c._metadata,t(this._metadata)),a&&(a.optional!==void 0&&(c._metadata.required=!a.optional),a.array!==void 0&&(c._metadata.array=a.array)),o&&c._setRawRelation(t(o)),c},_setRawRelation(e){o=e}};return s}const r=createTailorDBField;function uuid(e){return r(`uuid`,e)}function string(e){return r(`string`,e)}function bool(e){return r(`boolean`,e)}function int(e){return r(`integer`,e)}function float(e){return r(`float`,e)}function decimal(e){if(e?.scale!==void 0&&(!Number.isInteger(e.scale)||e.scale<0||e.scale>12))throw Error(`scale must be an integer between 0 and 12`);let t=r(`decimal`,e);return e?.scale!==void 0&&(t._metadata.scale=e.scale),t}function date(e){return r(`date`,e)}function datetime(e){return r(`datetime`,e)}function time(e){return r(`time`,e)}function _enum(e,t){return r(`enum`,t,void 0,e)}function object(e,t){return r(`nested`,t,e)}function createTailorDBType(t,n,r){let i=r.description,a={},o=[],s={},c={},l=[],u,d,f=new Set;r.description!==void 0&&f.add(`description`);function runMethodOnce(e,t){if(f.has(e))throw Error(`.${e}() has already been set`);let n=t();return f.add(e),n}if(r.pluralForm){if(t===r.pluralForm)throw Error(`The name and the plural form must be different. name=${t}`);a.pluralForm=r.pluralForm}let p={name:t,fields:{...n},_output:null,_description:i,get metadata(){let e={};return o.length>0&&o.forEach(t=>{let n=t.fields.map(e=>String(e)),r=t.name||`idx_${n.join(`_`)}`;e[r]={fields:n,unique:t.unique}}),{name:this.name,description:i,settings:a,permissions:s,files:c,...Object.keys(e).length>0&&{indexes:e},...u&&{typeHook:u},...d&&{typeValidate:d}}},hooks(e){return runMethodOnce(`hooks`,()=>(u=e,this))},validate(e){return runMethodOnce(`validate`,()=>(d=e,this))},features(e){return runMethodOnce(`features`,()=>(a={...a,...e},this))},indexes(...e){return runMethodOnce(`indexes`,()=>(o=e,this))},files(e){return runMethodOnce(`files`,()=>(c=e,this))},permission(e){return runMethodOnce(`permission`,()=>{let t=this;return s.record=e,t})},gqlPermission(e){return runMethodOnce(`gqlPermission`,()=>{let t=this;return s.gql=e,t})},description(e){return runMethodOnce(`description`,()=>(i=e,this._description=e,this))},pickFields(e,t){let n={};for(let r of e){let e=this.fields[r];n[r]=t?e.clone(t):e}return n},omitFields(e){let t=new Set(e),n={};for(let e in this.fields)Object.hasOwn(this.fields,e)&&!t.has(e)&&(n[e]=this.fields[e]);return n},get plugins(){return l},plugin(e){for(let[t,n]of Object.entries(e))l.push({pluginId:t,config:n});return this}};return e(p,`tailordb-type`)}const i=uuid();function dbTable(e,t,n){let r=Array.isArray(e)?e[0]:e,a=Array.isArray(e)?e[1]:void 0,o,s;return typeof t==`string`?(o=t,s=n):s=t,createTailorDBType(r,{id:i,...s},{pluralForm:a,description:o})}const timestampsUpdatedAtHook=({input:e,now:t})=>e??t,a=Symbol.for(`tailor-platform/sdk:precompiled-script-expr`);timestampsUpdatedAtHook[a]={"hooks.update":`(({ input, now }) => input ?? now)({ input: _value, oldValue: _oldValue, invoker: _principal, now: _now })`};const o={table:dbTable,uuid,string,bool,int,float,decimal,date,datetime,time,enum:_enum,object,fields:{timestamps:()=>({createdAt:datetime().default(`now`).description(`Record creation timestamp`),updatedAt:datetime().default(`now`).hooks({update:timestampsUpdatedAtHook}).description(`Record update timestamp`)})}};export{parseInternal as i,mapAllowedValues as n,parseInputFields as r,o as t};
2
+ //# sourceMappingURL=schema-AYG4OhXY.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"schema-Ze_dI5VX.mjs","names":["parseInternal","parseFieldInternal"],"sources":["../src/runtime/field-parse.ts","../src/configure/types/field.ts","../src/configure/services/tailordb/schema.ts"],"sourcesContent":["import type { FieldMetadata, TailorFieldType } from \"#/configure/types/field.types\";\nimport type { TailorPrincipal } from \"#/runtime/types\";\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\n\nconst regex = {\n uuid: /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,\n date: /^(?<year>\\d{4})-(?<month>\\d{2})-(?<day>\\d{2})$/,\n time: /^(?<hour>[01]\\d|2[0-3]):(?<minute>[0-5]\\d)$/,\n datetime:\n /^(?<year>\\d{4})-(?<month>\\d{2})-(?<day>\\d{2})[Tt](?<hour>[01]\\d|2[0-3]):(?<minute>[0-5]\\d):(?<second>[0-5]\\d|60)(\\.(?<fraction>\\d+))?(?<offset>[Zz]|[+-](?:[01]\\d|2[0-3]):[0-5]\\d)$/,\n decimal: /^-?(\\d+\\.?\\d*|\\.\\d+)([eE][+-]?\\d+)?$/,\n} as const;\n\nexport type FieldParseArgs = {\n value: unknown;\n data: unknown;\n invoker: TailorPrincipal | null;\n};\n\nexport type FieldParseInternalArgs = {\n value: unknown;\n data: unknown;\n invoker: TailorPrincipal | null;\n pathArray: string[];\n};\n\nexport type FieldRuntime<T extends TailorFieldType = TailorFieldType> = {\n readonly type: T;\n readonly fields: Record<string, FieldRuntime>;\n _metadata: FieldMetadata;\n};\n\ntype FieldParseRuntimeArgs<T extends TailorFieldType> = FieldParseInternalArgs & {\n field: FieldRuntime<T>;\n};\n\ntype FieldValidationArgs<T extends TailorFieldType> = FieldParseRuntimeArgs<T> & {\n issues: StandardSchemaV1.Issue[];\n};\n\nfunction validateBaseValue<T extends TailorFieldType>(args: FieldValidationArgs<T>): boolean {\n const { field, value, pathArray, issues } = args;\n const path = pathArray.length > 0 ? pathArray : undefined;\n const initialIssueCount = issues.length;\n\n switch (field.type) {\n case \"string\":\n if (typeof value !== \"string\") {\n issues.push({\n message: `Expected a string: received ${String(value)}`,\n path,\n });\n }\n break;\n\n case \"integer\":\n if (typeof value !== \"number\" || !Number.isInteger(value)) {\n issues.push({\n message: `Expected an integer: received ${String(value)}`,\n path,\n });\n }\n break;\n\n case \"float\":\n if (typeof value !== \"number\" || !Number.isFinite(value)) {\n issues.push({\n message: `Expected a number: received ${String(value)}`,\n path,\n });\n }\n break;\n\n case \"boolean\":\n if (typeof value !== \"boolean\") {\n issues.push({\n message: `Expected a boolean: received ${String(value)}`,\n path,\n });\n }\n break;\n\n case \"uuid\":\n if (typeof value !== \"string\" || !regex.uuid.test(value)) {\n issues.push({\n message: `Expected a valid UUID: received ${String(value)}`,\n path,\n });\n }\n break;\n case \"date\":\n if (typeof value !== \"string\" || !regex.date.test(value)) {\n issues.push({\n message: `Expected to match \"yyyy-MM-dd\" format: received ${String(value)}`,\n path,\n });\n }\n break;\n case \"datetime\":\n if (typeof value !== \"string\" || !regex.datetime.test(value)) {\n issues.push({\n message: `Expected to match ISO format: received ${String(value)}`,\n path,\n });\n }\n break;\n case \"time\":\n if (typeof value !== \"string\" || !regex.time.test(value)) {\n issues.push({\n message: `Expected to match \"HH:mm\" format: received ${String(value)}`,\n path,\n });\n }\n break;\n case \"decimal\":\n if (typeof value !== \"string\" || !regex.decimal.test(value)) {\n issues.push({\n message: `Expected a decimal string: received ${String(value)}`,\n path,\n });\n }\n break;\n\n case \"enum\":\n if (field._metadata.allowedValues) {\n const allowedValues = field._metadata.allowedValues.map((v) => v.value);\n if (typeof value !== \"string\" || !allowedValues.includes(value)) {\n issues.push({\n message: `Must be one of [${allowedValues.join(\", \")}]: received ${String(value)}`,\n path,\n });\n }\n }\n break;\n\n case \"nested\": {\n // Runtime input may not match the declared field type.\n // oxlint-disable typescript/no-unnecessary-condition\n if (\n typeof value !== \"object\" ||\n value === null ||\n Array.isArray(value) ||\n value instanceof Date\n ) {\n // oxlint-enable typescript/no-unnecessary-condition\n issues.push({\n message: `Expected an object: received ${String(value)}`,\n path,\n });\n return false;\n }\n\n let nestedBaseValid = true;\n for (const [fieldName, nestedField] of Object.entries(field.fields)) {\n const fieldValue = (value as Record<string, unknown>)[fieldName];\n if (\n !validateBaseField({\n ...args,\n field: nestedField,\n value: fieldValue,\n pathArray: pathArray.concat(fieldName),\n })\n ) {\n nestedBaseValid = false;\n }\n }\n return nestedBaseValid;\n }\n }\n\n return issues.length === initialIssueCount;\n}\n\nfunction validateCustomValue<T extends TailorFieldType>(\n args: FieldValidationArgs<T>,\n validateFns: NonNullable<FieldMetadata[\"validate\"]>,\n): void {\n const { value, pathArray, issues } = args;\n const path = pathArray.length > 0 ? pathArray : undefined;\n\n for (const fn of validateFns) {\n const result = fn({ value });\n if (typeof result === \"string\") {\n issues.push({\n message: result,\n path,\n });\n }\n }\n}\n\nfunction validateBaseField<T extends TailorFieldType>(args: FieldValidationArgs<T>): boolean {\n const { field, value, pathArray, issues } = args;\n const path = pathArray.length > 0 ? pathArray : undefined;\n\n const isNullOrUndefined = value === null || value === undefined;\n if (field._metadata.required && isNullOrUndefined) {\n issues.push({\n message: \"Required field is missing\",\n path,\n });\n return false;\n }\n\n if (!field._metadata.required && isNullOrUndefined) {\n return true;\n }\n\n let baseValid = true;\n if (field._metadata.array) {\n if (!Array.isArray(value)) {\n issues.push({\n message: \"Expected an array\",\n path,\n });\n return false;\n }\n\n for (let i = 0; i < value.length; i++) {\n if (\n !validateBaseValue({\n ...args,\n value: value[i],\n pathArray: pathArray.concat(`[${i}]`),\n })\n ) {\n baseValid = false;\n }\n }\n } else {\n baseValid = validateBaseValue(args);\n }\n\n return baseValid;\n}\n\nfunction validateCustomField<T extends TailorFieldType>(args: FieldValidationArgs<T>): void {\n const { field, value, pathArray } = args;\n if (value === null || value === undefined) {\n return;\n }\n\n if (field.type === \"nested\") {\n const records = field._metadata.array\n ? (value as Record<string, unknown>[])\n : [value as Record<string, unknown>];\n\n for (let i = 0; i < records.length; i++) {\n const record = records[i] as Record<string, unknown>;\n const recordPath = field._metadata.array ? pathArray.concat(`[${i}]`) : pathArray;\n for (const [fieldName, nestedField] of Object.entries(field.fields)) {\n validateCustomField({\n ...args,\n field: nestedField,\n value: record[fieldName],\n pathArray: recordPath.concat(fieldName),\n });\n }\n }\n }\n\n const validateFns = field._metadata.validate;\n if (validateFns?.length) {\n validateCustomValue(args, validateFns);\n }\n}\n\nexport function parseInternal<T extends TailorFieldType, Output>(\n args: FieldParseRuntimeArgs<T>,\n): StandardSchemaV1.Result<Output> {\n const { value } = args;\n const issues: StandardSchemaV1.Issue[] = [];\n const validationArgs = { ...args, issues };\n const baseValid = validateBaseField(validationArgs);\n if (baseValid) {\n validateCustomField(validationArgs);\n }\n if (issues.length > 0) {\n return { issues };\n }\n\n return { value: (value ?? null) as Output };\n}\n\ntype ParseInputFieldsArgs = FieldParseArgs & {\n fields: Record<string, FieldRuntime>;\n};\n\n/**\n * Validate a value against a record of input fields, treating the record as a\n * single required object — the same code path deployed functions run via\n * `t.object(fields).parse(...)`, so local validation matches platform behavior.\n * @param args - Input field definitions plus the value, context data, and user\n * @returns Validation result\n */\nexport function parseInputFields(args: ParseInputFieldsArgs): StandardSchemaV1.Result<unknown> {\n const { fields, ...parseArgs } = args;\n return parseInternal({\n ...parseArgs,\n field: { type: \"nested\", fields, _metadata: { required: true } },\n pathArray: [],\n });\n}\n","import type { EnumValue } from \"#/configure/types/field.types\";\n\nexport type AllowedValues = readonly [string | EnumValue, ...(string | EnumValue)[]];\n\n/**\n * Normalize allowed values into EnumValue objects with descriptions.\n * @param values - Allowed values as strings or EnumValue objects\n * @returns Normalized allowed values\n */\nexport function mapAllowedValues(values: AllowedValues): EnumValue[] {\n return values.map((value) => {\n if (typeof value === \"string\") {\n return { value, description: \"\" };\n }\n return { ...value, description: value.description ?? \"\" };\n });\n}\n\nexport type AllowedValuesOutput<V extends AllowedValues> = V[number] extends infer T\n ? T extends string\n ? T\n : T extends { value: infer K }\n ? K\n : never\n : never;\n","import { cloneDeep } from \"es-toolkit\";\nimport {\n type AllowedValues,\n type AllowedValuesOutput,\n mapAllowedValues,\n} from \"#/configure/types/field\";\nimport {\n parseInternal as parseFieldInternal,\n type FieldParseArgs,\n type FieldParseInternalArgs,\n} from \"#/runtime/field-parse\";\nimport { brandValue } from \"#/utils/brand\";\nimport type {\n FieldOptions,\n FieldOutput,\n TailorFieldType,\n TailorToTs,\n FieldValidateInput,\n} from \"#/configure/types/field.types\";\nimport type {\n PrecompiledScriptExprKey,\n PrecompiledScriptExprMap,\n} from \"#/parser/service/tailordb/types\";\nimport type { PluginAttachment, PluginConfigs } from \"#/plugin/types\";\nimport type { InferredAttributes } from \"#/runtime/types\";\nimport type { output, InferFieldsOutput, TypeLevelError } from \"#/types/helpers\";\nimport type { RawPermissions } from \"#/types/tailordb.generated\";\nimport type { TailorTypeGqlPermission, TailorTypePermission } from \"./permission\";\nimport type {\n TailorDBField as TailorDBFieldBase,\n TailorDBType as TailorDBTypeBase,\n DBFieldMetadata,\n DefinedDBFieldMetadata,\n SerialConfig,\n IndexDef,\n TailorDBTypeMetadata,\n RawRelationConfig,\n RelationType,\n Hook,\n TypeHook,\n UpdateHookFn,\n ExcludeNestedDBFields,\n ExcludeHookedDBFields,\n ExcludeDefaultedDBFields,\n TypeFeatures,\n TypeValidateFn,\n} from \"./types\";\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\n\n// Erased DB fields stay assignable across builder method-state changes.\n// oxlint-disable-next-line no-explicit-any\ntype AnyBuilderMethod = any;\n\nexport type TailorAnyDBField = Omit<\n TailorDBFieldBase<AnyBuilderMethod, AnyBuilderMethod>,\n \"fields\"\n> & {\n readonly fields: Record<string, AnyBuilderMethod>;\n _metadata: DBFieldMetadata;\n parse: AnyBuilderMethod;\n readonly typeName: TypeLevelError<string>;\n description: AnyBuilderMethod;\n relation: AnyBuilderMethod;\n index: AnyBuilderMethod;\n unique: AnyBuilderMethod;\n vector: AnyBuilderMethod;\n default: AnyBuilderMethod;\n hooks: AnyBuilderMethod;\n validate: AnyBuilderMethod;\n serial: AnyBuilderMethod;\n clone: AnyBuilderMethod;\n};\n\n// Helper alias\n// oxlint-disable-next-line no-explicit-any\nexport type TailorAnyDBType = TailorDBType<any, any, any>;\n\ntype IsAny<T> = 0 extends 1 & T ? true : false;\ntype DBFieldTypeNameMethod<Defined extends DefinedDBFieldMetadata> =\n IsAny<Defined> extends true\n ? TypeLevelError<string>\n : TypeLevelError<\"typeName cannot be used on TailorDB fields\">;\n\ntype WithDBFieldDescription<Defined> = Defined & { description: true };\ntype WithDBFieldRelation<Defined, S extends RelationType | RelationSelfConfig> = S extends\n | \"oneToOne\"\n | \"1-1\"\n ? Defined & { unique: true; index: true; relation: true }\n : S extends { type: \"oneToOne\" | \"1-1\" }\n ? Defined & { unique: true; index: true; relation: true }\n : Defined & { index: true; relation: true };\ntype WithDBFieldIndex<Defined> = Defined & { index: true };\ntype WithDBFieldUnique<Defined> = Defined & { unique: true; index: true };\ntype WithDBFieldVector<Defined> = Defined & { vector: true };\ntype WithDBFieldHooks<Defined, H> = Defined & {\n hooks: {\n create: H extends { create: unknown } ? true : false;\n update: H extends { update: unknown } ? true : false;\n };\n serial: false;\n};\ntype WithDBFieldDefault<Defined> = Defined & { default: true };\ntype WithDBFieldValidate<Defined> = Defined & { validate: true };\ntype WithDBFieldSerial<Defined> = Defined & {\n serial: true;\n hooks: { create: false; update: false };\n};\ntype WithDBFieldCloneOptions<Defined extends DefinedDBFieldMetadata, NewOpt extends FieldOptions> =\n IsAny<Defined> extends true\n ? Defined\n : Omit<Defined, \"array\"> & {\n array: NewOpt extends { array: true }\n ? true\n : NewOpt extends { array: false }\n ? false\n : Defined[\"array\"];\n };\ntype NonNullableDBFieldOutput<Output> = Exclude<Output, null>;\ntype DBFieldScalarOutput<Output> =\n NonNullableDBFieldOutput<Output> extends (infer Item)[] ? Item : NonNullableDBFieldOutput<Output>;\ntype DBFieldCloneArrayOutput<Output, NewOpt extends FieldOptions> = NewOpt extends {\n array: true;\n}\n ? DBFieldScalarOutput<Output>[]\n : NewOpt extends { array: false }\n ? DBFieldScalarOutput<Output>\n : NonNullableDBFieldOutput<Output>;\ntype DBFieldCloneOutput<Output, NewOpt extends FieldOptions> = NewOpt extends { optional: true }\n ? DBFieldCloneArrayOutput<Output, NewOpt> | null\n : NewOpt extends { optional: false }\n ? DBFieldCloneArrayOutput<Output, NewOpt>\n : null extends Output\n ? DBFieldCloneArrayOutput<Output, NewOpt> | null\n : DBFieldCloneArrayOutput<Output, NewOpt>;\ntype DBFieldCloneOptions<Defined extends DefinedDBFieldMetadata> = Omit<FieldOptions, \"array\"> & {\n array?: Defined extends { validate: unknown } ? Defined[\"array\"] : boolean;\n};\ntype InvalidValidatedArrayCloneKeys<\n Fields extends Record<string, TailorAnyDBField>,\n K extends keyof Fields,\n Opt extends FieldOptions,\n> = Opt extends { array: infer ArrayOption }\n ? {\n [P in K]: Fields[P] extends TailorDBField<infer Defined, infer _Output>\n ? Defined extends { validate: unknown }\n ? ArrayOption extends Defined[\"array\"]\n ? never\n : P\n : never\n : never;\n }[K]\n : never;\ntype DBFieldsCloneOptionsGuard<\n Fields extends Record<string, TailorAnyDBField>,\n K extends keyof Fields,\n Opt extends FieldOptions,\n> = [InvalidValidatedArrayCloneKeys<Fields, K, Opt>] extends [never]\n ? unknown\n : TypeLevelError<\"array cannot be changed on fields with custom validation\">;\ntype DefinedDBTypeMetadata = {\n hooks?: true;\n validate?: true;\n features?: true;\n indexes?: true;\n files?: true;\n permission?: true;\n gqlPermission?: true;\n description?: true;\n};\ntype WithDBTypeMetadata<\n Defined extends DefinedDBTypeMetadata,\n Key extends keyof DefinedDBTypeMetadata,\n> = Defined & Record<Key, true>;\ntype DBTypeDuplicateInputGuard<\n Defined extends DefinedDBTypeMetadata,\n Key extends keyof DefinedDBTypeMetadata,\n Input,\n Message extends string,\n> =\n IsAny<Defined> extends true\n ? Input\n : Defined extends Record<Key, unknown>\n ? TypeLevelError<Message>\n : Input;\ntype DBTypeDuplicateRestGuard<\n Defined extends DefinedDBTypeMetadata,\n Key extends keyof DefinedDBTypeMetadata,\n Input extends unknown[],\n Message extends string,\n> =\n IsAny<Defined> extends true\n ? Input\n : Defined extends Record<Key, unknown>\n ? [TypeLevelError<Message>, ...TypeLevelError<Message>[]]\n : Input;\ntype FileKeyConflictError<\n Fields extends Record<string, TailorAnyDBField>,\n User extends object,\n> = Partial<\n Record<\n keyof output<TailorDBType<Fields, User>> & string,\n TypeLevelError<\"file keys cannot use existing field names\">\n >\n>;\ntype DBFieldDescriptionFn<\n Defined extends DefinedDBFieldMetadata,\n Output,\n Nested extends Record<string, TailorAnyDBField>,\n> = (description: string) => TailorDBField<WithDBFieldDescription<Defined>, Output, Nested>;\ntype DBFieldRelationFn<\n Defined extends DefinedDBFieldMetadata,\n Output,\n Nested extends Record<string, TailorAnyDBField>,\n> = {\n <S extends RelationType, T extends TailorAnyDBType>(\n config: RelationConfig<S, T>,\n ): TailorDBField<WithDBFieldRelation<Defined, S>, Output, Nested>;\n <S extends RelationSelfConfig>(\n config: S,\n ): TailorDBField<WithDBFieldRelation<Defined, S>, Output, Nested>;\n};\ntype DBFieldIndexFn<\n Defined extends DefinedDBFieldMetadata,\n Output,\n Nested extends Record<string, TailorAnyDBField>,\n> = () => TailorDBField<WithDBFieldIndex<Defined>, Output, Nested>;\ntype DBFieldUniqueFn<\n Defined extends DefinedDBFieldMetadata,\n Output,\n Nested extends Record<string, TailorAnyDBField>,\n> = () => TailorDBField<WithDBFieldUnique<Defined>, Output, Nested>;\ntype DBFieldVectorFn<\n Defined extends DefinedDBFieldMetadata,\n Output,\n Nested extends Record<string, TailorAnyDBField>,\n> = () => TailorDBField<WithDBFieldVector<Defined>, Output, Nested>;\ntype DBFieldHooksFn<\n Defined extends DefinedDBFieldMetadata,\n Output,\n Nested extends Record<string, TailorAnyDBField>,\n> = <\n const H extends Hook<\n Output,\n Defined extends { default: true } ? Output | null | undefined : Output\n >,\n>(\n hooks: H,\n) => TailorDBField<WithDBFieldHooks<Defined, H>, Output, Nested>;\ntype DBFieldValidateFn<\n Defined extends DefinedDBFieldMetadata,\n Output,\n Nested extends Record<string, TailorAnyDBField>,\n> = (\n ...validate: FieldValidateInput<Output>[]\n) => TailorDBField<WithDBFieldValidate<Defined>, Output, Nested>;\ntype DBFieldSerialFn<\n Defined extends DefinedDBFieldMetadata,\n Output,\n Nested extends Record<string, TailorAnyDBField>,\n> = (\n config: SerialConfig<Defined[\"type\"] & (\"integer\" | \"string\")>,\n) => TailorDBField<WithDBFieldSerial<Defined>, Output, Nested>;\ntype DBFieldDescriptionMethod<\n Defined extends DefinedDBFieldMetadata,\n Output,\n Nested extends Record<string, TailorAnyDBField>,\n> =\n IsAny<Defined> extends true\n ? DBFieldDescriptionFn<Defined, Output, Nested>\n : Defined extends { description: unknown }\n ? TypeLevelError<\".description() has already been set\">\n : DBFieldDescriptionFn<Defined, Output, Nested>;\ntype DBFieldRelationMethod<\n Defined extends DefinedDBFieldMetadata,\n Output,\n Nested extends Record<string, TailorAnyDBField>,\n> =\n IsAny<Defined> extends true\n ? DBFieldRelationFn<Defined, Output, Nested>\n : Defined extends { relation: unknown }\n ? TypeLevelError<\".relation() has already been set\">\n : DBFieldRelationFn<Defined, Output, Nested>;\ntype DBFieldArrayCheck<A extends boolean, Ok, Msg extends string> = A extends true\n ? TypeLevelError<Msg>\n : Ok;\ntype DBFieldIndexMethod<\n Defined extends DefinedDBFieldMetadata,\n Output,\n Nested extends Record<string, TailorAnyDBField>,\n> =\n IsAny<Defined> extends true\n ? DBFieldIndexFn<Defined, Output, Nested>\n : Defined extends { index: unknown }\n ? TypeLevelError<\".index() has already been set\">\n : DBFieldArrayCheck<\n Defined[\"array\"],\n DBFieldIndexFn<Defined, Output, Nested>,\n \"index cannot be set on array fields\"\n >;\ntype DBFieldUniqueMethod<\n Defined extends DefinedDBFieldMetadata,\n Output,\n Nested extends Record<string, TailorAnyDBField>,\n> =\n IsAny<Defined> extends true\n ? DBFieldUniqueFn<Defined, Output, Nested>\n : Defined extends { unique: unknown }\n ? TypeLevelError<\".unique() has already been set\">\n : DBFieldArrayCheck<\n Defined[\"array\"],\n DBFieldUniqueFn<Defined, Output, Nested>,\n \"unique cannot be set on array fields\"\n >;\ntype DBFieldVectorMethod<\n Defined extends DefinedDBFieldMetadata,\n Output,\n Nested extends Record<string, TailorAnyDBField>,\n> =\n IsAny<Defined> extends true\n ? DBFieldVectorFn<Defined, Output, Nested>\n : Defined extends { vector: unknown }\n ? TypeLevelError<\".vector() has already been set\">\n : Defined extends { type: \"string\"; array: false }\n ? DBFieldVectorFn<Defined, Output, Nested>\n : TypeLevelError<\"vector can only be set on non-array string fields\">;\ntype DBFieldHooksMethod<\n Defined extends DefinedDBFieldMetadata,\n Output,\n Nested extends Record<string, TailorAnyDBField>,\n> =\n IsAny<Defined> extends true\n ? DBFieldHooksFn<Defined, Output, Nested>\n : Defined extends {\n serial: true;\n hooks: { create: false; update: false };\n }\n ? TypeLevelError<\"hooks cannot be set after serial\">\n : Defined extends {\n hooks: unknown;\n }\n ? TypeLevelError<\".hooks() has already been set\">\n : Defined extends { type: \"nested\" }\n ? TypeLevelError<\"hooks cannot be set on nested type fields\">\n : DBFieldHooksFn<Defined, Output, Nested>;\ntype DBFieldValidateMethod<\n Defined extends DefinedDBFieldMetadata,\n Output,\n Nested extends Record<string, TailorAnyDBField>,\n> =\n IsAny<Defined> extends true\n ? DBFieldValidateFn<Defined, Output, Nested>\n : Defined extends { validate: unknown }\n ? TypeLevelError<\".validate() has already been set\">\n : DBFieldValidateFn<Defined, Output, Nested>;\ntype DBFieldSerialMethod<\n Defined extends DefinedDBFieldMetadata,\n Output,\n Nested extends Record<string, TailorAnyDBField>,\n> =\n IsAny<Defined> extends true\n ? DBFieldSerialFn<Defined, Output, Nested>\n : Defined extends { serial: true }\n ? TypeLevelError<\".serial() has already been set\">\n : Defined extends { serial: false }\n ? TypeLevelError<\"serial cannot be set after hooks\">\n : IsAny<Output> extends true\n ? Defined extends { type: \"integer\" | \"string\"; array: false }\n ? DBFieldSerialFn<Defined, Output, Nested>\n : TypeLevelError<\"serial can only be set on non-array integer or string fields\">\n : null extends Output\n ? TypeLevelError<\"serial can only be set on non-array integer or string fields\">\n : Defined extends { type: \"integer\" | \"string\"; array: false }\n ? DBFieldSerialFn<Defined, Output, Nested>\n : TypeLevelError<\"serial can only be set on non-array integer or string fields\">;\ntype DBFieldDefaultFn<\n Defined extends DefinedDBFieldMetadata,\n Output,\n Nested extends Record<string, TailorAnyDBField>,\n> = (\n value: Output extends null ? NonNullable<Output> : Output,\n) => TailorDBField<WithDBFieldDefault<Defined>, Output, Nested>;\ntype DBFieldDefaultMethod<\n Defined extends DefinedDBFieldMetadata,\n Output,\n Nested extends Record<string, TailorAnyDBField>,\n> =\n IsAny<Defined> extends true\n ? DBFieldDefaultFn<Defined, Output, Nested>\n : Defined extends { default: unknown }\n ? TypeLevelError<\".default() has already been set\">\n : Defined extends { type: \"nested\" }\n ? TypeLevelError<\"default cannot be set on nested type fields\">\n : Defined extends { serial: true }\n ? TypeLevelError<\"default cannot be set on serial fields\">\n : null extends Output\n ? TypeLevelError<\"default cannot be set on optional fields\">\n : DBFieldDefaultFn<Defined, Output, Nested>;\n\n/**\n * Full TailorDBField interface with builder methods.\n * Extends the minimal structural interface from types/ with fluent API methods.\n */\nexport interface TailorDBField<\n Defined extends DefinedDBFieldMetadata = DefinedDBFieldMetadata,\n // oxlint-disable-next-line no-explicit-any\n Output = any,\n // Nested object fields, so a `db.object()` field keeps the shape it was declared with.\n // Every builder method passes it through; dropping it here would erase the shape as\n // soon as one is chained.\n Nested extends Record<string, TailorAnyDBField> = Record<string, TailorAnyDBField>,\n> extends Omit<TailorDBFieldBase<Defined, Output, Nested>, \"fields\"> {\n readonly fields: Nested;\n _metadata: DBFieldMetadata;\n\n /**\n * Parse and validate a value against this field's validation rules\n */\n parse(args: FieldParseArgs): StandardSchemaV1.Result<Output>;\n\n /**\n * typeName is not available on TailorDB fields.\n * Use typeName on pipeline fields (t.enum / t.object) instead.\n */\n typeName: DBFieldTypeNameMethod<Defined>;\n\n /**\n * Set a description for the field\n */\n description: DBFieldDescriptionMethod<Defined, Output, Nested>;\n\n /**\n * Define a relation to another table.\n */\n relation: DBFieldRelationMethod<Defined, Output, Nested>;\n\n /**\n * Add an index to the field\n */\n index: DBFieldIndexMethod<Defined, Output, Nested>;\n\n /**\n * Make the field unique (also adds an index)\n */\n unique: DBFieldUniqueMethod<Defined, Output, Nested>;\n\n /**\n * Enable vector search on the field (string type only)\n */\n vector: DBFieldVectorMethod<Defined, Output, Nested>;\n\n /**\n * Set a default value for the field on create. When the field is required,\n * this makes it optional in the Create input — the default fills in when\n * no value (or a nullish hook result) is provided.\n *\n * For datetime/date/time fields, pass `\"now\"` to use the operation timestamp.\n */\n default: DBFieldDefaultMethod<Defined, Output, Nested>;\n\n /**\n * Add hooks for create/update operations on this field.\n */\n hooks: DBFieldHooksMethod<Defined, Output, Nested>;\n\n /**\n * Add validation functions to the field.\n *\n * Validators receive `{ value, data, user }` and run after hooks and\n * built-in type validation; they are skipped when built-in validation\n * fails. For array fields, `value` is the complete array.\n */\n validate: DBFieldValidateMethod<Defined, Output, Nested>;\n\n /**\n * Configure serial/auto-increment behavior\n */\n serial: DBFieldSerialMethod<Defined, Output, Nested>;\n\n /**\n * Clone the field with optional overrides for field options.\n * The `array` option cannot change on fields with custom validation.\n */\n clone<const NewOpt extends DBFieldCloneOptions<Defined>>(\n options?: NewOpt,\n ): TailorDBField<\n WithDBFieldCloneOptions<Defined, NewOpt>,\n DBFieldCloneOutput<Output, NewOpt>,\n Nested\n >;\n}\n\n/**\n * Full TailorDBType interface with builder methods.\n * Extends the minimal structural interface from types/ with fluent API methods.\n */\nexport interface TailorDBType<\n // oxlint-disable-next-line no-explicit-any\n Fields extends Record<string, TailorAnyDBField> = any,\n User extends object = InferredAttributes,\n // oxlint-disable-next-line no-explicit-any\n Defined extends DefinedDBTypeMetadata = any,\n> extends TailorDBTypeBase<Fields, User> {\n _description?: string;\n\n hooks(\n hook: DBTypeDuplicateInputGuard<\n Defined,\n \"hooks\",\n TypeHook<Fields>,\n \".hooks() has already been set\"\n >,\n ): TailorDBType<Fields, User, WithDBTypeMetadata<Defined, \"hooks\">>;\n validate(\n fn: DBTypeDuplicateInputGuard<\n Defined,\n \"validate\",\n TypeValidateFn<Fields>,\n \".validate() has already been set\"\n >,\n ): TailorDBType<Fields, User, WithDBTypeMetadata<Defined, \"validate\">>;\n features(\n features: DBTypeDuplicateInputGuard<\n Defined,\n \"features\",\n Omit<TypeFeatures, \"pluralForm\">,\n \".features() has already been set\"\n >,\n ): TailorDBType<Fields, User, WithDBTypeMetadata<Defined, \"features\">>;\n indexes(\n ...indexes: DBTypeDuplicateRestGuard<\n Defined,\n \"indexes\",\n IndexDef<TailorDBType<Fields, User, Defined>>[],\n \".indexes() has already been set\"\n >\n ): TailorDBType<Fields, User, WithDBTypeMetadata<Defined, \"indexes\">>;\n files<const F extends string>(\n files: DBTypeDuplicateInputGuard<\n Defined,\n \"files\",\n Record<F, string> & FileKeyConflictError<Fields, User>,\n \".files() has already been set\"\n >,\n ): TailorDBType<Fields, User, WithDBTypeMetadata<Defined, \"files\">>;\n permission<\n U extends object = User,\n P extends TailorTypePermission<U, output<TailorDBType<Fields, User, Defined>>> =\n TailorTypePermission<U, output<TailorDBType<Fields, User, Defined>>>,\n >(\n permission: DBTypeDuplicateInputGuard<\n Defined,\n \"permission\",\n P,\n \".permission() has already been set\"\n >,\n ): TailorDBType<Fields, U, WithDBTypeMetadata<Defined, \"permission\">>;\n gqlPermission<\n U extends object = User,\n P extends TailorTypeGqlPermission<U> = TailorTypeGqlPermission<U>,\n >(\n permission: DBTypeDuplicateInputGuard<\n Defined,\n \"gqlPermission\",\n P,\n \".gqlPermission() has already been set\"\n >,\n ): TailorDBType<Fields, U, WithDBTypeMetadata<Defined, \"gqlPermission\">>;\n description(\n description: DBTypeDuplicateInputGuard<\n Defined,\n \"description\",\n string,\n \".description() has already been set\"\n >,\n ): TailorDBType<Fields, User, WithDBTypeMetadata<Defined, \"description\">>;\n pickFields<K extends keyof Fields>(keys: K[]): Pick<Fields, K>;\n pickFields<K extends keyof Fields, const Opt extends FieldOptions>(\n keys: K[],\n options: Opt & DBFieldsCloneOptionsGuard<Fields, K, Opt>,\n ): {\n [P in K]: Fields[P] extends TailorDBField<infer D, infer O>\n ? TailorDBField<WithDBFieldCloneOptions<D, Opt>, DBFieldCloneOutput<O, Opt>>\n : never;\n };\n omitFields<K extends keyof Fields>(keys: K[]): Omit<Fields, K>;\n plugin<P extends keyof PluginConfigs<keyof Fields & string>>(config: {\n [K in P]: PluginConfigs<keyof Fields & string>[K];\n }): TailorDBType<Fields, User, Defined>;\n}\n\nexport type TailorDBInstance<\n // oxlint-disable-next-line no-explicit-any\n Fields extends Record<string, TailorAnyDBField> = any,\n User extends object = InferredAttributes,\n // oxlint-disable-next-line no-explicit-any\n Defined extends DefinedDBTypeMetadata = any,\n> = TailorDBType<Fields, User, Defined>;\n\ninterface RelationConfig<S extends RelationType, T extends TailorDBType> {\n type: S;\n toward: {\n type: T;\n as?: string;\n key?: keyof T[\"fields\"] & string;\n };\n backward?: string;\n}\n\n// Special config variant for self-referencing relations\ntype RelationSelfConfig = {\n type: RelationType;\n toward: {\n type: \"self\";\n as?: string;\n key?: string;\n };\n backward?: string;\n};\n\nfunction isRelationSelfConfig(\n config: RelationConfig<RelationType, TailorDBType> | RelationSelfConfig,\n): config is RelationSelfConfig {\n return config.toward.type === \"self\";\n}\n\ntype DBFieldDefined<T extends TailorFieldType, Opt extends FieldOptions> = {\n type: T;\n array: Opt extends { array: true } ? true : false;\n};\ntype DBFieldOutput<\n T extends TailorFieldType,\n Opt extends FieldOptions,\n OutputBase = TailorToTs[T],\n> = FieldOutput<OutputBase, Opt>;\ntype TailorDBFieldInstance<\n T extends TailorFieldType,\n Opt extends FieldOptions,\n OutputBase = TailorToTs[T],\n> = TailorDBField<DBFieldDefined<T, Opt>, DBFieldOutput<T, Opt, OutputBase>>;\ntype TailorDBFieldRuntimeInstance<\n T extends TailorFieldType,\n Opt extends FieldOptions,\n OutputBase = TailorToTs[T],\n> = TailorDBFieldRuntime<DBFieldDefined<T, Opt>, DBFieldOutput<T, Opt, OutputBase>>;\ntype TailorDBFieldRuntime<Defined extends DefinedDBFieldMetadata, Output> = Omit<\n TailorDBFieldBase<Defined, Output>,\n \"fields\"\n> & {\n readonly fields: Record<string, TailorAnyDBField>;\n _metadata: DBFieldMetadata;\n description(description: string): object;\n typeName(typeName: string): object;\n validate(...validate: FieldValidateInput<Output>[]): object;\n relation(config: RelationConfig<RelationType, TailorDBType> | RelationSelfConfig): object;\n index(): object;\n unique(): object;\n vector(): object;\n default(value: unknown): object;\n hooks(hooks: Hook<Output>): object;\n serial(config: SerialConfig): object;\n clone(options?: FieldOptions): TailorDBFieldRuntime<DefinedDBFieldMetadata, AnyBuilderMethod>;\n parse(args: FieldParseArgs): StandardSchemaV1.Result<Output>;\n _setRawRelation(relation: RawRelationConfig): void;\n};\n\n/**\n * Creates a new TailorDBField instance.\n * @param type - Field type\n * @param options - Field options\n * @param fields - Nested fields for object-like types\n * @param values - Allowed values for enum-like fields\n * @returns A new TailorDBField\n */\nfunction createTailorDBField<\n const T extends TailorFieldType,\n const TOptions extends FieldOptions,\n const OutputBase = TailorToTs[T],\n>(\n type: T,\n options?: TOptions,\n fields?: Record<string, TailorAnyDBField>,\n values?: AllowedValues,\n): TailorDBFieldInstance<T, TOptions, OutputBase>;\nfunction createTailorDBField<const T extends TailorFieldType, const TOptions extends FieldOptions>(\n type: T,\n options?: TOptions,\n fields?: Record<string, TailorAnyDBField>,\n values?: AllowedValues,\n): object {\n return createTailorDBFieldRuntime(type, options, fields, values);\n}\n\nfunction createTailorDBFieldRuntime<\n const T extends TailorFieldType,\n const TOptions extends FieldOptions,\n const OutputBase = TailorToTs[T],\n>(\n type: T,\n options?: TOptions,\n fields?: Record<string, TailorAnyDBField>,\n values?: AllowedValues,\n): TailorDBFieldRuntimeInstance<T, TOptions, OutputBase> {\n type FieldValue = DBFieldOutput<T, TOptions, OutputBase>;\n type FieldType = TailorDBFieldRuntimeInstance<T, TOptions, OutputBase>;\n\n const _metadata: DBFieldMetadata = { required: true };\n let _rawRelation: RawRelationConfig | undefined;\n\n if (options) {\n if (options.optional === true) {\n _metadata.required = false;\n }\n if (options.array === true) {\n _metadata.array = true;\n }\n }\n if (values) {\n _metadata.allowedValues = mapAllowedValues(values);\n }\n\n function parseInternal(args: FieldParseInternalArgs): StandardSchemaV1.Result<FieldValue> {\n return parseFieldInternal<T, FieldValue>({\n ...args,\n field,\n });\n }\n\n function cloneWith(metadataUpdates: Partial<DBFieldMetadata>) {\n const cloned = field.clone();\n Object.assign(cloned._metadata, metadataUpdates);\n return cloned;\n }\n\n const field: FieldType = {\n type,\n fields: fields ?? {},\n _defined: undefined as unknown as DBFieldDefined<T, TOptions>,\n _output: undefined as FieldValue,\n _metadata,\n\n get metadata() {\n return { ...this._metadata };\n },\n\n get rawRelation(): Readonly<RawRelationConfig> | undefined {\n return _rawRelation ? { ..._rawRelation, toward: { ..._rawRelation.toward } } : undefined;\n },\n\n description(description: string) {\n return cloneWith({ description });\n },\n\n typeName(typeName: string) {\n return cloneWith({ typeName });\n },\n\n validate(...validateInputs: FieldValidateInput<FieldValue>[]) {\n return cloneWith({ validate: validateInputs });\n },\n\n parse(args: FieldParseArgs): StandardSchemaV1.Result<FieldValue> {\n return parseInternal({\n value: args.value,\n data: args.data,\n invoker: args.invoker,\n pathArray: [],\n });\n },\n\n // TailorDBField specific methods\n relation(config: RelationConfig<RelationType, TailorDBType> | RelationSelfConfig) {\n const cloned = field.clone();\n const targetType = isRelationSelfConfig(config) ? \"self\" : config.toward.type.name;\n cloned._setRawRelation({\n type: config.type,\n toward: {\n type: targetType,\n as: config.toward.as,\n key: config.toward.key,\n },\n backward: config.backward,\n });\n return cloned;\n },\n\n index() {\n return cloneWith({ index: true });\n },\n\n unique() {\n return cloneWith({ unique: true, index: true });\n },\n\n vector() {\n return cloneWith({ vector: true });\n },\n\n // oxlint-disable-next-line no-explicit-any\n default(value: any) {\n // oxlint-disable-next-line no-explicit-any\n return cloneWith({ default: value }) as any;\n },\n\n hooks(hooks: Hook<FieldValue>) {\n return cloneWith({ hooks });\n },\n\n serial(config: SerialConfig) {\n return cloneWith({ serial: config });\n },\n\n clone(cloneOptions?: FieldOptions) {\n if (\n this._metadata.validate?.length &&\n cloneOptions?.array !== undefined &&\n cloneOptions.array !== (this._metadata.array === true)\n ) {\n throw new Error(\"Cannot change the array option on a field with custom validation\");\n }\n\n // Deep clone nested object fields if present\n let clonedFields = fields;\n if (fields) {\n const cloned: Record<string, TailorAnyDBField> = {};\n for (const [key, field] of Object.entries(fields)) {\n cloned[key] = field.clone();\n }\n clonedFields = cloned;\n }\n\n // Create a new field with cloned configuration\n const clonedField = createTailorDBFieldRuntime(type, options, clonedFields, values);\n\n // Deep copy metadata using cloneDeep (preserves function references)\n Object.assign(clonedField._metadata, cloneDeep(this._metadata));\n\n // Apply new options if provided\n if (cloneOptions) {\n if (cloneOptions.optional !== undefined) {\n clonedField._metadata.required = !cloneOptions.optional;\n }\n if (cloneOptions.array !== undefined) {\n clonedField._metadata.array = cloneOptions.array;\n }\n }\n\n // Copy raw relation if exists\n if (_rawRelation) {\n clonedField._setRawRelation(cloneDeep(_rawRelation));\n }\n\n return clonedField;\n },\n\n _setRawRelation(relation: RawRelationConfig) {\n _rawRelation = relation;\n },\n };\n\n return field;\n}\n\nconst createField = createTailorDBField;\n\n/**\n * Create a UUID field.\n * @param options - Field configuration options\n * @returns A UUID field\n * @example db.uuid()\n * @example db.uuid({ optional: true })\n */\nfunction uuid<const Opt extends FieldOptions>(options?: Opt) {\n return createField(\"uuid\", options);\n}\n\n/**\n * Create a string field.\n * @param options - Field configuration options\n * @returns A string field\n * @example db.string()\n * @example db.string({ optional: true })\n */\nfunction string<const Opt extends FieldOptions>(options?: Opt) {\n return createField(\"string\", options);\n}\n\n/**\n * Create a boolean field.\n * Note: The method name is `bool` but creates a `boolean` type field.\n * @param options - Field configuration options\n * @returns A boolean field\n * @example db.bool()\n * @example db.bool({ optional: true })\n */\nfunction bool<const Opt extends FieldOptions>(options?: Opt) {\n return createField(\"boolean\", options);\n}\n\n/**\n * Create an integer field.\n * @param options - Field configuration options\n * @returns An integer field\n * @example db.int()\n * @example db.int({ optional: true })\n */\nfunction int<const Opt extends FieldOptions>(options?: Opt) {\n return createField(\"integer\", options);\n}\n\n/**\n * Create a float (decimal number) field.\n * @param options - Field configuration options\n * @returns A float field\n * @example db.float()\n * @example db.float({ optional: true })\n */\nfunction float<const Opt extends FieldOptions>(options?: Opt) {\n return createField(\"float\", options);\n}\n\ninterface DecimalFieldOptions extends FieldOptions {\n scale?: number;\n}\n\n/**\n * Create a decimal field (stored as string for precision).\n * @param options - Field configuration options including optional scale (0-12)\n * @returns A decimal field\n * @example db.decimal()\n * @example db.decimal({ scale: 2 })\n * @example db.decimal({ scale: 2, optional: true })\n */\nfunction decimal<const Opt extends DecimalFieldOptions>(options?: Opt) {\n if (options?.scale !== undefined) {\n if (!Number.isInteger(options.scale) || options.scale < 0 || options.scale > 12) {\n throw new Error(\"scale must be an integer between 0 and 12\");\n }\n }\n const field = createField(\"decimal\", options);\n if (options?.scale !== undefined) {\n field._metadata.scale = options.scale;\n }\n return field;\n}\n\n/**\n * Create a date field (date only, no time component).\n * Format: \"yyyy-MM-dd\"\n * @param options - Field configuration options\n * @returns A date field\n * @example db.date()\n */\nfunction date<const Opt extends FieldOptions>(options?: Opt) {\n return createField(\"date\", options);\n}\n\n/**\n * Create a datetime field (date and time).\n * Format: ISO 8601, such as \"yyyy-MM-ddTHH:mm:ssZ\" or \"yyyy-MM-ddTHH:mm:ss+09:00\"\n * @param options - Field configuration options\n * @returns A datetime field\n * @example db.datetime()\n */\nfunction datetime<const Opt extends FieldOptions>(options?: Opt) {\n return createField(\"datetime\", options);\n}\n\n/**\n * Create a time field (time only, no date component).\n * Format: \"HH:mm\"\n * @param options - Field configuration options\n * @returns A time field\n * @example db.time()\n */\nfunction time<const Opt extends FieldOptions>(options?: Opt) {\n return createField(\"time\", options);\n}\n\n/**\n * Create an enum field with a fixed set of allowed string values.\n * @param values - Array of allowed string values, or array of `{ value, description }` objects\n * @param options - Field configuration options\n * @returns An enum field\n * @example db.enum([\"active\", \"inactive\", \"suspended\"])\n * @example db.enum([\"small\", \"medium\", \"large\"], { optional: true })\n */\nfunction _enum<const V extends AllowedValues, const Opt extends FieldOptions>(\n values: V,\n options?: Opt,\n): TailorDBField<\n { type: \"enum\"; array: Opt extends { array: true } ? true : false },\n FieldOutput<AllowedValuesOutput<V>, Opt>\n> {\n return createField<\"enum\", Opt, AllowedValuesOutput<V>>(\"enum\", options, undefined, values);\n}\n\n/**\n * Create a nested object field with sub-fields.\n * @param fields - Record of nested field definitions\n * @param options - Field configuration options\n * @returns A nested object field\n * @example db.object({ street: db.string(), city: db.string(), zip: db.string() })\n * @example db.object({ name: db.string() }, { optional: true })\n */\nfunction object<\n const F extends Record<string, TailorAnyDBField> &\n ExcludeNestedDBFields<F> &\n ExcludeHookedDBFields<F> &\n ExcludeDefaultedDBFields<F>,\n const Opt extends FieldOptions,\n>(fields: F, options?: Opt) {\n return createField(\"nested\", options, fields) as unknown as TailorDBField<\n { type: \"nested\"; array: Opt extends { array: true } ? true : false },\n FieldOutput<InferFieldsOutput<F>, Opt>,\n F\n >;\n}\n\n/**\n * Creates a new TailorDBType instance.\n * @param name - Table name\n * @param fields - Field definitions\n * @param options - Table options\n * @param options.pluralForm - Optional plural form\n * @param options.description - Optional description\n * @returns A new TailorDBType\n */\nfunction createTailorDBType<\n // oxlint-disable-next-line no-explicit-any\n const Fields extends Record<string, TailorAnyDBField> = any,\n User extends object = InferredAttributes,\n>(\n name: string,\n fields: Fields,\n options: { pluralForm?: string; description?: string },\n): TailorDBType<Fields, User, DefinedDBTypeMetadata> {\n let _description = options.description;\n let _settings: TypeFeatures = {};\n let _indexes: IndexDef<TailorDBType<Fields, User, DefinedDBTypeMetadata>>[] = [];\n const _permissions: RawPermissions = {};\n let _files: Record<string, string> = {};\n const _plugins: PluginAttachment[] = [];\n // oxlint-disable-next-line typescript/no-unsafe-function-type\n let _typeHook: { create?: Function; update?: Function } | undefined;\n // oxlint-disable-next-line typescript/no-unsafe-function-type\n let _typeValidate: Function | undefined;\n const _definedMethods = new Set<keyof DefinedDBTypeMetadata>();\n if (options.description !== undefined) {\n _definedMethods.add(\"description\");\n }\n\n function runMethodOnce<T>(method: keyof DefinedDBTypeMetadata, action: () => T): T {\n if (_definedMethods.has(method)) {\n throw new Error(`.${method}() has already been set`);\n }\n const result = action();\n _definedMethods.add(method);\n return result;\n }\n type TypeAfter<Key extends keyof DefinedDBTypeMetadata> = TailorDBType<\n Fields,\n User,\n WithDBTypeMetadata<DefinedDBTypeMetadata, Key>\n >;\n type TypeAfterUser<\n NextUser extends object,\n Key extends keyof DefinedDBTypeMetadata,\n > = TailorDBType<Fields, NextUser, WithDBTypeMetadata<DefinedDBTypeMetadata, Key>>;\n\n if (options.pluralForm) {\n if (name === options.pluralForm) {\n throw new Error(`The name and the plural form must be different. name=${name}`);\n }\n _settings.pluralForm = options.pluralForm;\n }\n\n const dbType: TailorDBType<Fields, User, DefinedDBTypeMetadata> = {\n name,\n fields: { ...fields },\n _output: null as unknown as InferFieldsOutput<Fields>,\n _description,\n\n get metadata(): TailorDBTypeMetadata {\n // Convert indexes to the format expected by the manifest\n const indexes: Record<string, { fields: string[]; unique?: boolean }> = {};\n if (_indexes.length > 0) {\n _indexes.forEach((index) => {\n const fieldNames = index.fields.map((field) => String(field));\n const key = index.name || `idx_${fieldNames.join(\"_\")}`;\n indexes[key] = {\n fields: fieldNames,\n unique: index.unique,\n };\n });\n }\n\n return {\n name: this.name,\n description: _description,\n settings: _settings,\n permissions: _permissions,\n files: _files,\n ...(Object.keys(indexes).length > 0 && { indexes }),\n ...(_typeHook && { typeHook: _typeHook }),\n ...(_typeValidate && { typeValidate: _typeValidate }),\n };\n },\n\n hooks(hook: TypeHook<Fields>): TypeAfter<\"hooks\"> {\n return runMethodOnce(\"hooks\", () => {\n _typeHook = hook;\n return this as TypeAfter<\"hooks\">;\n });\n },\n\n validate(fn: TypeValidateFn<Fields>): TypeAfter<\"validate\"> {\n return runMethodOnce(\"validate\", () => {\n _typeValidate = fn;\n return this as TypeAfter<\"validate\">;\n });\n },\n\n features(features: Omit<TypeFeatures, \"pluralForm\">): TypeAfter<\"features\"> {\n return runMethodOnce(\"features\", () => {\n _settings = {\n ..._settings,\n ...features,\n };\n return this as TypeAfter<\"features\">;\n });\n },\n\n indexes(\n ...indexes: IndexDef<TailorDBType<Fields, User, DefinedDBTypeMetadata>>[]\n ): TypeAfter<\"indexes\"> {\n return runMethodOnce(\"indexes\", () => {\n _indexes = indexes;\n return this as TypeAfter<\"indexes\">;\n });\n },\n\n files<const F extends string>(\n files: Record<F, string> & FileKeyConflictError<Fields, User>,\n ): TypeAfter<\"files\"> {\n return runMethodOnce(\"files\", () => {\n _files = files;\n return this as TypeAfter<\"files\">;\n });\n },\n\n permission<\n U extends object = User,\n P extends TailorTypePermission<U, output<TailorDBType<Fields, User, DefinedDBTypeMetadata>>> =\n TailorTypePermission<U, output<TailorDBType<Fields, User, DefinedDBTypeMetadata>>>,\n >(permission: P): TypeAfterUser<U, \"permission\"> {\n return runMethodOnce(\"permission\", () => {\n const ret = this as unknown as TypeAfterUser<U, \"permission\">;\n _permissions.record = permission as RawPermissions[\"record\"];\n return ret;\n });\n },\n\n gqlPermission<\n U extends object = User,\n P extends TailorTypeGqlPermission<U> = TailorTypeGqlPermission<U>,\n >(permission: P): TypeAfterUser<U, \"gqlPermission\"> {\n return runMethodOnce(\"gqlPermission\", () => {\n const ret = this as unknown as TypeAfterUser<U, \"gqlPermission\">;\n _permissions.gql = permission as RawPermissions[\"gql\"];\n return ret;\n });\n },\n\n description(description: string): TypeAfter<\"description\"> {\n return runMethodOnce(\"description\", () => {\n _description = description;\n this._description = description;\n return this as TypeAfter<\"description\">;\n });\n },\n\n pickFields<K extends keyof Fields, const Opt extends FieldOptions>(keys: K[], options?: Opt) {\n const result = {} as Record<K, TailorAnyDBField>;\n for (const key of keys) {\n const field = this.fields[key] as TailorAnyDBField;\n if (options) {\n result[key] = field.clone(options);\n } else {\n result[key] = field;\n }\n }\n // oxlint-disable-next-line no-explicit-any\n return result as any;\n },\n\n omitFields<K extends keyof Fields>(keys: K[]): Omit<Fields, K> {\n const keysSet = new Set(keys);\n const result = {} as Record<string, TailorAnyDBField>;\n for (const key in this.fields) {\n if (Object.hasOwn(this.fields, key) && !keysSet.has(key as unknown as K)) {\n result[key] = this.fields[key] as TailorAnyDBField;\n }\n }\n return result as Omit<Fields, K>;\n },\n\n get plugins(): PluginAttachment[] {\n return _plugins;\n },\n\n plugin<P extends keyof PluginConfigs<keyof Fields & string>>(config: {\n [K in P]: PluginConfigs<keyof Fields & string>[K];\n }): TailorDBType<Fields, User, AnyBuilderMethod> {\n for (const [pluginId, pluginConfig] of Object.entries(config)) {\n _plugins.push({ pluginId, config: pluginConfig });\n }\n return this;\n },\n };\n\n return brandValue(dbType, \"tailordb-type\");\n}\n\nconst idField = uuid();\ntype idField = typeof idField;\ntype DBTable<\n F extends { id?: never } & Record<string, TailorAnyDBField>,\n Defined extends DefinedDBTypeMetadata = DefinedDBTypeMetadata,\n> = TailorDBInstance<{ id: idField } & F, InferredAttributes, Defined>;\n\n/**\n * Creates a new database table with the specified fields.\n * An `id` field (UUID) is automatically added to every table.\n * @param name - The name of the table, or a tuple of [name, pluralForm]\n * @param fields - The field definitions for the table\n * @returns A new TailorDB table instance\n * @example\n * export const user = db.table(\"User\", {\n * name: db.string(),\n * email: db.string(),\n * age: db.int({ optional: true }),\n * role: db.enum([\"admin\", \"member\"]),\n * ...db.fields.timestamps(),\n * });\n * // Always export both the value and type:\n * export type user = typeof user;\n */\nfunction dbTable<const F extends { id?: never } & Record<string, TailorAnyDBField>>(\n name: string | [string, string],\n fields: F,\n): DBTable<F>;\n/**\n * Creates a new database table with the specified fields and description.\n * An `id` field (UUID) is automatically added to every table.\n * @param name - The name of the table, or a tuple of [name, pluralForm]\n * @param description - A description of the table\n * @param fields - The field definitions for the table\n * @returns A new TailorDB table instance\n */\nfunction dbTable<const F extends { id?: never } & Record<string, TailorAnyDBField>>(\n name: string | [string, string],\n description: string,\n fields: F,\n): DBTable<F, WithDBTypeMetadata<DefinedDBTypeMetadata, \"description\">>;\nfunction dbTable<const F extends { id?: never } & Record<string, TailorAnyDBField>>(\n name: string | [string, string],\n fieldsOrDescription: string | F,\n fields?: F,\n): DBTable<F> | DBTable<F, WithDBTypeMetadata<DefinedDBTypeMetadata, \"description\">> {\n const typeName = Array.isArray(name) ? name[0] : name;\n const pluralForm = Array.isArray(name) ? name[1] : undefined;\n\n let description: string | undefined;\n let fieldDef: F;\n if (typeof fieldsOrDescription === \"string\") {\n description = fieldsOrDescription;\n fieldDef = fields as F;\n } else {\n fieldDef = fieldsOrDescription;\n }\n return createTailorDBType<{ id: idField } & F>(\n typeName,\n {\n id: idField,\n ...fieldDef,\n },\n { pluralForm, description },\n );\n}\n\n// `Function.prototype.toString()` of this hook is embedded verbatim into deployed\n// schemas and migration diffs (see parser/service/tailordb/hooks-validate-precompiled-expr.ts\n// and field.ts). Its source text depends on how the SDK itself was built (e.g.\n// minification), so a fixed expression is pinned onto it directly here instead -\n// configure cannot import parser's `setPrecompiledScriptExpr` runtime helper across\n// the module boundary, only the symbol registry key and map types. Keep\n// this literal in sync with the \"timestamps() updatedAt hook resolves to the pinned\n// expr\" test in parser/service/tailordb/field.precompiled.test.ts, which fails if it\n// ever drifts from what this hook's own source naturally produces.\ntype TimestampsUpdatedAtHookFn = UpdateHookFn<string | Date | null, string | Date>;\nconst timestampsUpdatedAtHook: TimestampsUpdatedAtHookFn = ({ input, now }) => input ?? now;\nconst PRECOMPILED_EXPR_KEY: PrecompiledScriptExprKey =\n \"tailor-platform/sdk:precompiled-script-expr\";\nconst PRECOMPILED_EXPR_SYMBOL = Symbol.for(PRECOMPILED_EXPR_KEY);\n(timestampsUpdatedAtHook as unknown as Record<symbol, PrecompiledScriptExprMap>)[\n PRECOMPILED_EXPR_SYMBOL\n] = {\n \"hooks.update\":\n \"(({ input, now }) => input ?? now)({ input: _value, oldValue: _oldValue, invoker: _principal, now: _now })\",\n};\n\n/** TailorDB schema builder utilities for defining tables and fields. */\nexport const db = {\n table: dbTable,\n uuid,\n string,\n bool,\n int,\n float,\n decimal,\n date,\n datetime,\n time,\n enum: _enum,\n object,\n fields: {\n /**\n * Creates standard timestamp fields (createdAt, updatedAt) with automatic defaults.\n * Both fields default to the current time on create. updatedAt is also refreshed on update.\n * User-specified values are respected when provided (e.g. seeding historical records).\n * @returns An object with createdAt and updatedAt fields\n * @example\n * const model = db.table(\"Model\", {\n * name: db.string(),\n * ...db.fields.timestamps(),\n * });\n */\n timestamps: () => ({\n createdAt: datetime().default(\"now\").description(\"Record creation timestamp\"),\n updatedAt: datetime()\n .default(\"now\")\n .hooks({ update: timestampsUpdatedAtHook })\n .description(\"Record update timestamp\"),\n }),\n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,CAAa,CAAC,EAElD,OAAO,IACT,CACF,EAEA,OAAO,EAAW,EAAQ,eAAe,CAC3C,CAEA,MAAM,EAAU,KAAK,EAyCrB,SAAS,QACP,EACA,EACA,EACmF,CACnF,IAAM,EAAW,MAAM,QAAQ,CAAI,EAAI,EAAK,GAAK,EAC3C,EAAa,MAAM,QAAQ,CAAI,EAAI,EAAK,GAAK,IAAA,GAE/C,EACA,EAOJ,OANI,OAAO,GAAwB,UACjC,EAAc,EACd,EAAW,GAEX,EAAW,EAEN,mBACL,EACA,CACE,GAAI,EACJ,GAAG,CACL,EACA,CAAE,aAAY,aAAY,CAC5B,CACF,CAYA,MAAM,yBAAsD,CAAE,QAAO,SAAU,GAAS,EAGlF,EAA0B,OAAO,IAAI,6CAAoB,EAC/D,wBACE,GACE,CACF,eACE,4GACJ,EAGA,MAAa,EAAK,CAChB,MAAO,QACP,KACA,OACA,KACA,IACA,MACA,QACA,KACA,SACA,KACA,KAAM,MACN,OACA,OAAQ,CAYN,gBAAmB,CACjB,UAAW,SAAS,CAAC,CAAC,QAAQ,KAAK,CAAC,CAAC,YAAY,2BAA2B,EAC5E,UAAW,SAAS,CAAC,CAClB,QAAQ,KAAK,CAAC,CACd,MAAM,CAAE,OAAQ,uBAAwB,CAAC,CAAC,CAC1C,YAAY,yBAAyB,CAC1C,EACF,CACF"}
1
+ {"version":3,"file":"schema-AYG4OhXY.mjs","names":["parseInternal","parseFieldInternal"],"sources":["../src/runtime/field-parse.ts","../src/configure/types/field.ts","../src/configure/services/tailordb/schema.ts"],"sourcesContent":["import type { FieldMetadata, TailorFieldType } from \"#/configure/types/field.types\";\nimport type { TailorPrincipal } from \"#/runtime/types\";\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\n\nconst regex = {\n uuid: /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,\n date: /^(?<year>\\d{4})-(?<month>\\d{2})-(?<day>\\d{2})$/,\n time: /^(?<hour>[01]\\d|2[0-3]):(?<minute>[0-5]\\d)$/,\n datetime:\n /^(?<year>\\d{4})-(?<month>\\d{2})-(?<day>\\d{2})[Tt](?<hour>[01]\\d|2[0-3]):(?<minute>[0-5]\\d):(?<second>[0-5]\\d|60)(\\.(?<fraction>\\d+))?(?<offset>[Zz]|[+-](?:[01]\\d|2[0-3]):[0-5]\\d)$/,\n decimal: /^-?(\\d+\\.?\\d*|\\.\\d+)([eE][+-]?\\d+)?$/,\n} as const;\n\nexport type FieldParseArgs = {\n value: unknown;\n data: unknown;\n invoker: TailorPrincipal | null;\n};\n\nexport type FieldParseInternalArgs = {\n value: unknown;\n data: unknown;\n invoker: TailorPrincipal | null;\n pathArray: string[];\n};\n\nexport type FieldRuntime<T extends TailorFieldType = TailorFieldType> = {\n readonly type: T;\n readonly fields: Record<string, FieldRuntime>;\n _metadata: FieldMetadata;\n};\n\ntype FieldParseRuntimeArgs<T extends TailorFieldType> = FieldParseInternalArgs & {\n field: FieldRuntime<T>;\n};\n\ntype FieldValidationArgs<T extends TailorFieldType> = FieldParseRuntimeArgs<T> & {\n issues: StandardSchemaV1.Issue[];\n};\n\nfunction validateBaseValue<T extends TailorFieldType>(args: FieldValidationArgs<T>): boolean {\n const { field, value, pathArray, issues } = args;\n const path = pathArray.length > 0 ? pathArray : undefined;\n const initialIssueCount = issues.length;\n\n switch (field.type) {\n case \"string\":\n if (typeof value !== \"string\") {\n issues.push({\n message: `Expected a string: received ${String(value)}`,\n path,\n });\n }\n break;\n\n case \"integer\":\n if (typeof value !== \"number\" || !Number.isInteger(value)) {\n issues.push({\n message: `Expected an integer: received ${String(value)}`,\n path,\n });\n }\n break;\n\n case \"float\":\n if (typeof value !== \"number\" || !Number.isFinite(value)) {\n issues.push({\n message: `Expected a number: received ${String(value)}`,\n path,\n });\n }\n break;\n\n case \"boolean\":\n if (typeof value !== \"boolean\") {\n issues.push({\n message: `Expected a boolean: received ${String(value)}`,\n path,\n });\n }\n break;\n\n case \"uuid\":\n if (typeof value !== \"string\" || !regex.uuid.test(value)) {\n issues.push({\n message: `Expected a valid UUID: received ${String(value)}`,\n path,\n });\n }\n break;\n case \"date\":\n if (typeof value !== \"string\" || !regex.date.test(value)) {\n issues.push({\n message: `Expected to match \"yyyy-MM-dd\" format: received ${String(value)}`,\n path,\n });\n }\n break;\n case \"datetime\":\n if (typeof value !== \"string\" || !regex.datetime.test(value)) {\n issues.push({\n message: `Expected to match ISO format: received ${String(value)}`,\n path,\n });\n }\n break;\n case \"time\":\n if (typeof value !== \"string\" || !regex.time.test(value)) {\n issues.push({\n message: `Expected to match \"HH:mm\" format: received ${String(value)}`,\n path,\n });\n }\n break;\n case \"decimal\":\n if (typeof value !== \"string\" || !regex.decimal.test(value)) {\n issues.push({\n message: `Expected a decimal string: received ${String(value)}`,\n path,\n });\n }\n break;\n\n case \"enum\":\n if (field._metadata.allowedValues) {\n const allowedValues = field._metadata.allowedValues.map((v) => v.value);\n if (typeof value !== \"string\" || !allowedValues.includes(value)) {\n issues.push({\n message: `Must be one of [${allowedValues.join(\", \")}]: received ${String(value)}`,\n path,\n });\n }\n }\n break;\n\n case \"nested\": {\n // Runtime input may not match the declared field type.\n // oxlint-disable typescript/no-unnecessary-condition\n if (\n typeof value !== \"object\" ||\n value === null ||\n Array.isArray(value) ||\n value instanceof Date\n ) {\n // oxlint-enable typescript/no-unnecessary-condition\n issues.push({\n message: `Expected an object: received ${String(value)}`,\n path,\n });\n return false;\n }\n\n let nestedBaseValid = true;\n for (const [fieldName, nestedField] of Object.entries(field.fields)) {\n const fieldValue = (value as Record<string, unknown>)[fieldName];\n if (\n !validateBaseField({\n ...args,\n field: nestedField,\n value: fieldValue,\n pathArray: pathArray.concat(fieldName),\n })\n ) {\n nestedBaseValid = false;\n }\n }\n return nestedBaseValid;\n }\n }\n\n return issues.length === initialIssueCount;\n}\n\nfunction validateCustomValue<T extends TailorFieldType>(\n args: FieldValidationArgs<T>,\n validateFns: NonNullable<FieldMetadata[\"validate\"]>,\n): void {\n const { value, pathArray, issues } = args;\n const path = pathArray.length > 0 ? pathArray : undefined;\n\n for (const fn of validateFns) {\n const result = fn({ value });\n if (typeof result === \"string\") {\n issues.push({\n message: result,\n path,\n });\n }\n }\n}\n\nfunction validateBaseField<T extends TailorFieldType>(args: FieldValidationArgs<T>): boolean {\n const { field, value, pathArray, issues } = args;\n const path = pathArray.length > 0 ? pathArray : undefined;\n\n const isNullOrUndefined = value === null || value === undefined;\n if (field._metadata.required && isNullOrUndefined) {\n issues.push({\n message: \"Required field is missing\",\n path,\n });\n return false;\n }\n\n if (!field._metadata.required && isNullOrUndefined) {\n return true;\n }\n\n let baseValid = true;\n if (field._metadata.array) {\n if (!Array.isArray(value)) {\n issues.push({\n message: \"Expected an array\",\n path,\n });\n return false;\n }\n\n for (let i = 0; i < value.length; i++) {\n if (\n !validateBaseValue({\n ...args,\n value: value[i],\n pathArray: pathArray.concat(`[${i}]`),\n })\n ) {\n baseValid = false;\n }\n }\n } else {\n baseValid = validateBaseValue(args);\n }\n\n return baseValid;\n}\n\nfunction validateCustomField<T extends TailorFieldType>(args: FieldValidationArgs<T>): void {\n const { field, value, pathArray } = args;\n if (value === null || value === undefined) {\n return;\n }\n\n if (field.type === \"nested\") {\n const records = field._metadata.array\n ? (value as Record<string, unknown>[])\n : [value as Record<string, unknown>];\n\n for (let i = 0; i < records.length; i++) {\n const record = records[i] as Record<string, unknown>;\n const recordPath = field._metadata.array ? pathArray.concat(`[${i}]`) : pathArray;\n for (const [fieldName, nestedField] of Object.entries(field.fields)) {\n validateCustomField({\n ...args,\n field: nestedField,\n value: record[fieldName],\n pathArray: recordPath.concat(fieldName),\n });\n }\n }\n }\n\n const validateFns = field._metadata.validate;\n if (validateFns?.length) {\n validateCustomValue(args, validateFns);\n }\n}\n\nexport function parseInternal<T extends TailorFieldType, Output>(\n args: FieldParseRuntimeArgs<T>,\n): StandardSchemaV1.Result<Output> {\n const { value } = args;\n const issues: StandardSchemaV1.Issue[] = [];\n const validationArgs = { ...args, issues };\n const baseValid = validateBaseField(validationArgs);\n if (baseValid) {\n validateCustomField(validationArgs);\n }\n if (issues.length > 0) {\n return { issues };\n }\n\n return { value: (value ?? null) as Output };\n}\n\ntype ParseInputFieldsArgs = FieldParseArgs & {\n fields: Record<string, FieldRuntime>;\n};\n\n/**\n * Validate a value against a record of input fields, treating the record as a\n * single required object — the same code path deployed functions run via\n * `t.object(fields).parse(...)`, so local validation matches platform behavior.\n * @param args - Input field definitions plus the value, context data, and user\n * @returns Validation result\n */\nexport function parseInputFields(args: ParseInputFieldsArgs): StandardSchemaV1.Result<unknown> {\n const { fields, ...parseArgs } = args;\n return parseInternal({\n ...parseArgs,\n field: { type: \"nested\", fields, _metadata: { required: true } },\n pathArray: [],\n });\n}\n","import type { EnumValue } from \"#/configure/types/field.types\";\n\nexport type AllowedValues = readonly [string | EnumValue, ...(string | EnumValue)[]];\n\n/**\n * Normalize allowed values into EnumValue objects with descriptions.\n * @param values - Allowed values as strings or EnumValue objects\n * @returns Normalized allowed values\n */\nexport function mapAllowedValues(values: AllowedValues): EnumValue[] {\n return values.map((value) => {\n if (typeof value === \"string\") {\n return { value, description: \"\" };\n }\n return { ...value, description: value.description ?? \"\" };\n });\n}\n\nexport type AllowedValuesOutput<V extends AllowedValues> = V[number] extends infer T\n ? T extends string\n ? T\n : T extends { value: infer K }\n ? K\n : never\n : never;\n","import { cloneDeep } from \"es-toolkit\";\nimport {\n type AllowedValues,\n type AllowedValuesOutput,\n mapAllowedValues,\n} from \"#/configure/types/field\";\nimport {\n parseInternal as parseFieldInternal,\n type FieldParseArgs,\n type FieldParseInternalArgs,\n} from \"#/runtime/field-parse\";\nimport { brandValue } from \"#/utils/brand\";\nimport type {\n FieldOptions,\n FieldOutput,\n TailorFieldType,\n TailorToTs,\n FieldValidateInput,\n} from \"#/configure/types/field.types\";\nimport type {\n PrecompiledScriptExprKey,\n PrecompiledScriptExprMap,\n} from \"#/parser/service/tailordb/types\";\nimport type { PluginAttachment, PluginConfigs } from \"#/plugin/types\";\nimport type { InferredAttributes } from \"#/runtime/types\";\nimport type { output, InferFieldsOutput, TypeLevelError } from \"#/types/helpers\";\nimport type { RawPermissions } from \"#/types/tailordb.generated\";\nimport type { TailorTypeGqlPermission, TailorTypePermission } from \"./permission\";\nimport type {\n TailorDBField as TailorDBFieldBase,\n TailorDBType as TailorDBTypeBase,\n DBFieldMetadata,\n DefinedDBFieldMetadata,\n SerialConfig,\n IndexDef,\n TailorDBTypeMetadata,\n RawRelationConfig,\n RelationType,\n Hook,\n TypeHook,\n UpdateHookFn,\n ExcludeNestedDBFields,\n ExcludeHookedDBFields,\n ExcludeDefaultedDBFields,\n TypeFeatures,\n TypeValidateFn,\n} from \"./types\";\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\n\n// Erased DB fields stay assignable across builder method-state changes.\n// oxlint-disable-next-line no-explicit-any\ntype AnyBuilderMethod = any;\n\nexport type TailorAnyDBField = Omit<\n TailorDBFieldBase<AnyBuilderMethod, AnyBuilderMethod>,\n \"fields\"\n> & {\n readonly fields: Record<string, AnyBuilderMethod>;\n _metadata: DBFieldMetadata;\n parse: AnyBuilderMethod;\n readonly typeName: TypeLevelError<string>;\n description: AnyBuilderMethod;\n relation: AnyBuilderMethod;\n index: AnyBuilderMethod;\n unique: AnyBuilderMethod;\n vector: AnyBuilderMethod;\n default: AnyBuilderMethod;\n hooks: AnyBuilderMethod;\n validate: AnyBuilderMethod;\n serial: AnyBuilderMethod;\n clone: AnyBuilderMethod;\n};\n\n// Helper alias\n// oxlint-disable-next-line no-explicit-any\nexport type TailorAnyDBType = TailorDBType<any, any, any>;\n\ntype IsAny<T> = 0 extends 1 & T ? true : false;\ntype DBFieldTypeNameMethod<Defined extends DefinedDBFieldMetadata> =\n IsAny<Defined> extends true\n ? TypeLevelError<string>\n : TypeLevelError<\"typeName cannot be used on TailorDB fields\">;\n\ntype WithDBFieldDescription<Defined> = Defined & { description: true };\ntype WithDBFieldRelation<Defined, S extends RelationType | RelationSelfConfig> = S extends\n | \"oneToOne\"\n | \"1-1\"\n ? Defined & { unique: true; index: true; relation: true }\n : S extends { type: \"oneToOne\" | \"1-1\" }\n ? Defined & { unique: true; index: true; relation: true }\n : Defined & { index: true; relation: true };\ntype WithDBFieldIndex<Defined> = Defined & { index: true };\ntype WithDBFieldUnique<Defined> = Defined & { unique: true; index: true };\ntype WithDBFieldVector<Defined> = Defined & { vector: true };\ntype WithDBFieldHooks<Defined, H> = Defined & {\n hooks: {\n create: H extends { create: unknown } ? true : false;\n update: H extends { update: unknown } ? true : false;\n };\n serial: false;\n};\ntype WithDBFieldDefault<Defined> = Defined & { default: true };\ntype WithDBFieldValidate<Defined> = Defined & { validate: true };\ntype WithDBFieldSerial<Defined> = Defined & {\n serial: true;\n hooks: { create: false; update: false };\n};\ntype WithDBFieldCloneOptions<Defined extends DefinedDBFieldMetadata, NewOpt extends FieldOptions> =\n IsAny<Defined> extends true\n ? Defined\n : Omit<Defined, \"array\"> & {\n array: NewOpt extends { array: true }\n ? true\n : NewOpt extends { array: false }\n ? false\n : Defined[\"array\"];\n };\ntype NonNullableDBFieldOutput<Output> = Exclude<Output, null>;\ntype DBFieldScalarOutput<Output> =\n NonNullableDBFieldOutput<Output> extends (infer Item)[] ? Item : NonNullableDBFieldOutput<Output>;\ntype DBFieldCloneArrayOutput<Output, NewOpt extends FieldOptions> = NewOpt extends {\n array: true;\n}\n ? DBFieldScalarOutput<Output>[]\n : NewOpt extends { array: false }\n ? DBFieldScalarOutput<Output>\n : NonNullableDBFieldOutput<Output>;\ntype DBFieldCloneOutput<Output, NewOpt extends FieldOptions> = NewOpt extends { optional: true }\n ? DBFieldCloneArrayOutput<Output, NewOpt> | null\n : NewOpt extends { optional: false }\n ? DBFieldCloneArrayOutput<Output, NewOpt>\n : null extends Output\n ? DBFieldCloneArrayOutput<Output, NewOpt> | null\n : DBFieldCloneArrayOutput<Output, NewOpt>;\ntype DBFieldCloneOptions<Defined extends DefinedDBFieldMetadata> = Omit<FieldOptions, \"array\"> & {\n array?: Defined extends { validate: unknown } ? Defined[\"array\"] : boolean;\n};\ntype InvalidValidatedArrayCloneKeys<\n Fields extends Record<string, TailorAnyDBField>,\n K extends keyof Fields,\n Opt extends FieldOptions,\n> = Opt extends { array: infer ArrayOption }\n ? {\n [P in K]: Fields[P] extends TailorDBField<infer Defined, infer _Output>\n ? Defined extends { validate: unknown }\n ? ArrayOption extends Defined[\"array\"]\n ? never\n : P\n : never\n : never;\n }[K]\n : never;\ntype DBFieldsCloneOptionsGuard<\n Fields extends Record<string, TailorAnyDBField>,\n K extends keyof Fields,\n Opt extends FieldOptions,\n> = [InvalidValidatedArrayCloneKeys<Fields, K, Opt>] extends [never]\n ? unknown\n : TypeLevelError<\"array cannot be changed on fields with custom validation\">;\ntype DefinedDBTypeMetadata = {\n hooks?: true;\n validate?: true;\n features?: true;\n indexes?: true;\n files?: true;\n permission?: true;\n gqlPermission?: true;\n description?: true;\n};\ntype WithDBTypeMetadata<\n Defined extends DefinedDBTypeMetadata,\n Key extends keyof DefinedDBTypeMetadata,\n> = Defined & Record<Key, true>;\ntype DBTypeDuplicateInputGuard<\n Defined extends DefinedDBTypeMetadata,\n Key extends keyof DefinedDBTypeMetadata,\n Input,\n Message extends string,\n> =\n IsAny<Defined> extends true\n ? Input\n : Defined extends Record<Key, unknown>\n ? TypeLevelError<Message>\n : Input;\ntype DBTypeDuplicateRestGuard<\n Defined extends DefinedDBTypeMetadata,\n Key extends keyof DefinedDBTypeMetadata,\n Input extends unknown[],\n Message extends string,\n> =\n IsAny<Defined> extends true\n ? Input\n : Defined extends Record<Key, unknown>\n ? [TypeLevelError<Message>, ...TypeLevelError<Message>[]]\n : Input;\ntype FileKeyConflictError<\n Fields extends Record<string, TailorAnyDBField>,\n User extends object,\n> = Partial<\n Record<\n keyof output<TailorDBType<Fields, User>> & string,\n TypeLevelError<\"file keys cannot use existing field names\">\n >\n>;\ntype DBFieldDescriptionFn<\n Defined extends DefinedDBFieldMetadata,\n Output,\n Nested extends Record<string, TailorAnyDBField>,\n> = (description: string) => TailorDBField<WithDBFieldDescription<Defined>, Output, Nested>;\ntype DBFieldRelationFn<\n Defined extends DefinedDBFieldMetadata,\n Output,\n Nested extends Record<string, TailorAnyDBField>,\n> = {\n <S extends RelationType, T extends TailorAnyDBType>(\n config: RelationConfig<S, T>,\n ): TailorDBField<WithDBFieldRelation<Defined, S>, Output, Nested>;\n <S extends RelationSelfConfig>(\n config: S,\n ): TailorDBField<WithDBFieldRelation<Defined, S>, Output, Nested>;\n};\ntype DBFieldIndexFn<\n Defined extends DefinedDBFieldMetadata,\n Output,\n Nested extends Record<string, TailorAnyDBField>,\n> = () => TailorDBField<WithDBFieldIndex<Defined>, Output, Nested>;\ntype DBFieldUniqueFn<\n Defined extends DefinedDBFieldMetadata,\n Output,\n Nested extends Record<string, TailorAnyDBField>,\n> = () => TailorDBField<WithDBFieldUnique<Defined>, Output, Nested>;\ntype DBFieldVectorFn<\n Defined extends DefinedDBFieldMetadata,\n Output,\n Nested extends Record<string, TailorAnyDBField>,\n> = () => TailorDBField<WithDBFieldVector<Defined>, Output, Nested>;\ntype DBFieldHooksFn<\n Defined extends DefinedDBFieldMetadata,\n Output,\n Nested extends Record<string, TailorAnyDBField>,\n> = <\n const H extends Hook<\n Output,\n Defined extends { default: true } ? Output | null | undefined : Output\n >,\n>(\n hooks: H,\n) => TailorDBField<WithDBFieldHooks<Defined, H>, Output, Nested>;\ntype DBFieldValidateFn<\n Defined extends DefinedDBFieldMetadata,\n Output,\n Nested extends Record<string, TailorAnyDBField>,\n> = (\n ...validate: FieldValidateInput<Output>[]\n) => TailorDBField<WithDBFieldValidate<Defined>, Output, Nested>;\ntype DBFieldSerialFn<\n Defined extends DefinedDBFieldMetadata,\n Output,\n Nested extends Record<string, TailorAnyDBField>,\n> = (\n config: SerialConfig<Defined[\"type\"] & (\"integer\" | \"string\")>,\n) => TailorDBField<WithDBFieldSerial<Defined>, Output, Nested>;\ntype DBFieldDescriptionMethod<\n Defined extends DefinedDBFieldMetadata,\n Output,\n Nested extends Record<string, TailorAnyDBField>,\n> =\n IsAny<Defined> extends true\n ? DBFieldDescriptionFn<Defined, Output, Nested>\n : Defined extends { description: unknown }\n ? TypeLevelError<\".description() has already been set\">\n : DBFieldDescriptionFn<Defined, Output, Nested>;\ntype DBFieldRelationMethod<\n Defined extends DefinedDBFieldMetadata,\n Output,\n Nested extends Record<string, TailorAnyDBField>,\n> =\n IsAny<Defined> extends true\n ? DBFieldRelationFn<Defined, Output, Nested>\n : Defined extends { relation: unknown }\n ? TypeLevelError<\".relation() has already been set\">\n : DBFieldRelationFn<Defined, Output, Nested>;\ntype DBFieldArrayCheck<A extends boolean, Ok, Msg extends string> = A extends true\n ? TypeLevelError<Msg>\n : Ok;\ntype DBFieldIndexMethod<\n Defined extends DefinedDBFieldMetadata,\n Output,\n Nested extends Record<string, TailorAnyDBField>,\n> =\n IsAny<Defined> extends true\n ? DBFieldIndexFn<Defined, Output, Nested>\n : Defined extends { index: unknown }\n ? TypeLevelError<\".index() has already been set\">\n : DBFieldArrayCheck<\n Defined[\"array\"],\n DBFieldIndexFn<Defined, Output, Nested>,\n \"index cannot be set on array fields\"\n >;\ntype DBFieldUniqueMethod<\n Defined extends DefinedDBFieldMetadata,\n Output,\n Nested extends Record<string, TailorAnyDBField>,\n> =\n IsAny<Defined> extends true\n ? DBFieldUniqueFn<Defined, Output, Nested>\n : Defined extends { unique: unknown }\n ? TypeLevelError<\".unique() has already been set\">\n : DBFieldArrayCheck<\n Defined[\"array\"],\n DBFieldUniqueFn<Defined, Output, Nested>,\n \"unique cannot be set on array fields\"\n >;\ntype DBFieldVectorMethod<\n Defined extends DefinedDBFieldMetadata,\n Output,\n Nested extends Record<string, TailorAnyDBField>,\n> =\n IsAny<Defined> extends true\n ? DBFieldVectorFn<Defined, Output, Nested>\n : Defined extends { vector: unknown }\n ? TypeLevelError<\".vector() has already been set\">\n : Defined extends { type: \"string\"; array: false }\n ? DBFieldVectorFn<Defined, Output, Nested>\n : TypeLevelError<\"vector can only be set on non-array string fields\">;\ntype DBFieldHooksMethod<\n Defined extends DefinedDBFieldMetadata,\n Output,\n Nested extends Record<string, TailorAnyDBField>,\n> =\n IsAny<Defined> extends true\n ? DBFieldHooksFn<Defined, Output, Nested>\n : Defined extends {\n serial: true;\n hooks: { create: false; update: false };\n }\n ? TypeLevelError<\"hooks cannot be set after serial\">\n : Defined extends {\n hooks: unknown;\n }\n ? TypeLevelError<\".hooks() has already been set\">\n : Defined extends { type: \"nested\" }\n ? TypeLevelError<\"hooks cannot be set on nested type fields\">\n : DBFieldHooksFn<Defined, Output, Nested>;\ntype DBFieldValidateMethod<\n Defined extends DefinedDBFieldMetadata,\n Output,\n Nested extends Record<string, TailorAnyDBField>,\n> =\n IsAny<Defined> extends true\n ? DBFieldValidateFn<Defined, Output, Nested>\n : Defined extends { validate: unknown }\n ? TypeLevelError<\".validate() has already been set\">\n : DBFieldValidateFn<Defined, Output, Nested>;\ntype DBFieldSerialMethod<\n Defined extends DefinedDBFieldMetadata,\n Output,\n Nested extends Record<string, TailorAnyDBField>,\n> =\n IsAny<Defined> extends true\n ? DBFieldSerialFn<Defined, Output, Nested>\n : Defined extends { serial: true }\n ? TypeLevelError<\".serial() has already been set\">\n : Defined extends { serial: false }\n ? TypeLevelError<\"serial cannot be set after hooks\">\n : IsAny<Output> extends true\n ? Defined extends { type: \"integer\" | \"string\"; array: false }\n ? DBFieldSerialFn<Defined, Output, Nested>\n : TypeLevelError<\"serial can only be set on non-array integer or string fields\">\n : null extends Output\n ? TypeLevelError<\"serial can only be set on non-array integer or string fields\">\n : Defined extends { type: \"integer\" | \"string\"; array: false }\n ? DBFieldSerialFn<Defined, Output, Nested>\n : TypeLevelError<\"serial can only be set on non-array integer or string fields\">;\ntype DBFieldDefaultFn<\n Defined extends DefinedDBFieldMetadata,\n Output,\n Nested extends Record<string, TailorAnyDBField>,\n> = (\n value: Output extends null ? NonNullable<Output> : Output,\n) => TailorDBField<WithDBFieldDefault<Defined>, Output, Nested>;\ntype DBFieldDefaultMethod<\n Defined extends DefinedDBFieldMetadata,\n Output,\n Nested extends Record<string, TailorAnyDBField>,\n> =\n IsAny<Defined> extends true\n ? DBFieldDefaultFn<Defined, Output, Nested>\n : Defined extends { default: unknown }\n ? TypeLevelError<\".default() has already been set\">\n : Defined extends { type: \"nested\" }\n ? TypeLevelError<\"default cannot be set on nested type fields\">\n : Defined extends { serial: true }\n ? TypeLevelError<\"default cannot be set on serial fields\">\n : null extends Output\n ? TypeLevelError<\"default cannot be set on optional fields\">\n : DBFieldDefaultFn<Defined, Output, Nested>;\n\n/**\n * Full TailorDBField interface with builder methods.\n * Extends the minimal structural interface from types/ with fluent API methods.\n */\nexport interface TailorDBField<\n Defined extends DefinedDBFieldMetadata = DefinedDBFieldMetadata,\n // oxlint-disable-next-line no-explicit-any\n Output = any,\n // Nested object fields, so a `db.object()` field keeps the shape it was declared with.\n // Every builder method passes it through; dropping it here would erase the shape as\n // soon as one is chained.\n Nested extends Record<string, TailorAnyDBField> = Record<string, TailorAnyDBField>,\n> extends Omit<TailorDBFieldBase<Defined, Output, Nested>, \"fields\"> {\n readonly fields: Nested;\n _metadata: DBFieldMetadata;\n\n /**\n * Parse and validate a value against this field's validation rules\n */\n parse(args: FieldParseArgs): StandardSchemaV1.Result<Output>;\n\n /**\n * typeName is not available on TailorDB fields.\n * Use typeName on pipeline fields (t.enum / t.object) instead.\n */\n typeName: DBFieldTypeNameMethod<Defined>;\n\n /**\n * Set a description for the field\n */\n description: DBFieldDescriptionMethod<Defined, Output, Nested>;\n\n /**\n * Define a relation to another table.\n */\n relation: DBFieldRelationMethod<Defined, Output, Nested>;\n\n /**\n * Add an index to the field\n */\n index: DBFieldIndexMethod<Defined, Output, Nested>;\n\n /**\n * Make the field unique (also adds an index)\n */\n unique: DBFieldUniqueMethod<Defined, Output, Nested>;\n\n /**\n * Enable vector search on the field (string type only)\n */\n vector: DBFieldVectorMethod<Defined, Output, Nested>;\n\n /**\n * Set a default value for the field on create. When the field is required,\n * this makes it optional in the Create input — the default fills in when\n * no value (or a nullish hook result) is provided.\n *\n * For datetime/date/time fields, pass `\"now\"` to use the operation timestamp.\n */\n default: DBFieldDefaultMethod<Defined, Output, Nested>;\n\n /**\n * Add hooks for create/update operations on this field.\n */\n hooks: DBFieldHooksMethod<Defined, Output, Nested>;\n\n /**\n * Add validation functions to the field.\n *\n * Validators receive `{ value, data, user }` and run after hooks and\n * built-in type validation; they are skipped when built-in validation\n * fails. For array fields, `value` is the complete array.\n */\n validate: DBFieldValidateMethod<Defined, Output, Nested>;\n\n /**\n * Configure serial/auto-increment behavior\n */\n serial: DBFieldSerialMethod<Defined, Output, Nested>;\n\n /**\n * Clone the field with optional overrides for field options.\n * The `array` option cannot change on fields with custom validation.\n */\n clone<const NewOpt extends DBFieldCloneOptions<Defined>>(\n options?: NewOpt,\n ): TailorDBField<\n WithDBFieldCloneOptions<Defined, NewOpt>,\n DBFieldCloneOutput<Output, NewOpt>,\n Nested\n >;\n}\n\n/**\n * Full TailorDBType interface with builder methods.\n * Extends the minimal structural interface from types/ with fluent API methods.\n */\nexport interface TailorDBType<\n // oxlint-disable-next-line no-explicit-any\n Fields extends Record<string, TailorAnyDBField> = any,\n User extends object = InferredAttributes,\n // oxlint-disable-next-line no-explicit-any\n Defined extends DefinedDBTypeMetadata = any,\n> extends TailorDBTypeBase<Fields, User> {\n _description?: string;\n\n hooks(\n hook: DBTypeDuplicateInputGuard<\n Defined,\n \"hooks\",\n TypeHook<Fields>,\n \".hooks() has already been set\"\n >,\n ): TailorDBType<Fields, User, WithDBTypeMetadata<Defined, \"hooks\">>;\n validate(\n fn: DBTypeDuplicateInputGuard<\n Defined,\n \"validate\",\n TypeValidateFn<Fields>,\n \".validate() has already been set\"\n >,\n ): TailorDBType<Fields, User, WithDBTypeMetadata<Defined, \"validate\">>;\n features(\n features: DBTypeDuplicateInputGuard<\n Defined,\n \"features\",\n Omit<TypeFeatures, \"pluralForm\">,\n \".features() has already been set\"\n >,\n ): TailorDBType<Fields, User, WithDBTypeMetadata<Defined, \"features\">>;\n indexes(\n ...indexes: DBTypeDuplicateRestGuard<\n Defined,\n \"indexes\",\n IndexDef<TailorDBType<Fields, User, Defined>>[],\n \".indexes() has already been set\"\n >\n ): TailorDBType<Fields, User, WithDBTypeMetadata<Defined, \"indexes\">>;\n files<const F extends string>(\n files: DBTypeDuplicateInputGuard<\n Defined,\n \"files\",\n Record<F, string> & FileKeyConflictError<Fields, User>,\n \".files() has already been set\"\n >,\n ): TailorDBType<Fields, User, WithDBTypeMetadata<Defined, \"files\">>;\n permission<\n U extends object = User,\n P extends TailorTypePermission<U, output<TailorDBType<Fields, User, Defined>>> =\n TailorTypePermission<U, output<TailorDBType<Fields, User, Defined>>>,\n >(\n permission: DBTypeDuplicateInputGuard<\n Defined,\n \"permission\",\n P,\n \".permission() has already been set\"\n >,\n ): TailorDBType<Fields, U, WithDBTypeMetadata<Defined, \"permission\">>;\n gqlPermission<\n U extends object = User,\n P extends TailorTypeGqlPermission<U> = TailorTypeGqlPermission<U>,\n >(\n permission: DBTypeDuplicateInputGuard<\n Defined,\n \"gqlPermission\",\n P,\n \".gqlPermission() has already been set\"\n >,\n ): TailorDBType<Fields, U, WithDBTypeMetadata<Defined, \"gqlPermission\">>;\n description(\n description: DBTypeDuplicateInputGuard<\n Defined,\n \"description\",\n string,\n \".description() has already been set\"\n >,\n ): TailorDBType<Fields, User, WithDBTypeMetadata<Defined, \"description\">>;\n pickFields<K extends keyof Fields>(keys: K[]): Pick<Fields, K>;\n pickFields<K extends keyof Fields, const Opt extends FieldOptions>(\n keys: K[],\n options: Opt & DBFieldsCloneOptionsGuard<Fields, K, Opt>,\n ): {\n [P in K]: Fields[P] extends TailorDBField<infer D, infer O>\n ? TailorDBField<WithDBFieldCloneOptions<D, Opt>, DBFieldCloneOutput<O, Opt>>\n : never;\n };\n omitFields<K extends keyof Fields>(keys: K[]): Omit<Fields, K>;\n plugin<P extends keyof PluginConfigs<keyof Fields & string>>(config: {\n [K in P]: PluginConfigs<keyof Fields & string>[K];\n }): TailorDBType<Fields, User, Defined>;\n}\n\nexport type TailorDBInstance<\n // oxlint-disable-next-line no-explicit-any\n Fields extends Record<string, TailorAnyDBField> = any,\n User extends object = InferredAttributes,\n // oxlint-disable-next-line no-explicit-any\n Defined extends DefinedDBTypeMetadata = any,\n> = TailorDBType<Fields, User, Defined>;\n\ninterface RelationConfig<S extends RelationType, T extends TailorDBType> {\n type: S;\n toward:\n | {\n table: T;\n as?: string;\n key?: keyof T[\"fields\"] & string;\n type?: never;\n }\n | {\n /**\n * @deprecated since 2.6.0 — use `table` instead. codemod: v3/relation-toward-table\n */\n type: T;\n as?: string;\n key?: keyof T[\"fields\"] & string;\n table?: never;\n };\n backward?: string;\n}\n\n// Special config variant for self-referencing relations\ntype RelationSelfConfig = {\n type: RelationType;\n toward:\n | {\n table: \"self\";\n as?: string;\n key?: string;\n type?: never;\n }\n | {\n /**\n * @deprecated since 2.6.0 — use `table` instead. codemod: v3/relation-toward-table\n */\n type: \"self\";\n as?: string;\n key?: string;\n table?: never;\n };\n backward?: string;\n};\n\ntype DBFieldDefined<T extends TailorFieldType, Opt extends FieldOptions> = {\n type: T;\n array: Opt extends { array: true } ? true : false;\n};\ntype DBFieldOutput<\n T extends TailorFieldType,\n Opt extends FieldOptions,\n OutputBase = TailorToTs[T],\n> = FieldOutput<OutputBase, Opt>;\ntype TailorDBFieldInstance<\n T extends TailorFieldType,\n Opt extends FieldOptions,\n OutputBase = TailorToTs[T],\n> = TailorDBField<DBFieldDefined<T, Opt>, DBFieldOutput<T, Opt, OutputBase>>;\ntype TailorDBFieldRuntimeInstance<\n T extends TailorFieldType,\n Opt extends FieldOptions,\n OutputBase = TailorToTs[T],\n> = TailorDBFieldRuntime<DBFieldDefined<T, Opt>, DBFieldOutput<T, Opt, OutputBase>>;\ntype TailorDBFieldRuntime<Defined extends DefinedDBFieldMetadata, Output> = Omit<\n TailorDBFieldBase<Defined, Output>,\n \"fields\"\n> & {\n readonly fields: Record<string, TailorAnyDBField>;\n _metadata: DBFieldMetadata;\n description(description: string): object;\n typeName(typeName: string): object;\n validate(...validate: FieldValidateInput<Output>[]): object;\n relation(config: RelationConfig<RelationType, TailorDBType> | RelationSelfConfig): object;\n index(): object;\n unique(): object;\n vector(): object;\n default(value: unknown): object;\n hooks(hooks: Hook<Output>): object;\n serial(config: SerialConfig): object;\n clone(options?: FieldOptions): TailorDBFieldRuntime<DefinedDBFieldMetadata, AnyBuilderMethod>;\n parse(args: FieldParseArgs): StandardSchemaV1.Result<Output>;\n _setRawRelation(relation: RawRelationConfig): void;\n};\n\n/**\n * Creates a new TailorDBField instance.\n * @param type - Field type\n * @param options - Field options\n * @param fields - Nested fields for object-like types\n * @param values - Allowed values for enum-like fields\n * @returns A new TailorDBField\n */\nfunction createTailorDBField<\n const T extends TailorFieldType,\n const TOptions extends FieldOptions,\n const OutputBase = TailorToTs[T],\n>(\n type: T,\n options?: TOptions,\n fields?: Record<string, TailorAnyDBField>,\n values?: AllowedValues,\n): TailorDBFieldInstance<T, TOptions, OutputBase>;\nfunction createTailorDBField<const T extends TailorFieldType, const TOptions extends FieldOptions>(\n type: T,\n options?: TOptions,\n fields?: Record<string, TailorAnyDBField>,\n values?: AllowedValues,\n): object {\n return createTailorDBFieldRuntime(type, options, fields, values);\n}\n\nfunction createTailorDBFieldRuntime<\n const T extends TailorFieldType,\n const TOptions extends FieldOptions,\n const OutputBase = TailorToTs[T],\n>(\n type: T,\n options?: TOptions,\n fields?: Record<string, TailorAnyDBField>,\n values?: AllowedValues,\n): TailorDBFieldRuntimeInstance<T, TOptions, OutputBase> {\n type FieldValue = DBFieldOutput<T, TOptions, OutputBase>;\n type FieldType = TailorDBFieldRuntimeInstance<T, TOptions, OutputBase>;\n\n const _metadata: DBFieldMetadata = { required: true };\n let _rawRelation: RawRelationConfig | undefined;\n\n if (options) {\n if (options.optional === true) {\n _metadata.required = false;\n }\n if (options.array === true) {\n _metadata.array = true;\n }\n }\n if (values) {\n _metadata.allowedValues = mapAllowedValues(values);\n }\n\n function parseInternal(args: FieldParseInternalArgs): StandardSchemaV1.Result<FieldValue> {\n return parseFieldInternal<T, FieldValue>({\n ...args,\n field,\n });\n }\n\n function cloneWith(metadataUpdates: Partial<DBFieldMetadata>) {\n const cloned = field.clone();\n Object.assign(cloned._metadata, metadataUpdates);\n return cloned;\n }\n\n const field: FieldType = {\n type,\n fields: fields ?? {},\n _defined: undefined as unknown as DBFieldDefined<T, TOptions>,\n _output: undefined as FieldValue,\n _metadata,\n\n get metadata() {\n return { ...this._metadata };\n },\n\n get rawRelation(): Readonly<RawRelationConfig> | undefined {\n return _rawRelation ? { ..._rawRelation, toward: { ..._rawRelation.toward } } : undefined;\n },\n\n description(description: string) {\n return cloneWith({ description });\n },\n\n typeName(typeName: string) {\n return cloneWith({ typeName });\n },\n\n validate(...validateInputs: FieldValidateInput<FieldValue>[]) {\n return cloneWith({ validate: validateInputs });\n },\n\n parse(args: FieldParseArgs): StandardSchemaV1.Result<FieldValue> {\n return parseInternal({\n value: args.value,\n data: args.data,\n invoker: args.invoker,\n pathArray: [],\n });\n },\n\n // TailorDBField specific methods\n relation(config: RelationConfig<RelationType, TailorDBType> | RelationSelfConfig) {\n const cloned = field.clone();\n // The public type is a nested union (RelationConfig | RelationSelfConfig,\n // each with a `{ table } | { type }` toward), which TS's \"in\" narrowing\n // can't discriminate across cleanly. Re-view it as the flat two-branch\n // shape it always is at runtime — the `table?: never` / `type?: never`\n // markers above already forbid both keys from being set together.\n const toward = config.toward as\n | { table: TailorDBType | \"self\" }\n | { type: TailorDBType | \"self\" };\n const towardTarget = \"table\" in toward ? toward.table : toward.type;\n const targetTable = towardTarget === \"self\" ? \"self\" : towardTarget.name;\n cloned._setRawRelation({\n type: config.type,\n toward: {\n table: targetTable,\n as: config.toward.as,\n key: config.toward.key,\n },\n backward: config.backward,\n });\n return cloned;\n },\n\n index() {\n return cloneWith({ index: true });\n },\n\n unique() {\n return cloneWith({ unique: true, index: true });\n },\n\n vector() {\n return cloneWith({ vector: true });\n },\n\n // oxlint-disable-next-line no-explicit-any\n default(value: any) {\n // oxlint-disable-next-line no-explicit-any\n return cloneWith({ default: value }) as any;\n },\n\n hooks(hooks: Hook<FieldValue>) {\n return cloneWith({ hooks });\n },\n\n serial(config: SerialConfig) {\n return cloneWith({ serial: config });\n },\n\n clone(cloneOptions?: FieldOptions) {\n if (\n this._metadata.validate?.length &&\n cloneOptions?.array !== undefined &&\n cloneOptions.array !== (this._metadata.array === true)\n ) {\n throw new Error(\"Cannot change the array option on a field with custom validation\");\n }\n\n // Deep clone nested object fields if present\n let clonedFields = fields;\n if (fields) {\n const cloned: Record<string, TailorAnyDBField> = {};\n for (const [key, field] of Object.entries(fields)) {\n cloned[key] = field.clone();\n }\n clonedFields = cloned;\n }\n\n // Create a new field with cloned configuration\n const clonedField = createTailorDBFieldRuntime(type, options, clonedFields, values);\n\n // Deep copy metadata using cloneDeep (preserves function references)\n Object.assign(clonedField._metadata, cloneDeep(this._metadata));\n\n // Apply new options if provided\n if (cloneOptions) {\n if (cloneOptions.optional !== undefined) {\n clonedField._metadata.required = !cloneOptions.optional;\n }\n if (cloneOptions.array !== undefined) {\n clonedField._metadata.array = cloneOptions.array;\n }\n }\n\n // Copy raw relation if exists\n if (_rawRelation) {\n clonedField._setRawRelation(cloneDeep(_rawRelation));\n }\n\n return clonedField;\n },\n\n _setRawRelation(relation: RawRelationConfig) {\n _rawRelation = relation;\n },\n };\n\n return field;\n}\n\nconst createField = createTailorDBField;\n\n/**\n * Create a UUID field.\n * @param options - Field configuration options\n * @returns A UUID field\n * @example db.uuid()\n * @example db.uuid({ optional: true })\n */\nfunction uuid<const Opt extends FieldOptions>(options?: Opt) {\n return createField(\"uuid\", options);\n}\n\n/**\n * Create a string field.\n * @param options - Field configuration options\n * @returns A string field\n * @example db.string()\n * @example db.string({ optional: true })\n */\nfunction string<const Opt extends FieldOptions>(options?: Opt) {\n return createField(\"string\", options);\n}\n\n/**\n * Create a boolean field.\n * Note: The method name is `bool` but creates a `boolean` type field.\n * @param options - Field configuration options\n * @returns A boolean field\n * @example db.bool()\n * @example db.bool({ optional: true })\n */\nfunction bool<const Opt extends FieldOptions>(options?: Opt) {\n return createField(\"boolean\", options);\n}\n\n/**\n * Create an integer field.\n * @param options - Field configuration options\n * @returns An integer field\n * @example db.int()\n * @example db.int({ optional: true })\n */\nfunction int<const Opt extends FieldOptions>(options?: Opt) {\n return createField(\"integer\", options);\n}\n\n/**\n * Create a float (decimal number) field.\n * @param options - Field configuration options\n * @returns A float field\n * @example db.float()\n * @example db.float({ optional: true })\n */\nfunction float<const Opt extends FieldOptions>(options?: Opt) {\n return createField(\"float\", options);\n}\n\ninterface DecimalFieldOptions extends FieldOptions {\n scale?: number;\n}\n\n/**\n * Create a decimal field (stored as string for precision).\n * @param options - Field configuration options including optional scale (0-12)\n * @returns A decimal field\n * @example db.decimal()\n * @example db.decimal({ scale: 2 })\n * @example db.decimal({ scale: 2, optional: true })\n */\nfunction decimal<const Opt extends DecimalFieldOptions>(options?: Opt) {\n if (options?.scale !== undefined) {\n if (!Number.isInteger(options.scale) || options.scale < 0 || options.scale > 12) {\n throw new Error(\"scale must be an integer between 0 and 12\");\n }\n }\n const field = createField(\"decimal\", options);\n if (options?.scale !== undefined) {\n field._metadata.scale = options.scale;\n }\n return field;\n}\n\n/**\n * Create a date field (date only, no time component).\n * Format: \"yyyy-MM-dd\"\n * @param options - Field configuration options\n * @returns A date field\n * @example db.date()\n */\nfunction date<const Opt extends FieldOptions>(options?: Opt) {\n return createField(\"date\", options);\n}\n\n/**\n * Create a datetime field (date and time).\n * Format: ISO 8601, such as \"yyyy-MM-ddTHH:mm:ssZ\" or \"yyyy-MM-ddTHH:mm:ss+09:00\"\n * @param options - Field configuration options\n * @returns A datetime field\n * @example db.datetime()\n */\nfunction datetime<const Opt extends FieldOptions>(options?: Opt) {\n return createField(\"datetime\", options);\n}\n\n/**\n * Create a time field (time only, no date component).\n * Format: \"HH:mm\"\n * @param options - Field configuration options\n * @returns A time field\n * @example db.time()\n */\nfunction time<const Opt extends FieldOptions>(options?: Opt) {\n return createField(\"time\", options);\n}\n\n/**\n * Create an enum field with a fixed set of allowed string values.\n * @param values - Array of allowed string values, or array of `{ value, description }` objects\n * @param options - Field configuration options\n * @returns An enum field\n * @example db.enum([\"active\", \"inactive\", \"suspended\"])\n * @example db.enum([\"small\", \"medium\", \"large\"], { optional: true })\n */\nfunction _enum<const V extends AllowedValues, const Opt extends FieldOptions>(\n values: V,\n options?: Opt,\n): TailorDBField<\n { type: \"enum\"; array: Opt extends { array: true } ? true : false },\n FieldOutput<AllowedValuesOutput<V>, Opt>\n> {\n return createField<\"enum\", Opt, AllowedValuesOutput<V>>(\"enum\", options, undefined, values);\n}\n\n/**\n * Create a nested object field with sub-fields.\n * @param fields - Record of nested field definitions\n * @param options - Field configuration options\n * @returns A nested object field\n * @example db.object({ street: db.string(), city: db.string(), zip: db.string() })\n * @example db.object({ name: db.string() }, { optional: true })\n */\nfunction object<\n const F extends Record<string, TailorAnyDBField> &\n ExcludeNestedDBFields<F> &\n ExcludeHookedDBFields<F> &\n ExcludeDefaultedDBFields<F>,\n const Opt extends FieldOptions,\n>(fields: F, options?: Opt) {\n return createField(\"nested\", options, fields) as unknown as TailorDBField<\n { type: \"nested\"; array: Opt extends { array: true } ? true : false },\n FieldOutput<InferFieldsOutput<F>, Opt>,\n F\n >;\n}\n\n/**\n * Creates a new TailorDBType instance.\n * @param name - Table name\n * @param fields - Field definitions\n * @param options - Table options\n * @param options.pluralForm - Optional plural form\n * @param options.description - Optional description\n * @returns A new TailorDBType\n */\nfunction createTailorDBType<\n // oxlint-disable-next-line no-explicit-any\n const Fields extends Record<string, TailorAnyDBField> = any,\n User extends object = InferredAttributes,\n>(\n name: string,\n fields: Fields,\n options: { pluralForm?: string; description?: string },\n): TailorDBType<Fields, User, DefinedDBTypeMetadata> {\n let _description = options.description;\n let _settings: TypeFeatures = {};\n let _indexes: IndexDef<TailorDBType<Fields, User, DefinedDBTypeMetadata>>[] = [];\n const _permissions: RawPermissions = {};\n let _files: Record<string, string> = {};\n const _plugins: PluginAttachment[] = [];\n // oxlint-disable-next-line typescript/no-unsafe-function-type\n let _typeHook: { create?: Function; update?: Function } | undefined;\n // oxlint-disable-next-line typescript/no-unsafe-function-type\n let _typeValidate: Function | undefined;\n const _definedMethods = new Set<keyof DefinedDBTypeMetadata>();\n if (options.description !== undefined) {\n _definedMethods.add(\"description\");\n }\n\n function runMethodOnce<T>(method: keyof DefinedDBTypeMetadata, action: () => T): T {\n if (_definedMethods.has(method)) {\n throw new Error(`.${method}() has already been set`);\n }\n const result = action();\n _definedMethods.add(method);\n return result;\n }\n type TypeAfter<Key extends keyof DefinedDBTypeMetadata> = TailorDBType<\n Fields,\n User,\n WithDBTypeMetadata<DefinedDBTypeMetadata, Key>\n >;\n type TypeAfterUser<\n NextUser extends object,\n Key extends keyof DefinedDBTypeMetadata,\n > = TailorDBType<Fields, NextUser, WithDBTypeMetadata<DefinedDBTypeMetadata, Key>>;\n\n if (options.pluralForm) {\n if (name === options.pluralForm) {\n throw new Error(`The name and the plural form must be different. name=${name}`);\n }\n _settings.pluralForm = options.pluralForm;\n }\n\n const dbType: TailorDBType<Fields, User, DefinedDBTypeMetadata> = {\n name,\n fields: { ...fields },\n _output: null as unknown as InferFieldsOutput<Fields>,\n _description,\n\n get metadata(): TailorDBTypeMetadata {\n // Convert indexes to the format expected by the manifest\n const indexes: Record<string, { fields: string[]; unique?: boolean }> = {};\n if (_indexes.length > 0) {\n _indexes.forEach((index) => {\n const fieldNames = index.fields.map((field) => String(field));\n const key = index.name || `idx_${fieldNames.join(\"_\")}`;\n indexes[key] = {\n fields: fieldNames,\n unique: index.unique,\n };\n });\n }\n\n return {\n name: this.name,\n description: _description,\n settings: _settings,\n permissions: _permissions,\n files: _files,\n ...(Object.keys(indexes).length > 0 && { indexes }),\n ...(_typeHook && { typeHook: _typeHook }),\n ...(_typeValidate && { typeValidate: _typeValidate }),\n };\n },\n\n hooks(hook: TypeHook<Fields>): TypeAfter<\"hooks\"> {\n return runMethodOnce(\"hooks\", () => {\n _typeHook = hook;\n return this as TypeAfter<\"hooks\">;\n });\n },\n\n validate(fn: TypeValidateFn<Fields>): TypeAfter<\"validate\"> {\n return runMethodOnce(\"validate\", () => {\n _typeValidate = fn;\n return this as TypeAfter<\"validate\">;\n });\n },\n\n features(features: Omit<TypeFeatures, \"pluralForm\">): TypeAfter<\"features\"> {\n return runMethodOnce(\"features\", () => {\n _settings = {\n ..._settings,\n ...features,\n };\n return this as TypeAfter<\"features\">;\n });\n },\n\n indexes(\n ...indexes: IndexDef<TailorDBType<Fields, User, DefinedDBTypeMetadata>>[]\n ): TypeAfter<\"indexes\"> {\n return runMethodOnce(\"indexes\", () => {\n _indexes = indexes;\n return this as TypeAfter<\"indexes\">;\n });\n },\n\n files<const F extends string>(\n files: Record<F, string> & FileKeyConflictError<Fields, User>,\n ): TypeAfter<\"files\"> {\n return runMethodOnce(\"files\", () => {\n _files = files;\n return this as TypeAfter<\"files\">;\n });\n },\n\n permission<\n U extends object = User,\n P extends TailorTypePermission<U, output<TailorDBType<Fields, User, DefinedDBTypeMetadata>>> =\n TailorTypePermission<U, output<TailorDBType<Fields, User, DefinedDBTypeMetadata>>>,\n >(permission: P): TypeAfterUser<U, \"permission\"> {\n return runMethodOnce(\"permission\", () => {\n const ret = this as unknown as TypeAfterUser<U, \"permission\">;\n _permissions.record = permission as RawPermissions[\"record\"];\n return ret;\n });\n },\n\n gqlPermission<\n U extends object = User,\n P extends TailorTypeGqlPermission<U> = TailorTypeGqlPermission<U>,\n >(permission: P): TypeAfterUser<U, \"gqlPermission\"> {\n return runMethodOnce(\"gqlPermission\", () => {\n const ret = this as unknown as TypeAfterUser<U, \"gqlPermission\">;\n _permissions.gql = permission as RawPermissions[\"gql\"];\n return ret;\n });\n },\n\n description(description: string): TypeAfter<\"description\"> {\n return runMethodOnce(\"description\", () => {\n _description = description;\n this._description = description;\n return this as TypeAfter<\"description\">;\n });\n },\n\n pickFields<K extends keyof Fields, const Opt extends FieldOptions>(keys: K[], options?: Opt) {\n const result = {} as Record<K, TailorAnyDBField>;\n for (const key of keys) {\n const field = this.fields[key] as TailorAnyDBField;\n if (options) {\n result[key] = field.clone(options);\n } else {\n result[key] = field;\n }\n }\n // oxlint-disable-next-line no-explicit-any\n return result as any;\n },\n\n omitFields<K extends keyof Fields>(keys: K[]): Omit<Fields, K> {\n const keysSet = new Set(keys);\n const result = {} as Record<string, TailorAnyDBField>;\n for (const key in this.fields) {\n if (Object.hasOwn(this.fields, key) && !keysSet.has(key as unknown as K)) {\n result[key] = this.fields[key] as TailorAnyDBField;\n }\n }\n return result as Omit<Fields, K>;\n },\n\n get plugins(): PluginAttachment[] {\n return _plugins;\n },\n\n plugin<P extends keyof PluginConfigs<keyof Fields & string>>(config: {\n [K in P]: PluginConfigs<keyof Fields & string>[K];\n }): TailorDBType<Fields, User, AnyBuilderMethod> {\n for (const [pluginId, pluginConfig] of Object.entries(config)) {\n _plugins.push({ pluginId, config: pluginConfig });\n }\n return this;\n },\n };\n\n return brandValue(dbType, \"tailordb-type\");\n}\n\nconst idField = uuid();\ntype idField = typeof idField;\ntype DBTable<\n F extends { id?: never } & Record<string, TailorAnyDBField>,\n Defined extends DefinedDBTypeMetadata = DefinedDBTypeMetadata,\n> = TailorDBInstance<{ id: idField } & F, InferredAttributes, Defined>;\n\n/**\n * Creates a new database table with the specified fields.\n * An `id` field (UUID) is automatically added to every table.\n * @param name - The name of the table, or a tuple of [name, pluralForm]\n * @param fields - The field definitions for the table\n * @returns A new TailorDB table instance\n * @example\n * export const user = db.table(\"User\", {\n * name: db.string(),\n * email: db.string(),\n * age: db.int({ optional: true }),\n * role: db.enum([\"admin\", \"member\"]),\n * ...db.fields.timestamps(),\n * });\n * // Always export both the value and type:\n * export type user = typeof user;\n */\nfunction dbTable<const F extends { id?: never } & Record<string, TailorAnyDBField>>(\n name: string | [string, string],\n fields: F,\n): DBTable<F>;\n/**\n * Creates a new database table with the specified fields and description.\n * An `id` field (UUID) is automatically added to every table.\n * @param name - The name of the table, or a tuple of [name, pluralForm]\n * @param description - A description of the table\n * @param fields - The field definitions for the table\n * @returns A new TailorDB table instance\n */\nfunction dbTable<const F extends { id?: never } & Record<string, TailorAnyDBField>>(\n name: string | [string, string],\n description: string,\n fields: F,\n): DBTable<F, WithDBTypeMetadata<DefinedDBTypeMetadata, \"description\">>;\nfunction dbTable<const F extends { id?: never } & Record<string, TailorAnyDBField>>(\n name: string | [string, string],\n fieldsOrDescription: string | F,\n fields?: F,\n): DBTable<F> | DBTable<F, WithDBTypeMetadata<DefinedDBTypeMetadata, \"description\">> {\n const typeName = Array.isArray(name) ? name[0] : name;\n const pluralForm = Array.isArray(name) ? name[1] : undefined;\n\n let description: string | undefined;\n let fieldDef: F;\n if (typeof fieldsOrDescription === \"string\") {\n description = fieldsOrDescription;\n fieldDef = fields as F;\n } else {\n fieldDef = fieldsOrDescription;\n }\n return createTailorDBType<{ id: idField } & F>(\n typeName,\n {\n id: idField,\n ...fieldDef,\n },\n { pluralForm, description },\n );\n}\n\n// `Function.prototype.toString()` of this hook is embedded verbatim into deployed\n// schemas and migration diffs (see parser/service/tailordb/hooks-validate-precompiled-expr.ts\n// and field.ts). Its source text depends on how the SDK itself was built (e.g.\n// minification), so a fixed expression is pinned onto it directly here instead -\n// configure cannot import parser's `setPrecompiledScriptExpr` runtime helper across\n// the module boundary, only the symbol registry key and map types. Keep\n// this literal in sync with the \"timestamps() updatedAt hook resolves to the pinned\n// expr\" test in parser/service/tailordb/field.precompiled.test.ts, which fails if it\n// ever drifts from what this hook's own source naturally produces.\ntype TimestampsUpdatedAtHookFn = UpdateHookFn<string | Date | null, string | Date>;\nconst timestampsUpdatedAtHook: TimestampsUpdatedAtHookFn = ({ input, now }) => input ?? now;\nconst PRECOMPILED_EXPR_KEY: PrecompiledScriptExprKey =\n \"tailor-platform/sdk:precompiled-script-expr\";\nconst PRECOMPILED_EXPR_SYMBOL = Symbol.for(PRECOMPILED_EXPR_KEY);\n(timestampsUpdatedAtHook as unknown as Record<symbol, PrecompiledScriptExprMap>)[\n PRECOMPILED_EXPR_SYMBOL\n] = {\n \"hooks.update\":\n \"(({ input, now }) => input ?? now)({ input: _value, oldValue: _oldValue, invoker: _principal, now: _now })\",\n};\n\n/** TailorDB schema builder utilities for defining tables and fields. */\nexport const db = {\n table: dbTable,\n uuid,\n string,\n bool,\n int,\n float,\n decimal,\n date,\n datetime,\n time,\n enum: _enum,\n object,\n fields: {\n /**\n * Creates standard timestamp fields (createdAt, updatedAt) with automatic defaults.\n * Both fields default to the current time on create. updatedAt is also refreshed on update.\n * User-specified values are respected when provided (e.g. seeding historical records).\n * @returns An object with createdAt and updatedAt fields\n * @example\n * const model = db.table(\"Model\", {\n * name: db.string(),\n * ...db.fields.timestamps(),\n * });\n */\n timestamps: () => ({\n createdAt: datetime().default(\"now\").description(\"Record creation timestamp\"),\n updatedAt: datetime()\n .default(\"now\")\n .hooks({ update: timestampsUpdatedAtHook })\n .description(\"Record update timestamp\"),\n }),\n },\n};\n"],"mappings":"gFAIA,MAAM,EAAQ,CACZ,KAAM,kEACN,KAAM,iDACN,KAAM,8CACN,SACE,sLACF,QAAS,sCACX,EA6BA,SAAS,kBAA6C,EAAuC,CAC3F,GAAM,CAAE,QAAO,QAAO,YAAW,UAAW,EACtC,EAAO,EAAU,OAAS,EAAI,EAAY,IAAA,GAC1C,EAAoB,EAAO,OAEjC,OAAQ,EAAM,KAAd,CACE,IAAK,SACC,OAAO,GAAU,UACnB,EAAO,KAAK,CACV,QAAS,+BAA+B,OAAO,CAAK,IACpD,MACF,CAAC,EAEH,MAEF,IAAK,WACC,OAAO,GAAU,UAAY,CAAC,OAAO,UAAU,CAAK,IACtD,EAAO,KAAK,CACV,QAAS,iCAAiC,OAAO,CAAK,IACtD,MACF,CAAC,EAEH,MAEF,IAAK,SACC,OAAO,GAAU,UAAY,CAA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A,KACA,IACA,MACA,QACA,KACA,SACA,KACA,KAAM,MACN,OACA,OAAQ,CAYN,gBAAmB,CACjB,UAAW,SAAS,CAAC,CAAC,QAAQ,KAAK,CAAC,CAAC,YAAY,2BAA2B,EAC5E,UAAW,SAAS,CAAC,CAClB,QAAQ,KAAK,CAAC,CACd,MAAM,CAAE,OAAQ,uBAAwB,CAAC,CAAC,CAC1C,YAAY,yBAAyB,CAC1C,EACF,CACF"}
@@ -1,2 +1,2 @@
1
- import{n as e,r as t}from"./logger-BcGy-u7G.mjs";import{t as n}from"./errors-DSEXKRVD.mjs";import*as r from"pathe";import{readPackageJSON as i}from"pkg-types";import{spawnSync as a}from"node:child_process";async function detectInstalledVersion(e){let t=r.resolve(e);for(;;){try{let e=r.join(t,`node_modules`,`@tailor-platform/sdk`),n=await i(e);if(n.version)return n.version}catch{}let e=r.dirname(t);if(e===t)break;t=e}return null}function printUpgradeSummary(n,r){r&&(e.info(`${t.bold(`[Dry Run]`)} No files were modified.`),e.log(``));let i=n.codemodsApplied+n.codemodsSkipped+n.errors.length;if(e.info(`Upgrade complete: ${t.success(`${n.codemodsApplied} applied`)}, ${t.dim(`${n.codemodsSkipped} skipped`)} (${i} total codemods)`),n.filesModified.length>0){e.log(``),e.info(`${r?`Files that would be modified`:`Modified files`} (${n.filesModified.length}):`);for(let r of n.filesModified)e.log(` ${t.path(r)}`)}if(n.warnings.length>0){e.log(``),e.warn(`Manual attention needed (${n.warnings.length}):`);for(let r of n.warnings)e.log(` ${t.warning(`!`)} ${r}`)}if(n.errors.length>0){e.log(``),e.error(`Failed codemods (${n.errors.length}):`);for(let{codemodId:r,message:i}of n.errors)e.log(` ${t.error(r)}: ${i}`)}}async function upgrade(r){let i=r.path,o=await detectInstalledVersion(i);if(!o)throw n({message:`Could not detect installed @tailor-platform/sdk version in ${i}`,suggestion:`Ensure @tailor-platform/sdk is installed. Run 'pnpm install' or 'npm install' first.`,command:`upgrade`});e.info(`Upgrading from ${t.highlight(r.from)} → ${t.highlight(o)}`),r.dryRun&&e.info(`${t.bold(`[Dry Run]`)} Changes will be previewed but not applied.`),e.log(``);let s=process.platform===`win32`?`npx.cmd`:`npx`,c=a(s,[`@tailor-platform/sdk-codemod@latest`,`--from`,r.from,`--to`,o,`--target`,i,...r.dryRun?[`--dry-run`]:[]],{cwd:i,stdio:[`ignore`,`pipe`,`pipe`],encoding:`utf-8`,timeout:3e5});if(c.error)throw n({message:`Failed to run @tailor-platform/sdk-codemod: ${c.error.message}`,suggestion:`Ensure npx is available and the network is accessible.`,command:`upgrade`});if(c.status!==0&&!c.stdout.trim())throw n({message:`@tailor-platform/sdk-codemod exited with code ${c.status}`,details:c.stderr.trim()||`(no stderr output)`,suggestion:`Review the error above. Common causes: invalid version arguments, network issues, or missing package registry access.`,command:`upgrade`});c.stderr&&process.stderr.write(c.stderr);let l;try{l=JSON.parse(c.stdout)}catch{throw n({message:`Failed to parse output from @tailor-platform/sdk-codemod`,details:c.stdout||`(empty stdout)`,suggestion:`This is likely a bug. Please report it.`,command:`upgrade`})}if(e.out(l),printUpgradeSummary(l,r.dryRun),l.errors.length>0)throw n({message:`Upgrade completed with ${l.errors.length} error(s)`,suggestion:`Review the errors above and re-run the upgrade after fixing the issues.`,command:`upgrade`})}export{upgrade};
2
- //# sourceMappingURL=service-DlgaUO4V.mjs.map
1
+ import{n as e,r as t}from"./logger-CCjs1DuH.mjs";import{t as n}from"./errors-DLsQ_-ol.mjs";import*as r from"pathe";import{readPackageJSON as i}from"pkg-types";import{spawnSync as a}from"node:child_process";async function detectInstalledVersion(e){let t=r.resolve(e);for(;;){try{let e=r.join(t,`node_modules`,`@tailor-platform/sdk`),n=await i(e);if(n.version)return n.version}catch{}let e=r.dirname(t);if(e===t)break;t=e}return null}function printUpgradeSummary(n,r){r&&(e.info(`${t.bold(`[Dry Run]`)} No files were modified.`),e.log(``));let i=n.codemodsApplied+n.codemodsSkipped+n.errors.length;if(e.info(`Upgrade complete: ${t.success(`${n.codemodsApplied} applied`)}, ${t.dim(`${n.codemodsSkipped} skipped`)} (${i} total codemods)`),n.filesModified.length>0){e.log(``),e.info(`${r?`Files that would be modified`:`Modified files`} (${n.filesModified.length}):`);for(let r of n.filesModified)e.log(` ${t.path(r)}`)}if(n.warnings.length>0){e.log(``),e.warn(`Manual attention needed (${n.warnings.length}):`);for(let r of n.warnings)e.log(` ${t.warning(`!`)} ${r}`)}if(n.errors.length>0){e.log(``),e.error(`Failed codemods (${n.errors.length}):`);for(let{codemodId:r,message:i}of n.errors)e.log(` ${t.error(r)}: ${i}`)}}async function upgrade(r){let i=r.path,o=await detectInstalledVersion(i);if(!o)throw n({message:`Could not detect installed @tailor-platform/sdk version in ${i}`,suggestion:`Ensure @tailor-platform/sdk is installed. Run 'pnpm install' or 'npm install' first.`,command:`upgrade`});e.info(`Upgrading from ${t.highlight(r.from)} → ${t.highlight(o)}`),r.dryRun&&e.info(`${t.bold(`[Dry Run]`)} Changes will be previewed but not applied.`),e.log(``);let s=process.platform===`win32`?`npx.cmd`:`npx`,c=a(s,[`@tailor-platform/sdk-codemod@latest`,`--from`,r.from,`--to`,o,`--target`,i,...r.dryRun?[`--dry-run`]:[]],{cwd:i,stdio:[`ignore`,`pipe`,`pipe`],encoding:`utf-8`,timeout:3e5});if(c.error)throw n({message:`Failed to run @tailor-platform/sdk-codemod: ${c.error.message}`,suggestion:`Ensure npx is available and the network is accessible.`,command:`upgrade`});if(c.status!==0&&!c.stdout.trim())throw n({message:`@tailor-platform/sdk-codemod exited with code ${c.status}`,details:c.stderr.trim()||`(no stderr output)`,suggestion:`Review the error above. Common causes: invalid version arguments, network issues, or missing package registry access.`,command:`upgrade`});c.stderr&&process.stderr.write(c.stderr);let l;try{l=JSON.parse(c.stdout)}catch{throw n({message:`Failed to parse output from @tailor-platform/sdk-codemod`,details:c.stdout||`(empty stdout)`,suggestion:`This is likely a bug. Please report it.`,command:`upgrade`})}if(e.out(l),printUpgradeSummary(l,r.dryRun),l.errors.length>0)throw n({message:`Upgrade completed with ${l.errors.length} error(s)`,suggestion:`Review the errors above and re-run the upgrade after fixing the issues.`,command:`upgrade`})}export{upgrade};
2
+ //# sourceMappingURL=service-CLPMoj9n.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"service-DlgaUO4V.mjs","names":["CLIError"],"sources":["../src/cli/commands/upgrade/version-detector.ts","../src/cli/commands/upgrade/service.ts"],"sourcesContent":["import * as path from \"pathe\";\nimport { readPackageJSON } from \"pkg-types\";\n\nconst SDK_PACKAGE_NAME = \"@tailor-platform/sdk\";\n\n/**\n * Detect the installed SDK version from the user's project.\n * Walks up from projectRoot to find the SDK package in node_modules,\n * matching Node's module resolution for workspace setups with hoisted deps.\n * @param projectRoot - The project root directory to search from\n * @returns The installed SDK version string, or null if not found\n */\nexport async function detectInstalledVersion(projectRoot: string): Promise<string | null> {\n let dir = path.resolve(projectRoot);\n // loop exits when a package.json is found or the root is reached\n // oxlint-disable-next-line typescript/no-unnecessary-condition\n while (true) {\n try {\n const sdkPath = path.join(dir, \"node_modules\", SDK_PACKAGE_NAME);\n const pkg = await readPackageJSON(sdkPath);\n if (pkg.version) return pkg.version;\n } catch {\n // Not found at this level, try parent\n }\n const parent = path.dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n return null;\n}\n","import { spawnSync } from \"node:child_process\";\nimport { CLIError } from \"#/cli/shared/errors\";\nimport { logger, styles } from \"#/cli/shared/logger\";\nimport { detectInstalledVersion } from \"./version-detector\";\nimport type { RunOutput } from \"./types\";\n\ninterface UpgradeOptions {\n from: string;\n dryRun: boolean;\n path: string;\n}\n\n/**\n * Print the upgrade summary to the terminal.\n * @param output - The parsed JSON output from sdk-codemod\n * @param dryRun - Whether this was a dry-run\n */\nfunction printUpgradeSummary(output: RunOutput, dryRun: boolean): void {\n if (dryRun) {\n logger.info(`${styles.bold(\"[Dry Run]\")} No files were modified.`);\n logger.log(\"\");\n }\n\n const total = output.codemodsApplied + output.codemodsSkipped + output.errors.length;\n logger.info(\n `Upgrade complete: ${styles.success(`${output.codemodsApplied} applied`)}, ${styles.dim(`${output.codemodsSkipped} skipped`)} (${total} total codemods)`,\n );\n\n if (output.filesModified.length > 0) {\n logger.log(\"\");\n logger.info(\n `${dryRun ? \"Files that would be modified\" : \"Modified files\"} (${output.filesModified.length}):`,\n );\n for (const file of output.filesModified) {\n logger.log(` ${styles.path(file)}`);\n }\n }\n\n if (output.warnings.length > 0) {\n logger.log(\"\");\n logger.warn(`Manual attention needed (${output.warnings.length}):`);\n for (const warning of output.warnings) {\n logger.log(` ${styles.warning(\"!\")} ${warning}`);\n }\n }\n\n if (output.errors.length > 0) {\n logger.log(\"\");\n logger.error(`Failed codemods (${output.errors.length}):`);\n for (const { codemodId, message } of output.errors) {\n logger.log(` ${styles.error(codemodId)}: ${message}`);\n }\n }\n}\n\n/**\n * Run the upgrade pipeline:\n * 1. Detect target SDK version from node_modules\n * 2. Invoke @tailor-platform/sdk-codemod CLI\n * 3. Parse JSON output and display results\n * @param options - Upgrade options\n */\nexport async function upgrade(options: UpgradeOptions): Promise<void> {\n const projectRoot = options.path;\n\n // Step 1: Detect target SDK version (the newly installed version)\n const targetVersion = await detectInstalledVersion(projectRoot);\n if (!targetVersion) {\n throw CLIError({\n message: `Could not detect installed @tailor-platform/sdk version in ${projectRoot}`,\n suggestion:\n \"Ensure @tailor-platform/sdk is installed. Run 'pnpm install' or 'npm install' first.\",\n command: \"upgrade\",\n });\n }\n\n logger.info(\n `Upgrading from ${styles.highlight(options.from)} → ${styles.highlight(targetVersion)}`,\n );\n\n if (options.dryRun) {\n logger.info(`${styles.bold(\"[Dry Run]\")} Changes will be previewed but not applied.`);\n }\n\n logger.log(\"\");\n\n // Step 2: Invoke sdk-codemod CLI\n // Use \"latest\" because sdk-codemod may not be published at the exact same\n // version as @tailor-platform/sdk. Version filtering is handled internally\n // by sdk-codemod's registry via the --from / --to arguments.\n const npxCommand = process.platform === \"win32\" ? \"npx.cmd\" : \"npx\";\n\n const result = spawnSync(\n npxCommand,\n [\n \"@tailor-platform/sdk-codemod@latest\",\n \"--from\",\n options.from,\n \"--to\",\n targetVersion,\n \"--target\",\n projectRoot,\n ...(options.dryRun ? [\"--dry-run\"] : []),\n ],\n {\n cwd: projectRoot,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n encoding: \"utf-8\",\n timeout: 300_000,\n },\n );\n\n if (result.error) {\n throw CLIError({\n message: `Failed to run @tailor-platform/sdk-codemod: ${result.error.message}`,\n suggestion: \"Ensure npx is available and the network is accessible.\",\n command: \"upgrade\",\n });\n }\n\n // Check for non-zero exit without a launch error (e.g. registry/auth/network failures)\n if (result.status !== 0 && !result.stdout.trim()) {\n throw CLIError({\n message: `@tailor-platform/sdk-codemod exited with code ${result.status}`,\n details: result.stderr.trim() || \"(no stderr output)\",\n suggestion:\n \"Review the error above. Common causes: invalid version arguments, network issues, or missing package registry access.\",\n command: \"upgrade\",\n });\n }\n\n // Forward captured stderr so users see dry-run diffs and progress messages\n // written by sdk-codemod. stderr is piped (not inherited) so that the error\n // path above can surface it via CLIError, but on success we still need to\n // replay it verbatim to keep the colorized unified diff output visible.\n if (result.stderr) {\n process.stderr.write(result.stderr);\n }\n\n // Step 3: Parse JSON output\n let output: RunOutput;\n try {\n output = JSON.parse(result.stdout);\n } catch {\n throw CLIError({\n message: \"Failed to parse output from @tailor-platform/sdk-codemod\",\n details: result.stdout || \"(empty stdout)\",\n suggestion: \"This is likely a bug. Please report it.\",\n command: \"upgrade\",\n });\n }\n\n // Step 4: Display results\n // Emit structured data on stdout (honors --json via logger.out) and\n // human-readable summary on stderr (via printUpgradeSummary).\n logger.out(output);\n printUpgradeSummary(output, options.dryRun);\n\n if (output.errors.length > 0) {\n throw CLIError({\n message: `Upgrade completed with ${output.errors.length} error(s)`,\n suggestion: \"Review the errors above and re-run the upgrade after fixing the issues.\",\n command: \"upgrade\",\n });\n }\n}\n"],"mappings":"8MAYA,eAAsB,uBAAuB,EAA6C,CACxF,IAAI,EAAM,EAAK,QAAQ,CAAW,EAG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O,OAAO,WACxD,WAAY,0EACZ,QAAS,SACX,CAAC,CAEL"}
1
+ {"version":3,"file":"service-CLPMoj9n.mjs","names":["CLIError"],"sources":["../src/cli/commands/upgrade/version-detector.ts","../src/cli/commands/upgrade/service.ts"],"sourcesContent":["import * as path from \"pathe\";\nimport { readPackageJSON } from \"pkg-types\";\n\nconst SDK_PACKAGE_NAME = \"@tailor-platform/sdk\";\n\n/**\n * Detect the installed SDK version from the user's project.\n * Walks up from projectRoot to find the SDK package in node_modules,\n * matching Node's module resolution for workspace setups with hoisted deps.\n * @param projectRoot - The project root directory to search from\n * @returns The installed SDK version string, or null if not found\n */\nexport async function detectInstalledVersion(projectRoot: string): Promise<string | null> {\n let dir = path.resolve(projectRoot);\n // loop exits when a package.json is found or the root is reached\n // oxlint-disable-next-line typescript/no-unnecessary-condition\n while (true) {\n try {\n const sdkPath = path.join(dir, \"node_modules\", SDK_PACKAGE_NAME);\n const pkg = await readPackageJSON(sdkPath);\n if (pkg.version) return pkg.version;\n } catch {\n // Not found at this level, try parent\n }\n const parent = path.dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n return null;\n}\n","import { spawnSync } from \"node:child_process\";\nimport { CLIError } from \"#/cli/shared/errors\";\nimport { logger, styles } from \"#/cli/shared/logger\";\nimport { detectInstalledVersion } from \"./version-detector\";\nimport type { RunOutput } from \"./types\";\n\ninterface UpgradeOptions {\n from: string;\n dryRun: boolean;\n path: string;\n}\n\n/**\n * Print the upgrade summary to the terminal.\n * @param output - The parsed JSON output from sdk-codemod\n * @param dryRun - Whether this was a dry-run\n */\nfunction printUpgradeSummary(output: RunOutput, dryRun: boolean): void {\n if (dryRun) {\n logger.info(`${styles.bold(\"[Dry Run]\")} No files were modified.`);\n logger.log(\"\");\n }\n\n const total = output.codemodsApplied + output.codemodsSkipped + output.errors.length;\n logger.info(\n `Upgrade complete: ${styles.success(`${output.codemodsApplied} applied`)}, ${styles.dim(`${output.codemodsSkipped} skipped`)} (${total} total codemods)`,\n );\n\n if (output.filesModified.length > 0) {\n logger.log(\"\");\n logger.info(\n `${dryRun ? \"Files that would be modified\" : \"Modified files\"} (${output.filesModified.length}):`,\n );\n for (const file of output.filesModified) {\n logger.log(` ${styles.path(file)}`);\n }\n }\n\n if (output.warnings.length > 0) {\n logger.log(\"\");\n logger.warn(`Manual attention needed (${output.warnings.length}):`);\n for (const warning of output.warnings) {\n logger.log(` ${styles.warning(\"!\")} ${warning}`);\n }\n }\n\n if (output.errors.length > 0) {\n logger.log(\"\");\n logger.error(`Failed codemods (${output.errors.length}):`);\n for (const { codemodId, message } of output.errors) {\n logger.log(` ${styles.error(codemodId)}: ${message}`);\n }\n }\n}\n\n/**\n * Run the upgrade pipeline:\n * 1. Detect target SDK version from node_modules\n * 2. Invoke @tailor-platform/sdk-codemod CLI\n * 3. Parse JSON output and display results\n * @param options - Upgrade options\n */\nexport async function upgrade(options: UpgradeOptions): Promise<void> {\n const projectRoot = options.path;\n\n // Step 1: Detect target SDK version (the newly installed version)\n const targetVersion = await detectInstalledVersion(projectRoot);\n if (!targetVersion) {\n throw CLIError({\n message: `Could not detect installed @tailor-platform/sdk version in ${projectRoot}`,\n suggestion:\n \"Ensure @tailor-platform/sdk is installed. Run 'pnpm install' or 'npm install' first.\",\n command: \"upgrade\",\n });\n }\n\n logger.info(\n `Upgrading from ${styles.highlight(options.from)} → ${styles.highlight(targetVersion)}`,\n );\n\n if (options.dryRun) {\n logger.info(`${styles.bold(\"[Dry Run]\")} Changes will be previewed but not applied.`);\n }\n\n logger.log(\"\");\n\n // Step 2: Invoke sdk-codemod CLI\n // Use \"latest\" because sdk-codemod may not be published at the exact same\n // version as @tailor-platform/sdk. Version filtering is handled internally\n // by sdk-codemod's registry via the --from / --to arguments.\n const npxCommand = process.platform === \"win32\" ? \"npx.cmd\" : \"npx\";\n\n const result = spawnSync(\n npxCommand,\n [\n \"@tailor-platform/sdk-codemod@latest\",\n \"--from\",\n options.from,\n \"--to\",\n targetVersion,\n \"--target\",\n projectRoot,\n ...(options.dryRun ? [\"--dry-run\"] : []),\n ],\n {\n cwd: projectRoot,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n encoding: \"utf-8\",\n timeout: 300_000,\n },\n );\n\n if (result.error) {\n throw CLIError({\n message: `Failed to run @tailor-platform/sdk-codemod: ${result.error.message}`,\n suggestion: \"Ensure npx is available and the network is accessible.\",\n command: \"upgrade\",\n });\n }\n\n // Check for non-zero exit without a launch error (e.g. registry/auth/network failures)\n if (result.status !== 0 && !result.stdout.trim()) {\n throw CLIError({\n message: `@tailor-platform/sdk-codemod exited with code ${result.status}`,\n details: result.stderr.trim() || \"(no stderr output)\",\n suggestion:\n \"Review the error above. Common causes: invalid version arguments, network issues, or missing package registry access.\",\n command: \"upgrade\",\n });\n }\n\n // Forward captured stderr so users see dry-run diffs and progress messages\n // written by sdk-codemod. stderr is piped (not inherited) so that the error\n // path above can surface it via CLIError, but on success we still need to\n // replay it verbatim to keep the colorized unified diff output visible.\n if (result.stderr) {\n process.stderr.write(result.stderr);\n }\n\n // Step 3: Parse JSON output\n let output: RunOutput;\n try {\n output = JSON.parse(result.stdout);\n } catch {\n throw CLIError({\n message: \"Failed to parse output from @tailor-platform/sdk-codemod\",\n details: result.stdout || \"(empty stdout)\",\n suggestion: \"This is likely a bug. Please report it.\",\n command: \"upgrade\",\n });\n }\n\n // Step 4: Display results\n // Emit structured data on stdout (honors --json via logger.out) and\n // human-readable summary on stderr (via printUpgradeSummary).\n logger.out(output);\n printUpgradeSummary(output, options.dryRun);\n\n if (output.errors.length > 0) {\n throw CLIError({\n message: `Upgrade completed with ${output.errors.length} error(s)`,\n suggestion: \"Review the errors above and re-run the upgrade after fixing the issues.\",\n command: \"upgrade\",\n });\n }\n}\n"],"mappings":"8MAYA,eAAsB,uBAAuB,EAA6C,CACxF,IAAI,EAAM,EAAK,QAAQ,CAAW,EAGlC,OAAa,CACX,GAAI,CACF,IAAM,EAAU,EAAK,KAAK,EAAK,eAAgB,sBAAgB,EACzD,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t as e}from"./service-YqDsHmlK.mjs";export{e as createExecutorService};
@@ -1,7 +1,7 @@
1
- import{n as e}from"./brand-C8nMKhJC.mjs";import{n as t,r as n}from"./logger-BcGy-u7G.mjs";import*as r from"pathe";import{z as i}from"zod";import*as a from"node:fs";import{pathToFileURL as o}from"node:url";const s=i.custom(e=>typeof e==`function`),c=`tailorImportNonce`;let l=0;function beginUserModuleRun(){l+=1}function currentImportNonce(){return l===0?void 0:String(l)}function importUserModule(e){let t=o(e),n=currentImportNonce();return n&&t.searchParams.set(c,n),import(t.href)}const ee=[`**/*.test.ts`,`**/*.spec.ts`],u=new Set;function loadFilesWithIgnores(e,n){if(e.files.length===0)return[];let i=resolveFiles(e,n),a=e.files.every(e=>r.isAbsolute(e));if(i.matchedAnyPattern||n===process.cwd()||a)return i.files;let o=`${n}\0${e.files.join(`\0`)}`;return u.has(o)||(u.add(o),t.warn(`No files matched "${e.files.join(`, `)}" relative to "${n}"; falling back to process.cwd(). Update this config's file patterns to be relative to its own directory before v2, when this fallback will be removed.`)),resolveFiles(e,process.cwd()).files}function resolveFiles(e,n){let i=e.ignores===void 0,o=e.ignores??ee,s=i?o:o.map(e=>r.resolve(n,e)),c=[],l=!1;for(let i of e.files){let e=r.resolve(n,i);try{let t=a.globSync(e);t.length>0&&(l=!0);let n=t.filter(e=>!s.some(t=>r.matchesGlob(e,t)));c.push(...n)}catch(e){l=!0,t.warn(`Failed to glob pattern "${i}": ${String(e)}`)}}return{files:c,matchedAnyPattern:l}}const d={"1-1":`1-1`,oneToOne:`1-1`,"n-1":`n-1`,manyToOne:`n-1`,"N-1":`n-1`,keyOnly:`keyOnly`},f=Object.keys(d);function fieldRef(e){return`Field "${e.fieldName}" on table "${e.tableName}"`}function validateRelationConfig(e,t){if(!e.type)throw Error(`${fieldRef(t)} has a relation but is missing the required 'type' property. Valid values: ${f.join(`, `)}.`);if(!(e.type in d))throw Error(`${fieldRef(t)} has invalid relation type '${e.type}'. Valid values: ${f.join(`, `)}.`);if(e.toward.type!==`self`&&!t.allTableNames.has(e.toward.type))throw Error(`${fieldRef(t)} references unknown table "${e.toward.type}".`)}function processRelationMetadata(e,t,n=!1){let r=d[e.type]===`1-1`,i=e.toward.key??`id`,a=e.toward.type===`self`?t.tableName:e.toward.type,o=!n,s=!n&&r;return{index:o,foreignKey:!0,relationType:e.type,unique:s,foreignKeyType:a,foreignKeyField:i}}function buildRelationInfo(e,t){if(e.type===`keyOnly`)return;let n=d[e.type]===`1-1`,r=e.toward.key??`id`,i=e.toward.type===`self`?t.tableName:e.toward.type,a=e.toward.as;return a||=t.fieldName.replace(/(ID|Id|id)$/u,``),{targetType:i,forwardName:a,backwardName:e.backward??``,key:r,unique:n}}function applyRelationMetadataToFieldConfig(e,t){return{...e,index:t.index,foreignKey:t.foreignKey,unique:t.unique,foreignKeyType:t.foreignKeyType,foreignKeyField:t.foreignKeyField}}function normalizeGqlOperations(e){return e===`query`?{create:!1,update:!1,delete:!1,read:!0}:e}const p=i.union([i.literal(`query`),i.strictObject({create:i.boolean().optional().describe(`Enable create mutation (default: true)`),update:i.boolean().optional().describe(`Enable update mutation (default: true)`),delete:i.boolean().optional().describe(`Enable delete mutation (default: true)`),read:i.boolean().optional().describe(`Enable read queries - get, list, aggregation (default: true)`)})]).describe(`Configuration for GraphQL operations on a TailorDB table.
2
- All operations are enabled by default (undefined or true = enabled, false = disabled).`).transform(e=>normalizeGqlOperations(e)),m=i.enum([`uuid`,`string`,`boolean`,`integer`,`float`,`decimal`,`enum`,`date`,`datetime`,`time`,`nested`]),h=i.strictObject({value:i.string(),description:i.string().optional()}),g=i.strictObject({required:i.boolean().optional().describe(`Whether the field is required`),array:i.boolean().optional().describe(`Whether the field is an array`),description:i.string().optional().describe(`Field description`),typeName:i.string().optional().describe(`Type name for nested or enum fields`),allowedValues:i.array(h).optional().describe(`Allowed values for enum fields`),index:i.boolean().optional().describe(`Whether the field is indexed for faster queries`),unique:i.boolean().optional().describe(`Whether the field value must be unique`),vector:i.boolean().optional().describe(`Whether the field is a vector field for similarity search`),foreignKey:i.boolean().optional().describe(`Whether the field is a foreign key`),foreignKeyType:i.string().optional().describe(`Target table name for foreign key relations`),foreignKeyField:i.string().optional().describe(`Target field name for foreign key relations`),hooks:i.strictObject({create:s.optional().describe(`Hook function called on record creation`),update:s.optional().describe(`Hook function called on record update`)}).optional().describe(`Lifecycle hooks for the field`),validate:i.array(s).optional().describe(`Validation functions for the field`),serial:i.strictObject({start:i.number().describe(`Starting value for the serial sequence`),maxValue:i.number().optional().describe(`Maximum value for the serial sequence`),format:i.string().optional().describe(`Format string for serial value (string type only)`)}).optional().describe(`Serial (auto-increment) configuration`),scale:i.number().int().min(0).max(12).optional().describe(`Decimal scale (number of digits after decimal point, 0-12)`),default:i.unknown().optional().describe(`Default value for the field on create`)}),te=i.enum(f),ne=i.strictObject({type:te.describe(`Relation cardinality type`),toward:i.strictObject({type:i.string().describe(`Target table name, or 'self' for self-relations`),as:i.string().optional().describe(`Custom forward relation name`),key:i.string().optional().describe(`Target field to join on (default: 'id')`)}),backward:i.string().optional().describe(`Backward relation name on the target table`)}),_=i.lazy(()=>i.object({type:m,fields:i.record(i.string(),_).optional(),metadata:g,rawRelation:ne.optional()})),v=i.strictObject({pluralForm:i.string().optional().describe(`Custom plural form of the table name for GraphQL`),aggregation:i.boolean().optional().describe(`Enable aggregation queries for this table`),bulkUpsert:i.boolean().optional().describe(`Enable bulk upsert mutation for this table`),gqlOperations:p.optional().describe(`Configure GraphQL operations for this table. Use "query" for read-only mode, or an object for granular control.`),publishEvents:i.boolean().optional().describe(`Enable publishing events for this table.
1
+ import{n as e}from"./brand-C8nMKhJC.mjs";import{n as t,r as n}from"./logger-CCjs1DuH.mjs";import*as r from"pathe";import{z as i}from"zod";import*as a from"node:fs";import{pathToFileURL as o}from"node:url";const s=i.custom(e=>typeof e==`function`),c=`tailorImportNonce`;let l=0;function beginUserModuleRun(){l+=1}function currentImportNonce(){return l===0?void 0:String(l)}function importUserModule(e){let t=o(e),n=currentImportNonce();return n&&t.searchParams.set(c,n),import(t.href)}const ee=[`**/*.test.ts`,`**/*.spec.ts`],u=new Set;function loadFilesWithIgnores(e,n){if(e.files.length===0)return[];let i=resolveFiles(e,n),a=e.files.every(e=>r.isAbsolute(e));if(i.matchedAnyPattern||n===process.cwd()||a)return i.files;let o=`${n}\0${e.files.join(`\0`)}`;return u.has(o)||(u.add(o),t.warn(`No files matched "${e.files.join(`, `)}" relative to "${n}"; falling back to process.cwd(). Update this config's file patterns to be relative to its own directory before v2, when this fallback will be removed.`)),resolveFiles(e,process.cwd()).files}function resolveFiles(e,n){let i=e.ignores===void 0,o=e.ignores??ee,s=i?o:o.map(e=>r.resolve(n,e)),c=[],l=!1;for(let i of e.files){let e=r.resolve(n,i);try{let t=a.globSync(e);t.length>0&&(l=!0);let n=t.filter(e=>!s.some(t=>r.matchesGlob(e,t)));c.push(...n)}catch(e){l=!0,t.warn(`Failed to glob pattern "${i}": ${String(e)}`)}}return{files:c,matchedAnyPattern:l}}const d={"1-1":`1-1`,oneToOne:`1-1`,"n-1":`n-1`,manyToOne:`n-1`,"N-1":`n-1`,keyOnly:`keyOnly`},f=Object.keys(d);function fieldRef(e){return`Field "${e.fieldName}" on table "${e.tableName}"`}function validateRelationConfig(e,t){if(!e.type)throw Error(`${fieldRef(t)} has a relation but is missing the required 'type' property. Valid values: ${f.join(`, `)}.`);if(!(e.type in d))throw Error(`${fieldRef(t)} has invalid relation type '${e.type}'. Valid values: ${f.join(`, `)}.`);if(e.toward.table!==`self`&&!t.allTableNames.has(e.toward.table))throw Error(`${fieldRef(t)} references unknown table "${e.toward.table}".`)}function processRelationMetadata(e,t,n=!1){let r=d[e.type]===`1-1`,i=e.toward.key??`id`,a=e.toward.table===`self`?t.tableName:e.toward.table,o=!n,s=!n&&r;return{index:o,foreignKey:!0,relationType:e.type,unique:s,foreignKeyType:a,foreignKeyField:i}}function buildRelationInfo(e,t){if(e.type===`keyOnly`)return;let n=d[e.type]===`1-1`,r=e.toward.key??`id`,i=e.toward.table===`self`?t.tableName:e.toward.table,a=e.toward.as;return a||=t.fieldName.replace(/(ID|Id|id)$/u,``),{targetType:i,forwardName:a,backwardName:e.backward??``,key:r,unique:n}}function applyRelationMetadataToFieldConfig(e,t){return{...e,index:t.index,foreignKey:t.foreignKey,unique:t.unique,foreignKeyType:t.foreignKeyType,foreignKeyField:t.foreignKeyField}}function normalizeGqlOperations(e){return e===`query`?{create:!1,update:!1,delete:!1,read:!0}:e}const p=i.union([i.literal(`query`),i.strictObject({create:i.boolean().optional().describe(`Enable create mutation (default: true)`),update:i.boolean().optional().describe(`Enable update mutation (default: true)`),delete:i.boolean().optional().describe(`Enable delete mutation (default: true)`),read:i.boolean().optional().describe(`Enable read queries - get, list, aggregation (default: true)`)})]).describe(`Configuration for GraphQL operations on a TailorDB table.
2
+ All operations are enabled by default (undefined or true = enabled, false = disabled).`).transform(e=>normalizeGqlOperations(e)),m=i.enum([`uuid`,`string`,`boolean`,`integer`,`float`,`decimal`,`enum`,`date`,`datetime`,`time`,`nested`]),h=i.strictObject({value:i.string(),description:i.string().optional()}),g=i.strictObject({required:i.boolean().optional().describe(`Whether the field is required`),array:i.boolean().optional().describe(`Whether the field is an array`),description:i.string().optional().describe(`Field description`),typeName:i.string().optional().describe(`Type name for nested or enum fields`),allowedValues:i.array(h).optional().describe(`Allowed values for enum fields`),index:i.boolean().optional().describe(`Whether the field is indexed for faster queries`),unique:i.boolean().optional().describe(`Whether the field value must be unique`),vector:i.boolean().optional().describe(`Whether the field is a vector field for similarity search`),foreignKey:i.boolean().optional().describe(`Whether the field is a foreign key`),foreignKeyType:i.string().optional().describe(`Target table name for foreign key relations`),foreignKeyField:i.string().optional().describe(`Target field name for foreign key relations`),hooks:i.strictObject({create:s.optional().describe(`Hook function called on record creation`),update:s.optional().describe(`Hook function called on record update`)}).optional().describe(`Lifecycle hooks for the field`),validate:i.array(s).optional().describe(`Validation functions for the field`),serial:i.strictObject({start:i.number().describe(`Starting value for the serial sequence`),maxValue:i.number().optional().describe(`Maximum value for the serial sequence`),format:i.string().optional().describe(`Format string for serial value (string type only)`)}).optional().describe(`Serial (auto-increment) configuration`),scale:i.number().int().min(0).max(12).optional().describe(`Decimal scale (number of digits after decimal point, 0-12)`),default:i.unknown().optional().describe(`Default value for the field on create`)}),te=i.enum(f),ne=i.strictObject({type:te.describe(`Relation cardinality type`),toward:i.strictObject({table:i.string().describe(`Target table name, or 'self' for self-relations`),as:i.string().optional().describe(`Custom forward relation name`),key:i.string().optional().describe(`Target field to join on (default: 'id')`)}),backward:i.string().optional().describe(`Backward relation name on the target table`)}),_=i.lazy(()=>i.object({type:m,fields:i.record(i.string(),_).optional(),metadata:g,rawRelation:ne.optional()})),v=i.strictObject({pluralForm:i.string().optional().describe(`Custom plural form of the table name for GraphQL`),aggregation:i.boolean().optional().describe(`Enable aggregation queries for this table`),bulkUpsert:i.boolean().optional().describe(`Enable bulk upsert mutation for this table`),gqlOperations:p.optional().describe(`Configure GraphQL operations for this table. Use "query" for read-only mode, or an object for granular control.`),publishEvents:i.boolean().optional().describe(`Enable publishing events for this table.
3
3
  When enabled, record creation/update/deletion events are published.
4
4
  If not specified, this is automatically set to true when an executor uses this table
5
5
  with recordCreated/recordUpdated/recordDeleted triggers. If explicitly set to false
6
6
  while an executor uses this table, an error will be thrown during apply.`)}),y=i.union([i.strictObject({user:i.string()}),i.string(),i.boolean(),i.array(i.string()),i.array(i.boolean())],{error:e=>{if(typeof e.input==`object`&&e.input!==null){let t=Object.keys(e.input);return t.length===1?`"${t[0]}" operand is not supported in gqlPermission. Use permission() for record-level conditions.`:`Operand object must have exactly 1 key`}return`Invalid operand in gqlPermission`}}),b=i.union([y,i.strictObject({record:i.string()}),i.strictObject({oldRecord:i.string()}),i.strictObject({newRecord:i.string()})]),x=i.enum([`=`,`!=`,`in`,`not in`,`hasAny`,`not hasAny`]),S=i.tuple([b,x,b]).readonly(),re=i.tuple([y,x,y]).readonly(),C=i.union([i.strictObject({conditions:i.union([S,i.array(S).readonly()]),description:i.string().optional(),permit:i.boolean().optional()}),i.tuple([b,x,b]).readonly(),i.tuple([b,x,b,i.boolean()]).readonly(),i.array(i.union([S,i.boolean()])).refine(e=>{let t=e.findIndex(e=>typeof e==`boolean`);return t===-1||t===e.length-1},{message:`Boolean permit flag must only appear at the end`}).readonly()]),ie=i.enum([`read`,`create`,`update`,`delete`,`aggregate`,`bulkUpsert`]),ae=i.strictObject({conditions:i.array(re).readonly(),actions:i.union([i.literal(`all`),i.array(ie).readonly()]),permit:i.boolean().optional(),description:i.string().optional()}),oe=i.strictObject({record:i.strictObject({create:i.array(C).readonly(),read:i.array(C).readonly(),update:i.array(C).readonly(),delete:i.array(C).readonly()}).optional(),gql:i.array(ae).readonly().optional()}),w=i.strictObject({name:i.string(),fields:i.record(i.string(),_),metadata:i.object({name:i.string(),description:i.string().optional(),settings:v.optional(),permissions:oe,files:i.record(i.string(),i.string()),indexes:i.record(i.string(),i.strictObject({fields:i.array(i.string()),unique:i.boolean().optional()})).optional(),typeHook:i.strictObject({create:s.optional(),update:s.optional()}).optional(),typeValidate:s.optional()}).strict()}),T=i.strictObject({directory:i.string().describe(`Directory containing migration files`),machineUser:i.string().optional().describe(`Machine user name for migration execution`)}),E=i.strictObject({files:i.array(i.string()).describe(`Glob patterns for TailorDB table definition files`),ignores:i.array(i.string()).optional().describe(`Glob patterns to exclude from table discovery`),migration:T.optional().describe(`Migration configuration`),gqlOperations:p.optional().describe(`Default GraphQL operations for all tables in this service`)}),D=w.keyof().options;function stripTailorDBTypeBuilderHelpers(t){if(!e(t,`tailordb-type`))return t;let n={},r=t;for(let e of D)Object.prototype.hasOwnProperty.call(r,e)&&(n[e]=r[e]);return n}const O=i.strictObject({providerUrl:i.string().describe(`OAuth2 provider URL`),issuerUrl:i.string().describe(`OAuth2 issuer URL`),clientId:i.string().describe(`OAuth2 client ID`),clientSecret:i.string().describe(`OAuth2 client secret`),authUrl:i.string().optional().describe(`OAuth2 authorization endpoint override`),tokenUrl:i.string().optional().describe(`OAuth2 token endpoint override`)}).extend({type:i.literal(`oauth2`).describe(`Connection type`)}),k=i.enum([`uuid`,`string`,`boolean`,`integer`,`float`,`decimal`,`enum`,`date`,`datetime`,`time`,`nested`]),A=i.strictObject({value:i.string().describe(`The allowed value`),description:i.string().optional().describe(`Description of the allowed value`)}),j=i.strictObject({required:i.boolean().optional().describe(`Whether the field is required`),array:i.boolean().optional().describe(`Whether the field is an array`),description:i.string().optional().describe(`Field description`),allowedValues:i.array(A).optional().describe(`Allowed values for enum fields`),hooks:i.strictObject({create:s.optional().describe(`Hook function called on creation`),update:s.optional().describe(`Hook function called on update`)}).optional().describe(`Lifecycle hooks`),validate:i.array(s).optional().describe(`Validation functions for the field`),typeName:i.string().optional().describe(`Type name for nested or enum fields`),default:i.unknown().optional().describe(`Default value for the field on create`)}),M=i.object({type:k.describe(`Field data type`),metadata:j.describe(`Field metadata configuration`),get fields(){return i.record(i.string(),M)}}),N=i.strictObject({namespace:i.string().describe(`Auth namespace`),machineUserName:i.string().describe(`Machine user name for authentication`)}),P=i.union([i.string().describe(`Machine user name (namespace auto-resolved from auth service)`),N]),F=i.strictObject({vaultName:i.string().describe(`Vault name containing the secret`),secretKey:i.string().describe(`Key of the secret in the vault`)}),I=i.strictObject({name:i.string().describe(`Identity provider name`),kind:i.literal(`OIDC`),clientID:i.string().describe(`OAuth2 client ID`),clientSecret:F.describe(`OAuth2 client secret`),providerURL:i.string().describe(`OIDC provider URL`),issuerURL:i.string().optional().describe(`OIDC issuer URL (defaults to providerURL)`),usernameClaim:i.string().optional().describe(`JWT claim to use as username`)}),L=i.strictObject({name:i.string().describe(`Identity provider name`),kind:i.literal(`SAML`),enableSignRequest:i.boolean().default(!1).describe(`Enable signing of SAML requests`),metadataURL:i.string().optional().describe(`URL to fetch SAML metadata (mutually exclusive with rawMetadata)`),rawMetadata:i.string().optional().describe(`Raw SAML metadata XML (mutually exclusive with metadataURL)`),defaultRedirectURL:i.string().optional().describe(`URL to redirect to when SAML ACS receives a response with an empty RelayState.`)}).refine(e=>e.metadataURL!==void 0!=(e.rawMetadata!==void 0),`Provide either metadataURL or rawMetadata`),R=i.strictObject({name:i.string().describe(`Identity provider name`),kind:i.literal(`IDToken`),providerURL:i.string().describe(`ID token provider URL`),issuerURL:i.string().optional().describe(`ID token issuer URL`),clientID:i.string().describe(`Client ID for ID token validation`),usernameClaim:i.string().optional().describe(`JWT claim to use as username`)}),z=i.strictObject({name:i.string().describe(`Identity provider name`),kind:i.literal(`BuiltInIdP`),namespace:i.string().describe(`IdP namespace`),clientName:i.string().describe(`OAuth2 client name in the IdP`)}),B=i.discriminatedUnion(`kind`,[I,L,R,z]),V=i.union([i.literal(`authorization_code`),i.literal(`refresh_token`)]).describe(`OAuth2 grant type`),H=i.strictObject({description:i.string().optional().describe(`Client description`),grantTypes:i.array(V).default([`authorization_code`,`refresh_token`]).describe(`Allowed OAuth2 grant types`),redirectURIs:i.array(i.union([i.templateLiteral([`https://`,i.string()]),i.templateLiteral([`http://`,i.string()]),i.templateLiteral([i.string(),`:url`]),i.templateLiteral([i.string(),`:url/`,i.string()])])).describe(`Allowed redirect URIs`),clientType:i.union([i.literal(`confidential`),i.literal(`public`),i.literal(`browser`)]).optional().describe(`OAuth2 client type`),accessTokenLifetimeSeconds:i.number().int().min(60,`Minimum access token lifetime is 60 seconds`).max(86400,`Maximum access token lifetime is 1 day (86400 seconds)`).optional().describe(`Access token lifetime in seconds (60-86400)`).transform(e=>e?{seconds:BigInt(e),nanos:0}:void 0),refreshTokenLifetimeSeconds:i.number().int().min(60,`Minimum refresh token lifetime is 60 seconds`).max(604800,`Maximum refresh token lifetime is 7 days (604800 seconds)`).optional().describe(`Refresh token lifetime in seconds (60-604800)`).transform(e=>e?{seconds:BigInt(e),nanos:0}:void 0),requireDpop:i.boolean().optional().describe(`Require DPoP (Demonstrating Proof-of-Possession) for token requests`)}).refine(e=>e.clientType!==`browser`||e.requireDpop!==!0,{message:`requireDpop cannot be set to true for browser clients as they don't support DPoP`,path:[`requireDpop`]}),U=i.strictObject({type:i.union([i.literal(`oauth2`),i.literal(`bearer`)]).describe(`SCIM authorization type`),bearerSecret:F.optional().describe(`Bearer token secret (required for bearer type)`)}),W=i.union([i.literal(`string`),i.literal(`number`),i.literal(`boolean`),i.literal(`datetime`),i.literal(`complex`)]).describe(`SCIM attribute data type`),G=i.strictObject({type:W.describe(`Attribute data type`),name:i.string().describe(`Attribute name`),description:i.string().optional().describe(`Attribute description`),mutability:i.union([i.literal(`readOnly`),i.literal(`readWrite`),i.literal(`writeOnly`)]).optional().describe(`Attribute mutability`),required:i.boolean().optional().describe(`Whether the attribute is required`),multiValued:i.boolean().optional().describe(`Whether the attribute can have multiple values`),uniqueness:i.union([i.literal(`none`),i.literal(`server`),i.literal(`global`)]).optional().describe(`Uniqueness constraint`),canonicalValues:i.array(i.string()).nullable().optional().describe(`List of canonical values`),get subAttributes(){return i.array(G).nullable().optional()}}),K=i.strictObject({name:i.string().describe(`SCIM schema name`),attributes:i.array(G).describe(`Schema attributes`)}),q=i.strictObject({tailorDBField:i.string().describe(`TailorDB field name to map to`),scimPath:i.string().describe(`SCIM attribute path`)}),se=i.strictObject({name:i.string().describe(`SCIM resource name`),tailorDBNamespace:i.string().describe(`TailorDB namespace for the resource`),tailorDBType:i.string().describe(`TailorDB table name for the resource`),coreSchema:K.describe(`Core SCIM schema definition`),attributeMapping:i.array(q).describe(`Attribute mapping configuration`)}),ce=i.strictObject({machineUserName:i.string().describe(`Machine user name for SCIM operations`),authorization:U.describe(`SCIM authorization configuration`),resources:i.array(se).describe(`SCIM resource definitions`)}),le=i.strictObject({namespace:i.string().describe(`TailorDB namespace for the tenant table`),type:i.string().describe(`TailorDB table name for tenants`),signatureField:i.string().describe(`Field used as the tenant signature`)}),ue=i.strictObject({namespace:i.string().optional().describe(`TailorDB namespace where the user table is defined`),type:i.custom().transform(stripTailorDBTypeBuilderHelpers).pipe(w),usernameField:i.string(),attributes:i.record(i.string(),i.literal(!0)).optional(),attributeList:i.array(i.string()).optional()}),de=i.union([i.string(),i.boolean(),i.array(i.string()),i.array(i.boolean())]),fe=i.strictObject({attributes:i.record(i.string(),de.nullish()).transform(e=>Object.fromEntries(Object.entries(e).filter(e=>e[1]!=null))).optional(),attributeList:i.array(i.uuid()).optional()}),pe=i.strictObject({handler:i.function(),invoker:i.string()}),J=i.strictObject({name:i.string().describe(`Auth service name`),hooks:i.strictObject({beforeLogin:pe.optional().describe(`Before login auth hook`)}).optional().describe(`Auth hooks`),machineUsers:i.record(i.string(),fe).optional().describe(`Machine user definitions`),oauth2Clients:i.record(i.string(),H).optional().describe(`OAuth2 client definitions`),idProvider:B.optional().describe(`Identity provider configuration`),scim:ce.optional().describe(`SCIM provisioning configuration`),tenantProvider:le.optional().describe(`Multi-tenant provider configuration`),connections:i.record(i.string(),O).optional().describe(`Auth connection definitions for external OAuth2 providers`),publishSessionEvents:i.boolean().optional().describe(`Enable publishing session events`)}),me=i.xor([J.extend({userProfile:ue.optional().describe(`User profile configuration`),machineUserAttributes:i.undefined().optional()}),J.extend({userProfile:i.undefined().optional(),machineUserAttributes:i.record(i.string(),M).describe(`Machine user attribute fields`)})],{error:e=>{if(e.code===`invalid_union`&&!(e.errors.length<2)&&e.errors.every(e=>e.every(e=>e.path.length===1&&(e.path[0]===`userProfile`||e.path[0]===`machineUserAttributes`))))return"Specify either `userProfile` or `machineUserAttributes`, not both."}}).brand(`AuthConfig`),he=i.strictObject({kind:i.literal(`tailordb`).describe(`TailorDB record event trigger`),events:i.array(i.enum([`tailordb.type_record.created`,`tailordb.type_record.updated`,`tailordb.type_record.deleted`])).min(1).transform(e=>[...new Set(e)]).describe(`TailorDB event types to trigger on`),tableName:i.string().describe(`TailorDB table name to watch for events`),condition:s.optional().describe(`Condition function to filter events`)}),ge=i.strictObject({kind:i.literal(`resolverExecuted`),resolverName:i.string().describe(`Name of the resolver to trigger on`),condition:s.optional().describe(`Condition function to filter events`)}),_e=i.strictObject({kind:i.literal(`schedule`),cron:i.string().describe(`CRON expression for the schedule`),timezone:i.string().optional().default(`UTC`).describe(`Timezone for the CRON schedule (default: UTC)`)}),ve=i.strictObject({body:s.optional().describe(`Function returning the response body`),statusCode:i.number().int().optional().describe(`HTTP status code for the response`)}),ye=i.strictObject({kind:i.literal(`incomingWebhook`),response:ve.optional().describe(`Response configuration`)}),be=i.strictObject({kind:i.literal(`idpUser`).describe(`IdP user event trigger`),events:i.array(i.enum([`idp.user.created`,`idp.user.updated`,`idp.user.deleted`])).min(1).transform(e=>[...new Set(e)]).describe(`IdP user event types to trigger on`),idp:i.string().optional().describe(`IdP namespace name to subscribe to. If omitted, the project's only IdP is used; throws when multiple IdPs exist.`)}),xe=i.strictObject({kind:i.literal(`authAccessToken`).describe(`Auth access token event trigger`),events:i.array(i.enum([`auth.access_token.issued`,`auth.access_token.refreshed`,`auth.access_token.revoked`])).min(1).transform(e=>[...new Set(e)]).describe(`Auth access token event types to trigger on`)}),Y=i.string().refine(e=>e.trim().length>0,`Workflow name cannot be blank`).describe(`Workflow name to subscribe to.`),Se=i.strictObject({kind:i.literal(`workflowExecution`).describe(`Workflow execution event trigger`),events:i.array(i.enum([`workflow.workflow_execution.started`,`workflow.workflow_execution.completed`,`workflow.workflow_execution.retried`,`workflow.workflow_execution.resumed`,`workflow.workflow_execution.wait_started`,`workflow.workflow_execution.wait_resolved`])).min(1).transform(e=>[...new Set(e)]).describe(`Workflow execution event types to trigger on`),workflowName:Y,condition:s.optional().describe(`Condition function to filter events`)}),Ce=i.strictObject({kind:i.literal(`workflowJobExecution`).describe(`Workflow job execution event trigger`),events:i.array(i.enum([`workflow.workflow_execution.job_execution.started`,`workflow.workflow_execution.job_execution.completed`,`workflow.workflow_execution.job_execution.wait_started`,`workflow.workflow_execution.job_execution.wait_resolved`])).min(1).transform(e=>[...new Set(e)]).describe(`Workflow job execution event types to trigger on`),workflowName:Y,condition:s.optional().describe(`Condition function to filter events`)}),X=i.discriminatedUnion(`kind`,[he,ge,_e,ye,be,xe,Se,Ce]),we=i.strictObject({kind:i.enum([`function`,`jobFunction`]),body:s.describe(`Function implementation`),invoker:P.optional().describe(`Invoker for the function execution`)}),Te=i.strictObject({kind:i.literal(`graphql`),appName:i.string().optional().describe(`Target application name for the GraphQL query`),query:i.preprocess(e=>String(e),i.string().describe(`GraphQL query string`)),variables:s.optional().describe(`Function to compute GraphQL variables`),invoker:P.optional().describe(`Invoker for the GraphQL execution`)}),Ee=i.strictObject({kind:i.literal(`webhook`),url:s.describe(`Function returning the webhook URL`),requestBody:s.optional().describe(`Function to compute the request body`),headers:i.record(i.string(),i.union([i.string(),i.strictObject({vault:i.string(),key:i.string()})])).optional().describe(`HTTP headers for the webhook request`)}),Z=i.lazy(()=>i.union([i.string(),i.number(),i.boolean(),i.null(),i.array(Z),i.record(i.string(),Z)])),De=i.union([i.string(),i.number(),i.boolean(),i.array(Z),i.record(i.string(),Z)]),Oe=i.union([De,s]).describe(`Arguments to pass to the workflow`),Q={kind:i.literal(`workflow`),args:Oe.optional(),invoker:P.optional().describe(`Invoker for the workflow execution`)},ke=i.strictObject({...Q,workflowName:i.string().describe(`Name of the workflow to execute`),workflow:i.never().optional()}),Ae=i.strictObject({...Q,workflow:i.looseObject({name:i.string()}),workflowName:i.string().optional()}).transform(({workflow:e,...t})=>({...t,workflowName:e.name})),je=i.union([Ae,ke]),Me=i.union([we,Te,Ee,je]),$=i.strictObject({name:i.string().describe(`Executor name`),description:i.string().optional().describe(`Executor description`),disabled:i.boolean().optional().default(!1).describe(`Whether the executor is disabled`),trigger:X.describe(`Event trigger configuration`),operation:Me.describe(`Operation to execute when triggered`)});function stripExecutorTriggerArgs(t){if(!e(t,`executor`))return t;let n=t.trigger;if(typeof n!=`object`||!n||!(`__args`in n))return t;let{__args:r,...i}=n;return{...t,trigger:i}}async function loadExecutor(e){let t=(await importUserModule(e)).default,n=$.safeParse(stripExecutorTriggerArgs(t));return n.success?n.data:null}function createExecutorService(i){let{config:a,baseDir:o}=i,s={},c=[],l,loadExecutorForFile=async i=>{try{let a=await importUserModule(i),o=$.safeParse(stripExecutorTriggerArgs(a.default));if(o.success){let e=r.relative(process.cwd(),i);return t.log(`Executor: ${n.successBright(`"${o.data.name}"`)} loaded from ${n.path(e)}`),s[i]=o.data,o.data}if(e(a.default,`executor`))throw o.error}catch(e){let a=r.relative(process.cwd(),i);throw t.error(`Failed to load executor from ${n.bold(a)}`),t.error(String(e)),e}};return{config:a,get executors(){return s},get pluginExecutors(){return c},loadExecutors:async()=>(l||=(async()=>{if(a.files.length===0)return;let e=loadFilesWithIgnores(a,o);return t.newline(),t.log(`Found ${n.highlight(e.length.toString())} executor files`),await Promise.all(e.map(e=>loadExecutorForFile(e))),assertUniqueExecutorNames(s),s})(),l),loadPluginExecutorFiles:async e=>{if(e.length!==0){t.newline(),t.log(`Loading ${n.highlight(e.length.toString())} plugin-generated executor files`);for(let t of e){let e=await loadExecutorForFile(t);e&&c.push({executor:e,pluginId:`plugin-generated`,sourceTableName:void 0})}assertUniqueExecutorNames(s)}}}}function assertUniqueExecutorNames(e){let t=new Map;for(let[n,i]of Object.entries(e)){let e=r.relative(process.cwd(),n),a=t.get(i.name);if(a)throw Error(`Duplicate executor name "${i.name}" found:\n - ${a}\n - ${e}\nEach executor must have a unique name.`);t.set(i.name,e)}}export{beginUserModuleRun as _,me as a,s as b,stripTailorDBTypeBuilderHelpers as c,applyRelationMetadataToFieldConfig as d,buildRelationInfo as f,c as g,loadFilesWithIgnores as h,$ as i,E as l,validateRelationConfig as m,loadExecutor as n,P as o,processRelationMetadata as p,stripExecutorTriggerArgs as r,M as s,createExecutorService as t,w as u,currentImportNonce as v,importUserModule as y};
7
- //# sourceMappingURL=service-BVe9u2Rt.mjs.map
7
+ //# sourceMappingURL=service-YqDsHmlK.mjs.map