@tailor-platform/sdk 2.2.0 → 2.4.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.
- package/CHANGELOG.md +183 -0
- package/README.md +1 -1
- package/dist/{application-BpLeawBg.mjs → application-C8a0UJ-z.mjs} +312 -166
- package/dist/application-C8a0UJ-z.mjs.map +1 -0
- package/dist/application-D4zOiLLa.mjs +3 -0
- package/dist/cli/commands/tailordb/migrate/diff-calculator.d.mts +47 -24
- package/dist/cli/commands/tailordb/migrate/generate.d.mts +6 -0
- package/dist/cli/commands/tailordb/migrate/rename-detection.d.mts +22 -0
- package/dist/cli/commands/tailordb/migrate/snapshot-types.d.mts +1 -1
- package/dist/cli/commands/tailordb/migrate/snapshot.d.mts +30 -11
- package/dist/cli/commands/tailordb/truncate.d.mts +2 -2
- package/dist/cli/lib.mjs +2 -2
- package/dist/cli/lib.mjs.map +1 -1
- package/dist/cli/main.mjs +366 -137
- package/dist/cli/main.mjs.map +1 -1
- package/dist/cli/ts-hook.mjs +55 -8
- package/dist/completion/zsh-worker.zsh +38 -10
- package/dist/configure/config/index.d.mts +1 -1
- package/dist/configure/index.d.mts +3 -2
- package/dist/configure/index.mjs +92 -25
- package/dist/configure/index.mjs.map +1 -1
- package/dist/configure/services/aigateway/index.d.mts +5 -4
- package/dist/configure/services/aigateway/types.d.mts +6 -1
- package/dist/configure/services/auth/types.d.mts +2 -2
- package/dist/configure/services/index.d.mts +2 -2
- package/dist/configure/services/tailordb/permission.d.mts +1 -1
- package/dist/configure/services/tailordb/schema.d.mts +1 -1
- package/dist/configure/services/tailordb/types.d.mts +7 -4
- package/dist/configure/services/workflow/index.d.mts +2 -2
- package/dist/configure/services/workflow/wait-point.d.mts +72 -13
- package/dist/configure/types/auth-namespace-name.d.mts +18 -0
- package/dist/{crashreport-CINZ5dVN.mjs → crashreport-Cd4TqfZq.mjs} +1 -1
- package/dist/{crashreport-CIIfLnoO.mjs → crashreport-Q0pDAlrj.mjs} +8 -4
- package/dist/{crashreport-CIIfLnoO.mjs.map → crashreport-Q0pDAlrj.mjs.map} +1 -1
- package/dist/{errors-CWj21238.mjs → errors-Bxut5_Sy.mjs} +17 -3
- package/dist/{errors-CWj21238.mjs.map → errors-Bxut5_Sy.mjs.map} +1 -1
- package/dist/file-BUcmVIH2.mjs.map +1 -1
- package/dist/kysely/index.d.mts +2 -1
- package/dist/kysely/index.mjs +2 -1
- package/dist/kysely/index.mjs.map +1 -1
- package/dist/{logger-DSdExfor.mjs → logger-D0bEznPv.mjs} +9 -5
- package/dist/{logger-DSdExfor.mjs.map → logger-D0bEznPv.mjs.map} +1 -1
- package/dist/package-json-8b0O9TlX.mjs.map +1 -1
- package/dist/plugin/builtin/enum-constants/index.d.mts +1 -1
- package/dist/plugin/builtin/enum-constants/index.mjs +5 -5
- package/dist/plugin/builtin/enum-constants/index.mjs.map +1 -1
- package/dist/plugin/builtin/file-utils/index.d.mts +1 -1
- package/dist/plugin/builtin/file-utils/index.mjs +14 -11
- package/dist/plugin/builtin/file-utils/index.mjs.map +1 -1
- package/dist/plugin/builtin/kysely-type/index.d.mts +1 -1
- package/dist/plugin/builtin/kysely-type/index.mjs +9 -9
- package/dist/plugin/builtin/kysely-type/index.mjs.map +1 -1
- package/dist/plugin/builtin/seed/index.mjs +1 -1
- package/dist/plugin/builtin/seed/seed-type-processor.d.mts +4 -4
- package/dist/plugin/get-generated-type.d.mts +4 -4
- package/dist/plugin/index.mjs +13 -13
- package/dist/plugin/index.mjs.map +1 -1
- package/dist/plugin/types.d.mts +2 -2
- package/dist/plugin/with-context.d.mts +1 -1
- package/dist/{register-ts-hook-CTth1eqj.mjs → register-ts-hook-Vqjza10T.mjs} +2516 -857
- package/dist/register-ts-hook-Vqjza10T.mjs.map +1 -0
- package/dist/{repl-editor-BCozyiNq.mjs → repl-editor-F9LotMNx.mjs} +3 -2
- package/dist/{repl-editor-BCozyiNq.mjs.map → repl-editor-F9LotMNx.mjs.map} +1 -1
- package/dist/runtime/file.d.mts +14 -14
- package/dist/{schema--xYWRGfe.mjs → schema-D4TC4BC3.mjs} +4 -3
- package/dist/schema-D4TC4BC3.mjs.map +1 -0
- package/dist/seed/index.d.mts +4 -4
- package/dist/seed/index.mjs +3 -3
- package/dist/seed/index.mjs.map +1 -1
- package/dist/{seed-xqM9WIHP.mjs → seed-Cibjmtry.mjs} +46 -40
- package/dist/seed-Cibjmtry.mjs.map +1 -0
- package/dist/{service-goqlJJgA.mjs → service-2grcAOCJ.mjs} +61 -27
- package/dist/service-2grcAOCJ.mjs.map +1 -0
- package/dist/service-CaBPNDIZ.mjs +3 -0
- package/dist/{service-CCwl3Avt.mjs → service-LTfp03ZZ.mjs} +7 -5
- package/dist/{service-CCwl3Avt.mjs.map → service-LTfp03ZZ.mjs.map} +1 -1
- package/dist/types/aigateway.generated.d.mts +2 -2
- package/dist/types/auth.generated.d.mts +3 -3
- package/dist/types/executor.generated.d.mts +1 -1
- package/dist/types/tailordb.generated.d.mts +12 -12
- package/dist/utils/test/index.d.mts +4 -4
- package/dist/utils/test/index.mjs +4 -4
- package/dist/utils/test/index.mjs.map +1 -1
- package/dist/vitest/index.mjs +95 -7
- package/dist/vitest/index.mjs.map +1 -1
- package/dist/vitest/mocks/workflow.d.mts +13 -1
- package/dist/wait-point-invoker-__oE88_P.mjs +148 -0
- package/dist/wait-point-invoker-__oE88_P.mjs.map +1 -0
- package/dist/wait-point-registry-TL99zotw.mjs +47 -0
- package/dist/wait-point-registry-TL99zotw.mjs.map +1 -0
- package/docs/cli/application.md +3 -1
- package/docs/cli/function.md +17 -13
- package/docs/cli/setup.md +14 -1
- package/docs/cli/tailordb.md +30 -27
- package/docs/cli/workspace.md +2 -2
- package/docs/cli-reference.md +23 -22
- package/docs/configuration.md +2 -2
- package/docs/github-actions.md +73 -28
- package/docs/migration/v2.md +58 -4
- package/docs/migration/v3.md +41 -0
- package/docs/quickstart.md +1 -1
- package/docs/services/aigateway.md +33 -9
- package/docs/services/executor.md +5 -1
- package/docs/services/tailordb-migration.md +146 -44
- package/docs/services/tailordb.md +7 -7
- package/docs/services/workflow.md +52 -2
- package/docs/testing.md +13 -1
- package/package.json +8 -8
- package/dist/application-BpLeawBg.mjs.map +0 -1
- package/dist/application-BxLLiLsr.mjs +0 -3
- package/dist/register-ts-hook-CTth1eqj.mjs.map +0 -1
- package/dist/schema--xYWRGfe.mjs.map +0 -1
- package/dist/seed-xqM9WIHP.mjs.map +0 -1
- package/dist/service-_XmjSEGr.mjs +0 -3
- package/dist/service-goqlJJgA.mjs.map +0 -1
- package/dist/test-env-key-D7UkZp99.mjs +0 -75
- package/dist/test-env-key-D7UkZp99.mjs.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"schema--xYWRGfe.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 TailorDBField as TailorDBFieldBase,\n TailorDBType as TailorDBTypeBase,\n DBFieldMetadata,\n DefinedDBFieldMetadata,\n SerialConfig,\n IndexDef,\n TailorDBTypeMetadata,\n RawRelationConfig,\n RelationType,\n} from \"#/configure/services/tailordb/types\";\nimport type {\n FieldOptions,\n FieldOutput,\n TailorFieldType,\n TailorToTs,\n FieldValidateInput,\n} from \"#/configure/types/field.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 Hook,\n TypeHook,\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 type.\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 - Type name\n * @param fields - Field definitions\n * @param options - Type 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 ) as DBTable<F>;\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: ({ input, now }) => input ?? now })\n .description(\"Record update timestamp\"),\n }),\n },\n};\n"],"mappings":";;;;AAIA,MAAM,QAAQ;CACZ,MAAM;CACN,MAAM;CACN,MAAM;CACN,UACE;CACF,SAAS;AACX;AA6BA,SAAS,kBAA6C,MAAuC;CAC3F,MAAM,EAAE,OAAO,OAAO,WAAW,WAAW;CAC5C,MAAM,OAAO,UAAU,SAAS,IAAI,YAAY;CAChD,MAAM,oBAAoB,OAAO;CAEjC,QAAQ,MAAM,MAAd;EACE,KAAK;GACH,IAAI,OAAO,UAAU,UACnB,OAAO,KAAK;IACV,SAAS,+BAA+B,OAAO,KAAK;IACpD;GACF,CAAC;GAEH;EAEF,KAAK;GACH,IAAI,OAAO,UAAU,YAAY,CAAC,OAAO,UAAU,KAAK,GACtD,OAAO,KAAK;IACV,SAAS,iCAAiC,OAAO,KAAK;IACtD;GACF,CAAC;GAEH;EAEF,KAAK;GACH,IAAI,OAAO,UAAU,YAAY,CAAC,OAAO,SAAS,KAAK,GACrD,OAAO,KAAK;IACV,SAAS,+BAA+B,OAAO,KAAK;IACpD;GACF,CAAC;GAEH;EAEF,KAAK;GACH,IAAI,OAAO,UAAU,WACnB,OAAO,KAAK;IACV,SAAS,gCAAgC,OAAO,KAAK;IACrD;GACF,CAAC;GAEH;EAEF,KAAK;GACH,IAAI,OAAO,UAAU,YAAY,CAAC,MAAM,KAAK,KAAK,KAAK,GACrD,OAAO,KAAK;IACV,SAAS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KAAK;CACjD,MAAM,aAAa,MAAM,QAAQ,IAAI,IAAI,KAAK,KAAK;CAEnD,IAAI;CACJ,IAAI;CACJ,IAAI,OAAO,wBAAwB,UAAU;EAC3C,cAAc;EACd,WAAW;CACb,OACE,WAAW;CAEb,OAAO,mBACL,UACA;EACE,IAAI;EACJ,GAAG;CACL,GACA;EAAE;EAAY;CAAY,CAC5B;AACF;;AAGA,MAAa,KAAK;CAChB,OAAO;CACP;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA,MAAM;CACN;CACA,QAAQ;;;;;;;;;;;;AAYN,mBAAmB;EACjB,WAAW,SAAS,CAAC,CAAC,QAAQ,KAAK,CAAC,CAAC,YAAY,2BAA2B;EAC5E,WAAW,SAAS,CAAC,CAClB,QAAQ,KAAK,CAAC,CACd,MAAM,EAAE,SAAS,EAAE,OAAO,UAAU,SAAS,IAAI,CAAC,CAAC,CACnD,YAAY,yBAAyB;CAC1C,GACF;AACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"seed-xqM9WIHP.mjs","names":["ml"],"sources":["../src/plugin/builtin/seed/idp-user-processor.ts","../src/plugin/builtin/seed/lines-db-processor.ts","../src/plugin/builtin/seed/index.ts"],"sourcesContent":["import ml from \"#/utils/multiline\";\nimport type { GeneratorAuthInput } from \"#/plugin/types\";\n\nexport interface IdpUserMetadata {\n name: \"_User\";\n dependencies: string[];\n dataFile: string;\n idpNamespace: string;\n schema: {\n usernameField: string;\n userTypeName: string;\n };\n}\n\n/**\n * Processes auth configuration to generate IdP user seed metadata\n * @param auth - Auth configuration from generator\n * @returns IdP user metadata or undefined if not applicable\n */\nexport function processIdpUser(auth: GeneratorAuthInput): IdpUserMetadata | undefined {\n // Only process if idProvider is BuiltInIdP and userProfile is defined\n if (auth.idProvider?.kind !== \"BuiltInIdP\" || !auth.userProfile) {\n return undefined;\n }\n\n const { typeName, usernameField } = auth.userProfile;\n\n return {\n name: \"_User\",\n dependencies: [typeName],\n dataFile: \"data/_User.jsonl\",\n idpNamespace: auth.idProvider.namespace,\n schema: {\n usernameField,\n userTypeName: typeName,\n },\n };\n}\n\n/**\n * Generates the server-side IDP seed script code for testExecScript execution.\n * Uses the global tailor.idp.Client - no bundling required.\n * @param idpNamespace - The IDP namespace name\n * @returns Script code string\n */\nexport function generateIdpSeedScriptCode(idpNamespace: string): string {\n return ml /* ts */ `\n export async function main(input) {\n const client = new tailor.idp.Client({ namespace: \"${idpNamespace}\" });\n const errors = [];\n let processed = 0;\n let created = 0;\n let updated = 0;\n let skipped = 0;\n const upsert = input.upsert === true;\n\n for (let i = 0; i < input.users.length; i++) {\n try {\n if (upsert) {\n let existing;\n let lookupError;\n try {\n existing = await client.userByName(input.users[i].name);\n } catch (error) {\n existing = undefined;\n lookupError = error instanceof Error ? error.message : String(error);\n }\n\n if (existing) {\n const { name, ...attributes } = input.users[i];\n if (Object.keys(attributes).length === 0) {\n skipped++;\n } else {\n await client.updateUser({ id: existing.id, ...attributes });\n updated++;\n }\n } else {\n try {\n await client.createUser(input.users[i]);\n created++;\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(\n lookupError ? \\`create failed (\\${message}); lookup failed (\\${lookupError})\\` : message,\n );\n }\n }\n } else {\n await client.createUser(input.users[i]);\n created++;\n }\n processed++;\n console.log(\\`[_User] \\${i + 1}/\\${input.users.length}: \\${input.users[i].name}\\`);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n errors.push(\\`Row \\${i} (\\${input.users[i].name}): \\${message}\\`);\n console.error(\\`[_User] Row \\${i} failed: \\${message}\\`);\n }\n }\n\n return {\n success: errors.length === 0,\n processed,\n created,\n updated,\n skipped,\n errors,\n };\n }\n `;\n}\n\n/**\n * Generates the server-side IDP truncation script code for testExecScript execution.\n * Lists all users with pagination and deletes each one.\n * @param idpNamespace - The IDP namespace name\n * @returns Script code string\n */\nexport function generateIdpTruncateScriptCode(idpNamespace: string): string {\n return ml /* ts */ `\n export async function main() {\n const client = new tailor.idp.Client({ namespace: \"${idpNamespace}\" });\n const errors = [];\n let deleted = 0;\n\n // List all users with pagination\n let after = undefined;\n const allUsers = [];\n do {\n const response = await client.users(after ? { after } : undefined);\n allUsers.push(...(response.users || []));\n after = response.nextPageToken;\n } while (after);\n\n console.log(\\`Found \\${allUsers.length} IDP users to delete\\`);\n\n for (const user of allUsers) {\n try {\n await client.deleteUser(user.id);\n deleted++;\n console.log(\\`[_User] Deleted \\${deleted}/\\${allUsers.length}: \\${user.name}\\`);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n errors.push(\\`User \\${user.id} (\\${user.name}): \\${message}\\`);\n console.error(\\`[_User] Delete failed for \\${user.name}: \\${message}\\`);\n }\n }\n\n return {\n success: errors.length === 0,\n deleted,\n total: allUsers.length,\n errors,\n };\n }\n `;\n}\n\ntype GenerateIdpUserSchemaFileOptions = {\n usernameField: string;\n userTypeName: string;\n /**\n * When `true` (default), emit a foreign key from `_User.name` to the\n * userProfile type's username field so that seed validation rejects `_User`\n * rows without a matching userProfile row. Set to `false` to seed `_User`\n * rows that do not yet have a corresponding userProfile row.\n */\n includeUserProfileFK?: boolean;\n};\n\n/**\n * Generates the schema file content for IdP users. Emits the\n * `_User.name -> <userProfile>.<usernameField>` foreign key by default; pass\n * `includeUserProfileFK: false` to omit it (e.g. when seeding `_User` rows\n * that do not yet have a corresponding userProfile row).\n * @param options - Schema generation options\n * @param options.usernameField - Username field name\n * @param options.userTypeName - TailorDB user type name\n * @param options.includeUserProfileFK - Whether to emit the `_User -> userProfile` foreign key (default `true`)\n * @returns Schema file contents\n */\nexport function generateIdpUserSchemaFile(options: GenerateIdpUserSchemaFileOptions): string {\n const { usernameField, userTypeName, includeUserProfileFK = true } = options;\n const schemaBody = includeUserProfileFK\n ? ml`\n primaryKey: \"name\",\n indexes: [\n { name: \"_user_name_unique_idx\", columns: [\"name\"], unique: true },\n ],\n foreignKeys: [\n {\n column: \"name\",\n references: {\n table: \"${userTypeName}\",\n column: \"${usernameField}\",\n },\n },\n ],\n `\n : ml`\n primaryKey: \"name\",\n indexes: [\n { name: \"_user_name_unique_idx\", columns: [\"name\"], unique: true },\n ],\n `;\n\n return ml /* ts */ `\n import { t } from \"@tailor-platform/sdk\";\n import { defineSchema } from \"@tailor-platform/sdk/seed\";\n import { createStandardSchema } from \"@tailor-platform/sdk/test\";\n\n const schemaType = t.object({\n name: t.string(),\n password: t.string(),\n });\n\n // Simple identity hook for _User (no TailorDB backing type)\n export const hook = <T>(data: unknown) => data as T;\n\n export const schema = defineSchema(\n createStandardSchema(schemaType, hook),\n {\n ${schemaBody}\n }\n );\n\n `;\n}\n","import { isPluginGeneratedType } from \"#/parser/service/tailordb/type-source\";\nimport ml from \"#/utils/multiline\";\nimport type {\n PluginGeneratedTypeSource,\n TailorDBType,\n TypeSourceInfoEntry,\n} from \"#/parser/service/tailordb/types\";\nimport type { LinesDbMetadata } from \"./types\";\nimport type { ForeignKeyDefinition, IndexDefinition } from \"@toiroakr/lines-db\";\n\n/**\n * Processes TailorDB types to generate lines-db metadata\n * @param type - Parsed TailorDB type\n * @param source - Source file info\n * @returns Generated lines-db metadata\n */\nexport function processLinesDb(type: TailorDBType, source: TypeSourceInfoEntry): LinesDbMetadata {\n if (isPluginGeneratedType(source)) {\n // Plugin-generated type\n return processLinesDbForPluginType(type, source);\n }\n\n // User-defined type\n if (!source.filePath) {\n throw new Error(`Missing source info for type ${type.name}`);\n }\n if (!source.exportName) {\n throw new Error(`Missing export name for type ${type.name}`);\n }\n\n const { optionalFields, omitFields, indexes, foreignKeys } = extractFieldMetadata(type);\n\n return {\n typeName: type.name,\n exportName: source.exportName,\n importPath: source.filePath,\n optionalFields,\n omitFields,\n foreignKeys,\n indexes,\n };\n}\n\n/**\n * Process lines-db metadata for plugin-generated types\n * @param type - Parsed TailorDB type\n * @param source - Plugin-generated type source info\n * @returns Generated lines-db metadata with plugin source\n */\nfunction processLinesDbForPluginType(\n type: TailorDBType,\n source: PluginGeneratedTypeSource,\n): LinesDbMetadata {\n const { optionalFields, omitFields, indexes, foreignKeys } = extractFieldMetadata(type);\n\n return {\n typeName: type.name,\n exportName: source.exportName,\n importPath: \"\",\n optionalFields,\n omitFields,\n foreignKeys,\n indexes,\n pluginSource: source,\n };\n}\n\n/**\n * Extract field metadata from TailorDB type\n * @param type - Parsed TailorDB type\n * @returns Field metadata including optional fields, omit fields, indexes, and foreign keys\n */\nfunction extractFieldMetadata(type: TailorDBType): {\n optionalFields: string[];\n omitFields: string[];\n indexes: IndexDefinition[];\n foreignKeys: ForeignKeyDefinition[];\n} {\n const optionalFields = [\"id\"]; // id is always optional\n const omitFields: string[] = [];\n const indexes: IndexDefinition[] = [];\n const foreignKeys: ForeignKeyDefinition[] = [];\n\n // Find fields with hooks.create or serial\n for (const [fieldName, field] of Object.entries(type.fields)) {\n if (field.config.hooks?.create) {\n optionalFields.push(fieldName);\n }\n // Serial fields are auto-generated, so they should be optional in seed data\n if (field.config.serial) {\n omitFields.push(fieldName);\n }\n if (field.config.unique) {\n indexes.push({\n name: `${type.name.toLowerCase()}_${fieldName}_unique_idx`,\n columns: [fieldName],\n unique: true,\n });\n }\n }\n\n // Extract indexes\n if (type.indexes) {\n for (const [indexName, indexDef] of Object.entries(type.indexes)) {\n indexes.push({\n name: indexName,\n columns: indexDef.fields,\n unique: indexDef.unique,\n });\n }\n }\n\n // Extract foreign keys from relations\n for (const [fieldName, field] of Object.entries(type.fields)) {\n if (field.relation) {\n foreignKeys.push({\n column: fieldName,\n references: {\n table: field.relation.targetType,\n column: field.relation.key,\n },\n });\n }\n }\n\n return { optionalFields, omitFields, indexes, foreignKeys };\n}\n\n/**\n * Generate schema options code for lines-db\n * @param foreignKeys - Foreign key definitions\n * @param indexes - Index definitions\n * @returns Schema options code string\n */\nfunction generateSchemaOptions(\n foreignKeys: ForeignKeyDefinition[],\n indexes: IndexDefinition[],\n): string {\n const schemaOptions: string[] = [];\n\n if (foreignKeys.length > 0) {\n schemaOptions.push(`foreignKeys: [`);\n foreignKeys.forEach((fk) => {\n schemaOptions.push(` ${JSON.stringify(fk)},`);\n });\n schemaOptions.push(`],`);\n }\n\n if (indexes.length > 0) {\n schemaOptions.push(`indexes: [`);\n indexes.forEach((index) => {\n schemaOptions.push(` ${JSON.stringify(index)},`);\n });\n schemaOptions.push(\"],\");\n }\n\n return schemaOptions.length > 0\n ? [\"\\n {\", ...schemaOptions.map((option) => ` ${option}`), \" }\"].join(\"\\n\")\n : \"\";\n}\n\n/**\n * Generates the schema file content for lines-db (for user-defined types with import)\n * @param metadata - lines-db metadata\n * @param importPath - Import path for the TailorDB type\n * @returns Schema file contents\n */\nexport function generateLinesDbSchemaFile(metadata: LinesDbMetadata, importPath: string): string {\n const { exportName, optionalFields, omitFields, foreignKeys, indexes } = metadata;\n\n const schemaTypeCode = ml /* ts */ `\n const schemaType = t.object({\n ...${exportName}.pickFields(${JSON.stringify(optionalFields)}, { optional: true }),\n ...${exportName}.omitFields(${JSON.stringify([...optionalFields, ...omitFields])}),\n });\n `;\n\n const schemaOptionsCode = generateSchemaOptions(foreignKeys, indexes);\n\n return ml /* ts */ `\n import { t } from \"@tailor-platform/sdk\";\n import { defineSchema } from \"@tailor-platform/sdk/seed\";\n import { createTailorDBHook, createStandardSchema } from \"@tailor-platform/sdk/test\";\n import { ${exportName} } from \"${importPath}\";\n\n ${schemaTypeCode}\n\n export const hook = createTailorDBHook(${exportName});\n\n export const schema = defineSchema(\n createStandardSchema(schemaType, hook, ${exportName}),${schemaOptionsCode}\n );\n\n `;\n}\n\n/**\n * Parameters for generating plugin-type schema file\n */\nexport interface PluginSchemaParams {\n /** Relative path from schema output to tailor.config.ts */\n configImportPath: string;\n /** Relative import path to the original type file (for type-attached plugins) */\n originalImportPath?: string;\n}\n\n/**\n * Generates the schema file content using getGeneratedType API\n * (for plugin-generated types)\n * @param metadata - lines-db metadata (must have pluginSource)\n * @param params - Plugin import paths\n * @returns Schema file contents\n */\nexport function generateLinesDbSchemaFileWithPluginAPI(\n metadata: LinesDbMetadata,\n params: PluginSchemaParams,\n): string {\n const { typeName, exportName, optionalFields, omitFields, foreignKeys, indexes, pluginSource } =\n metadata;\n\n if (!pluginSource) {\n throw new Error(`pluginSource is required for plugin-generated type \"${typeName}\"`);\n }\n\n const { configImportPath, originalImportPath } = params;\n\n const schemaTypeCode = ml /* ts */ `\n const schemaType = t.object({\n ...${exportName}.pickFields(${JSON.stringify(optionalFields)}, { optional: true }),\n ...${exportName}.omitFields(${JSON.stringify([...optionalFields, ...omitFields])}),\n });\n `;\n\n const schemaOptionsCode = generateSchemaOptions(foreignKeys, indexes);\n\n // Type-attached plugin (e.g., changeset): import original type and use getGeneratedType(configPath, pluginId, type, kind)\n if (pluginSource.originalExportName && originalImportPath && pluginSource.generatedTypeKind) {\n return ml /* ts */ `\n import { join } from \"node:path\";\n import { t } from \"@tailor-platform/sdk\";\n import { getGeneratedType } from \"@tailor-platform/sdk/plugin\";\n import { defineSchema } from \"@tailor-platform/sdk/seed\";\n import { createTailorDBHook, createStandardSchema } from \"@tailor-platform/sdk/test\";\n import { ${pluginSource.originalExportName} } from \"${originalImportPath}\";\n\n const configPath = join(import.meta.dirname, \"${configImportPath}\");\n const ${exportName} = await getGeneratedType(configPath, \"${pluginSource.pluginId}\", ${pluginSource.originalExportName}, \"${pluginSource.generatedTypeKind}\");\n\n ${schemaTypeCode}\n\n export const hook = createTailorDBHook(${exportName});\n\n export const schema = defineSchema(\n createStandardSchema(schemaType, hook, ${exportName}),${schemaOptionsCode}\n );\n\n `;\n }\n\n // Namespace plugin (e.g., audit-log): use getGeneratedType(configPath, pluginId, null, kind)\n // For namespace plugins, generatedTypeKind is required\n if (!pluginSource.generatedTypeKind) {\n throw new Error(\n `Namespace plugin \"${pluginSource.pluginId}\" must provide generatedTypeKind for type \"${typeName}\"`,\n );\n }\n\n return ml /* ts */ `\n import { join } from \"node:path\";\n import { t } from \"@tailor-platform/sdk\";\n import { getGeneratedType } from \"@tailor-platform/sdk/plugin\";\n import { defineSchema } from \"@tailor-platform/sdk/seed\";\n import { createTailorDBHook, createStandardSchema } from \"@tailor-platform/sdk/test\";\n\n const configPath = join(import.meta.dirname, \"${configImportPath}\");\n const ${exportName} = await getGeneratedType(configPath, \"${pluginSource.pluginId}\", null, \"${pluginSource.generatedTypeKind}\");\n\n ${schemaTypeCode}\n\n export const hook = createTailorDBHook(${exportName});\n\n export const schema = defineSchema(\n createStandardSchema(schemaType, hook, ${exportName}),${schemaOptionsCode}\n );\n\n `;\n}\n","import * as path from \"pathe\";\nimport { assertDefined } from \"#/utils/assert\";\nimport { processIdpUser, generateIdpUserSchemaFile } from \"./idp-user-processor\";\nimport {\n processLinesDb,\n generateLinesDbSchemaFile,\n generateLinesDbSchemaFileWithPluginAPI,\n type PluginSchemaParams,\n} from \"./lines-db-processor\";\nimport type { Plugin, GeneratorResult, TailorDBReadyContext } from \"#/plugin/types\";\n\n/** Unique identifier for the seed generator plugin. */\nexport const SeedGeneratorID = \"@tailor-platform/seed\";\n\ntype DisableIdpUserSyncDirections = {\n /**\n * Skip emitting the foreign key from `<userProfile>.<usernameField>` to\n * `_User.name`. Defaults to `false` (FK emitted).\n *\n * Set to `true` to seed pre-registration states such as\n * invited-but-not-registered users.\n */\n userToIdp?: boolean;\n /**\n * Skip emitting the foreign key from `_User.name` to\n * `<userProfile>.<usernameField>`. Defaults to `false` (FK emitted).\n *\n * Set to `true` to seed `_User` rows that do not yet have a corresponding\n * userProfile row.\n */\n idpToUser?: boolean;\n};\n\nexport type SeedPluginOptions = {\n distPath: string;\n machineUserName?: string;\n /**\n * Disable individual `_User <-> userProfile` foreign keys emitted into\n * the generated seed schema. Both directions are emitted by default.\n *\n * Set a direction to `true` to relax it — for example to seed invited\n * users that do not yet have an IdP credential.\n */\n disableIdpUserSync?: DisableIdpUserSyncDirections;\n};\n\nfunction resolveIdpUserSyncFKs(option: SeedPluginOptions[\"disableIdpUserSync\"]): {\n emitUserToIdpFK: boolean;\n emitIdpToUserFK: boolean;\n} {\n return {\n emitUserToIdpFK: !(option?.userToIdp ?? false),\n emitIdpToUserFK: !(option?.idpToUser ?? false),\n };\n}\n/**\n * Plugin that generates seed data and schema files consumed by the\n * `tailor seed` commands (@tailor-platform/sdk-plugin-seed).\n * @param options - Plugin options\n * @param options.distPath - Output directory path for generated seed files\n * @param options.machineUserName - Default machine user name for authentication\n * @param options.disableIdpUserSync - Skip emitting individual `_User <-> userProfile` foreign keys. Both directions are emitted by default; set a direction to `true` to relax that side.\n * @returns Plugin instance with onTailorDBReady hook\n */\nexport function seedPlugin(options: SeedPluginOptions): Plugin<unknown, SeedPluginOptions> {\n return {\n id: SeedGeneratorID,\n description: \"Generates seed data and schema files for the tailor seed CLI plugin\",\n pluginConfig: options,\n\n async onTailorDBReady(ctx: TailorDBReadyContext<SeedPluginOptions>): Promise<GeneratorResult> {\n const files: GeneratorResult[\"files\"] = [];\n\n // Process IdP user early so we can add reverse FK to the user profile type\n const idpUser = ctx.auth ? (processIdpUser(ctx.auth) ?? null) : null;\n const idpUserSyncFKs = resolveIdpUserSyncFKs(ctx.pluginConfig.disableIdpUserSync);\n\n for (const ns of ctx.tailordb) {\n for (const [typeName, type] of Object.entries(ns.types)) {\n const source = assertDefined(\n ns.sourceInfo.get(typeName),\n `source info missing for type: ${typeName}`,\n );\n const linesDb = processLinesDb(type, source);\n\n // Add reverse FK from userProfile type to _User (opt-out via disableIdpUserSync.userToIdp: true)\n if (\n idpUserSyncFKs.emitUserToIdpFK &&\n idpUser &&\n typeName === idpUser.schema.userTypeName\n ) {\n linesDb.foreignKeys.push({\n column: idpUser.schema.usernameField,\n references: {\n table: \"_User\",\n column: \"name\",\n },\n });\n }\n\n // Generate empty JSONL data file\n files.push({\n path: path.join(ctx.pluginConfig.distPath, \"data\", `${linesDb.typeName}.jsonl`),\n content: \"\",\n skipIfExists: true,\n });\n\n const schemaOutputPath = path.join(\n ctx.pluginConfig.distPath,\n \"data\",\n `${linesDb.typeName}.schema.ts`,\n );\n\n // Plugin-generated type: use getGeneratedType API\n if (linesDb.pluginSource && linesDb.pluginSource.pluginImportPath) {\n // Build original type import path\n let originalImportPath: string | undefined;\n if (linesDb.pluginSource.originalFilePath && linesDb.pluginSource.originalExportName) {\n const relativePath = path.relative(\n path.dirname(schemaOutputPath),\n linesDb.pluginSource.originalFilePath,\n );\n originalImportPath = relativePath.replace(/\\.ts$/, \"\").startsWith(\".\")\n ? relativePath.replace(/\\.ts$/, \"\")\n : `./${relativePath.replace(/\\.ts$/, \"\")}`;\n }\n\n // Compute relative path from schema output to config file\n const configImportPath = path.relative(path.dirname(schemaOutputPath), ctx.configPath);\n\n const params: PluginSchemaParams = {\n configImportPath,\n originalImportPath,\n };\n\n const schemaContent = generateLinesDbSchemaFileWithPluginAPI(linesDb, params);\n\n files.push({\n path: schemaOutputPath,\n content: schemaContent,\n });\n } else {\n // User-defined type: import from source file\n const relativePath = path.relative(path.dirname(schemaOutputPath), linesDb.importPath);\n const typeImportPath = relativePath.replace(/\\.ts$/, \"\").startsWith(\".\")\n ? relativePath.replace(/\\.ts$/, \"\")\n : `./${relativePath.replace(/\\.ts$/, \"\")}`;\n const schemaContent = generateLinesDbSchemaFile(linesDb, typeImportPath);\n\n files.push({\n path: schemaOutputPath,\n content: schemaContent,\n });\n }\n }\n }\n\n if (idpUser) {\n // Generate empty JSONL data file\n files.push({\n path: path.join(ctx.pluginConfig.distPath, idpUser.dataFile),\n content: \"\",\n skipIfExists: true,\n });\n\n // Generate schema file with foreign key (opt-out via disableIdpUserSync.idpToUser: true)\n files.push({\n path: path.join(ctx.pluginConfig.distPath, \"data\", `${idpUser.name}.schema.ts`),\n content: generateIdpUserSchemaFile({\n usernameField: idpUser.schema.usernameField,\n userTypeName: idpUser.schema.userTypeName,\n includeUserProfileFK: idpUserSyncFKs.emitIdpToUserFK,\n }),\n });\n }\n\n return { files };\n },\n };\n}\n"],"mappings":";;;;;;;;;;;AAmBA,SAAgB,eAAe,MAAuD;CAEpF,IAAI,KAAK,YAAY,SAAS,gBAAgB,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gA.mjs","names":["TailorFieldTypeSchema","AllowedValueSchema"],"sources":["../src/parser/service/common.ts","../src/cli/services/file-loader.ts","../src/parser/service/tailordb/relation.ts","../src/parser/service/tailordb/schema.ts","../src/parser/service/tailordb/builder-helpers.ts","../src/parser/service/auth-connection/schema.ts","../src/parser/service/field/schema.ts","../src/parser/service/auth/schema.ts","../src/parser/service/executor/schema.ts","../src/cli/services/executor/loader.ts","../src/cli/services/executor/service.ts"],"sourcesContent":["import { z } from \"zod\";\n\n// Use `z.custom` instead of `z.function`, since `z.function` changes `toString` representation.\n// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\nexport const functionSchema: z.ZodType<Function, Function> = z.custom<Function>(\n (val) => typeof val === \"function\",\n);\n","import * as fs from \"node:fs\";\nimport * as path from \"pathe\";\nimport { logger } from \"#/cli/shared/logger\";\n\nexport interface FileLoadConfig {\n files: string[];\n ignores?: string[];\n}\n\nconst DEFAULT_IGNORE_PATTERNS = [\"**/*.test.ts\", \"**/*.spec.ts\"];\n\n// loadFilesWithIgnores is called once per service/bundler, so a single\n// generate/apply run can call it multiple times for the same baseDir (once\n// per resolver/executor/tailordb/etc. config sharing that directory). Track\n// which (baseDir, patterns) pairs have already warned so each one only warns\n// once per run — keyed by patterns too, since different services sharing a\n// baseDir can have different `files` patterns each needing their own warning.\nconst warnedFallbacks = new Set<string>();\n\n/**\n * Load files matching the given patterns, excluding files that match ignore patterns.\n * By default, test files (*.test.ts, *.spec.ts) are excluded unless ignores is explicitly specified.\n * @param config - Configuration with files patterns and optional ignores patterns\n * @param baseDir - Directory relative patterns are resolved against\n * @returns Array of absolute file paths\n */\nexport function loadFilesWithIgnores(config: FileLoadConfig, baseDir: string): string[] {\n if (config.files.length === 0) {\n return [];\n }\n\n const resolved = resolveFiles(config, baseDir);\n const allPatternsAbsolute = config.files.every((pattern) => path.isAbsolute(pattern));\n if (resolved.matchedAnyPattern || baseDir === process.cwd() || allPatternsAbsolute) {\n return resolved.files;\n }\n\n // v1 compatibility fallback: pre-existing configs may have relative\n // patterns written against the invocation cwd rather than baseDir. Only\n // triggers when baseDir's patterns matched nothing at all (not merely\n // \"matched, but every hit got filtered out by ignores\") — otherwise this\n // fallback would reintroduce the same cross-app file bleed this baseDir\n // resolution is meant to prevent. Also skipped when every pattern is\n // already absolute, since baseDir can't change an absolute pattern's\n // resolution — re-running against cwd would just repeat the same glob.\n // Remove this fallback in v2, once such configs are expected to have\n // migrated.\n const fallbackKey = `${baseDir}\\0${config.files.join(\"\\0\")}`;\n if (!warnedFallbacks.has(fallbackKey)) {\n warnedFallbacks.add(fallbackKey);\n logger.warn(\n `No files matched \"${config.files.join(\", \")}\" relative to \"${baseDir}\"; falling back to ` +\n `process.cwd(). Update this config's file patterns to be relative to its own directory ` +\n `before v2, when this fallback will be removed.`,\n );\n }\n return resolveFiles(config, process.cwd()).files;\n}\n\ninterface ResolvedFiles {\n files: string[];\n /** Whether any `files` pattern matched anything under baseDir, before ignore filtering. */\n matchedAnyPattern: boolean;\n}\n\nfunction resolveFiles(config: FileLoadConfig, baseDir: string): ResolvedFiles {\n // Use user-provided patterns if specified, otherwise use defaults. Default\n // patterns are left unanchored (\"**/*.test.ts\") so they match a test file\n // regardless of which directory a `files` pattern's matches actually came\n // from — this matters when a pattern is absolute or otherwise escapes\n // baseDir. User-provided patterns are baseDir-relative, matching `files`.\n const isDefaultIgnores = config.ignores === undefined;\n const ignorePatterns = config.ignores ?? DEFAULT_IGNORE_PATTERNS;\n const resolvedIgnorePatterns = isDefaultIgnores\n ? ignorePatterns\n : ignorePatterns.map((ignorePattern) => path.resolve(baseDir, ignorePattern));\n\n const files: string[] = [];\n let matchedAnyPattern = false;\n for (const pattern of config.files) {\n const absolutePattern = path.resolve(baseDir, pattern);\n try {\n const matchedFiles = fs.globSync(absolutePattern);\n if (matchedFiles.length > 0) {\n matchedAnyPattern = true;\n }\n // Filter out ignored files\n const filteredFiles = matchedFiles.filter(\n (file) =>\n !resolvedIgnorePatterns.some((ignorePattern) => path.matchesGlob(file, ignorePattern)),\n );\n files.push(...filteredFiles);\n } catch (error) {\n // A glob failure means we don't know whether baseDir has matching\n // files, not that it has none — treat it as a match so it can't\n // trigger the v1 compatibility fallback below.\n matchedAnyPattern = true;\n logger.warn(`Failed to glob pattern \"${pattern}\": ${String(error)}`);\n }\n }\n\n return { files, matchedAnyPattern };\n}\n","import type { RawRelationConfig } from \"#/configure/services/tailordb/types\";\nimport type { OperatorFieldConfig } from \"#/parser/service/tailordb/types\";\nimport type { UnionToTuple } from \"type-fest\";\n\nconst relationTypes = {\n \"1-1\": \"1-1\",\n oneToOne: \"1-1\",\n \"n-1\": \"n-1\",\n manyToOne: \"n-1\",\n \"N-1\": \"n-1\",\n keyOnly: \"keyOnly\",\n} as const;\nexport const relationTypesKeys = Object.keys(relationTypes) as UnionToTuple<\n keyof typeof relationTypes\n>;\n\nexport interface RelationProcessingContext {\n typeName: string;\n fieldName: string;\n allTypeNames: Set<string>;\n}\n\nexport interface ProcessedRelationMetadata {\n index: boolean;\n foreignKey: boolean;\n relationType: string;\n unique: boolean;\n foreignKeyType: string;\n foreignKeyField: string;\n}\n\nexport interface RelationInfo {\n targetType: string;\n forwardName: string;\n backwardName: string;\n key: string;\n unique: boolean;\n}\n\nfunction fieldRef(context: RelationProcessingContext): string {\n return `Field \"${context.fieldName}\" on type \"${context.typeName}\"`;\n}\n\n/**\n * Validate relation configuration.\n * @param rawRelation - Raw relation configuration from TailorDB type definition\n * @param context - Context information for the relation (type name, field name, all type names)\n */\nexport function validateRelationConfig(\n rawRelation: RawRelationConfig,\n context: RelationProcessingContext,\n): void {\n // raw user config may omit the field\n // oxlint-disable-next-line typescript/no-unnecessary-condition\n if (!rawRelation.type) {\n throw new Error(\n `${fieldRef(context)} has a relation but is missing the required 'type' property. ` +\n `Valid values: ${relationTypesKeys.join(\", \")}.`,\n );\n }\n if (!(rawRelation.type in relationTypes)) {\n throw new Error(\n `${fieldRef(context)} has invalid relation type '${rawRelation.type}'. ` +\n `Valid values: ${relationTypesKeys.join(\", \")}.`,\n );\n }\n\n // Validate target type exists (for non-self relations)\n if (rawRelation.toward.type !== \"self\" && !context.allTypeNames.has(rawRelation.toward.type)) {\n throw new Error(`${fieldRef(context)} references unknown type \"${rawRelation.toward.type}\".`);\n }\n}\n\n/**\n * Process raw relation config and compute derived metadata values.\n * @param rawRelation - Raw relation configuration\n * @param context - Context information for the relation\n * @param isArrayField - Whether the target field is an array field\n * @returns Computed relation metadata to apply to field config\n */\nexport function processRelationMetadata(\n rawRelation: RawRelationConfig,\n context: RelationProcessingContext,\n isArrayField: boolean = false,\n): ProcessedRelationMetadata {\n const isUnique = relationTypes[rawRelation.type] === \"1-1\";\n const key = rawRelation.toward.key ?? \"id\";\n\n // Resolve target type name (handle \"self\" reference)\n const targetTypeName =\n rawRelation.toward.type === \"self\" ? context.typeName : rawRelation.toward.type;\n\n // Index and unique are not supported on array fields\n const shouldSetIndex = !isArrayField;\n const shouldSetUnique = !isArrayField && isUnique;\n\n return {\n index: shouldSetIndex,\n foreignKey: true,\n relationType: rawRelation.type,\n unique: shouldSetUnique,\n foreignKeyType: targetTypeName,\n foreignKeyField: key,\n };\n}\n\n/**\n * Build relation info for creating forward/backward relationships.\n * Returns undefined for keyOnly relations.\n * @param rawRelation - Raw relation configuration\n * @param context - Context information for the relation\n * @returns Relation information or undefined for keyOnly relations\n */\nexport function buildRelationInfo(\n rawRelation: RawRelationConfig,\n context: RelationProcessingContext,\n): RelationInfo | undefined {\n // keyOnly relations don't create forward/backward relationships\n if (rawRelation.type === \"keyOnly\") {\n return undefined;\n }\n\n const isUnique = relationTypes[rawRelation.type] === \"1-1\";\n const key = rawRelation.toward.key ?? \"id\";\n\n // Resolve target type name (handle \"self\" reference)\n const targetTypeName =\n rawRelation.toward.type === \"self\" ? context.typeName : rawRelation.toward.type;\n\n let forwardName = rawRelation.toward.as;\n if (!forwardName) {\n forwardName = context.fieldName.replace(/(ID|Id|id)$/u, \"\");\n }\n\n return {\n targetType: targetTypeName,\n forwardName,\n backwardName: rawRelation.backward ?? \"\",\n key,\n unique: isUnique,\n };\n}\n\n/**\n * Apply processed relation metadata to field config.\n * @param fieldConfig - Original operator field configuration\n * @param metadata - Processed relation metadata to apply\n * @returns Field config with relation metadata applied\n */\nexport function applyRelationMetadataToFieldConfig(\n fieldConfig: OperatorFieldConfig,\n metadata: ProcessedRelationMetadata,\n): OperatorFieldConfig {\n return {\n ...fieldConfig,\n index: metadata.index,\n foreignKey: metadata.foreignKey,\n unique: metadata.unique,\n foreignKeyType: metadata.foreignKeyType,\n foreignKeyField: metadata.foreignKeyField,\n };\n}\n","import { z } from \"zod\";\nimport { functionSchema } from \"../common\";\nimport { relationTypesKeys } from \"./relation\";\nimport type { TailorDBFieldOutput } from \"#/parser/service/tailordb/types\";\n\n/**\n * Normalize GqlOperationsConfig (alias or object) to GqlOperations object.\n * \"query\" alias expands to read-only mode: { create: false, update: false, delete: false, read: true }\n * @param config - The config to normalize\n * @returns The normalized GqlOperations object\n */\nfunction normalizeGqlOperations(\n config: \"query\" | { create?: boolean; update?: boolean; delete?: boolean; read?: boolean },\n) {\n if (config === \"query\") {\n return { create: false, update: false, delete: false, read: true };\n }\n return config;\n}\n\n/**\n * Zod schema for GqlOperations configuration with normalization transform.\n * Accepts \"query\" alias or detailed object, normalizes to GqlOperations object.\n */\nexport const GqlOperationsSchema = z\n .union([\n z.literal(\"query\"),\n z.strictObject({\n create: z.boolean().optional().describe(\"Enable create mutation (default: true)\"),\n update: z.boolean().optional().describe(\"Enable update mutation (default: true)\"),\n delete: z.boolean().optional().describe(\"Enable delete mutation (default: true)\"),\n read: z\n .boolean()\n .optional()\n .describe(\"Enable read queries - get, list, aggregation (default: true)\"),\n }),\n ])\n .describe(\n \"Configuration for GraphQL operations on a TailorDB type.\\nAll operations are enabled by default (undefined or true = enabled, false = disabled).\",\n )\n .transform((val) => normalizeGqlOperations(val));\n\nconst TailorFieldTypeSchema = z.enum([\n \"uuid\",\n \"string\",\n \"boolean\",\n \"integer\",\n \"float\",\n \"decimal\",\n \"enum\",\n \"date\",\n \"datetime\",\n \"time\",\n \"nested\",\n]);\n\nconst AllowedValueSchema = z.strictObject({\n value: z.string(),\n description: z.string().optional(),\n});\n\nexport const DBFieldMetadataSchema = z.strictObject({\n required: z.boolean().optional().describe(\"Whether the field is required\"),\n array: z.boolean().optional().describe(\"Whether the field is an array\"),\n description: z.string().optional().describe(\"Field description\"),\n typeName: z.string().optional().describe(\"Type name for nested or enum fields\"),\n allowedValues: z.array(AllowedValueSchema).optional().describe(\"Allowed values for enum fields\"),\n index: z.boolean().optional().describe(\"Whether the field is indexed for faster queries\"),\n unique: z.boolean().optional().describe(\"Whether the field value must be unique\"),\n vector: z\n .boolean()\n .optional()\n .describe(\"Whether the field is a vector field for similarity search\"),\n foreignKey: z.boolean().optional().describe(\"Whether the field is a foreign key\"),\n foreignKeyType: z.string().optional().describe(\"Target type name for foreign key relations\"),\n foreignKeyField: z.string().optional().describe(\"Target field name for foreign key relations\"),\n hooks: z\n .strictObject({\n create: functionSchema.optional().describe(\"Hook function called on record creation\"),\n update: functionSchema.optional().describe(\"Hook function called on record update\"),\n })\n .optional()\n .describe(\"Lifecycle hooks for the field\"),\n validate: z.array(functionSchema).optional().describe(\"Validation functions for the field\"),\n serial: z\n .strictObject({\n start: z.number().describe(\"Starting value for the serial sequence\"),\n maxValue: z.number().optional().describe(\"Maximum value for the serial sequence\"),\n format: z.string().optional().describe(\"Format string for serial value (string type only)\"),\n })\n .optional()\n .describe(\"Serial (auto-increment) configuration\"),\n scale: z\n .number()\n .int()\n .min(0)\n .max(12)\n .optional()\n .describe(\"Decimal scale (number of digits after decimal point, 0-12)\"),\n default: z.unknown().optional().describe(\"Default value for the field on create\"),\n});\n\nconst RelationTypeSchema = z.enum(relationTypesKeys);\n\nexport const RawRelationConfigSchema = z.strictObject({\n type: RelationTypeSchema.describe(\"Relation cardinality type\"),\n toward: z.strictObject({\n type: z.string().describe(\"Target type name, or 'self' for self-relations\"),\n as: z.string().optional().describe(\"Custom forward relation name\"),\n key: z.string().optional().describe(\"Target field to join on (default: 'id')\"),\n }),\n backward: z.string().optional().describe(\"Backward relation name on the target type\"),\n});\n\nconst TailorDBFieldSchema: z.ZodType<TailorDBFieldOutput> = z.lazy(() =>\n // strip unknown keys\n z.object({\n type: TailorFieldTypeSchema,\n fields: z.record(z.string(), TailorDBFieldSchema).optional(),\n metadata: DBFieldMetadataSchema,\n rawRelation: RawRelationConfigSchema.optional(),\n }),\n);\n\n/**\n * Schema for TailorDB type settings.\n * Normalizes gqlOperations from alias (\"query\") to object format.\n */\nexport const TailorDBTypeSettingsSchema = z.strictObject({\n pluralForm: z.string().optional().describe(\"Custom plural form of the type name for GraphQL\"),\n aggregation: z.boolean().optional().describe(\"Enable aggregation queries for this type\"),\n bulkUpsert: z.boolean().optional().describe(\"Enable bulk upsert mutation for this type\"),\n gqlOperations: GqlOperationsSchema.optional().describe(\n 'Configure GraphQL operations for this type. Use \"query\" for read-only mode, or an object for granular control.',\n ),\n publishEvents: z\n .boolean()\n .optional()\n .describe(\n \"Enable publishing events for this type.\\nWhen enabled, record creation/update/deletion events are published.\\nIf not specified, this is automatically set to true when an executor uses this type\\nwith recordCreated/recordUpdated/recordDeleted triggers. If explicitly set to false\\nwhile an executor uses this type, an error will be thrown during apply.\",\n ),\n});\n\nexport const GQL_PERMISSION_INVALID_OPERAND_MESSAGE =\n \"operand is not supported in gqlPermission. Use permission() for record-level conditions.\";\n\nconst GqlPermissionOperandSchema = z.union(\n [\n z.strictObject({ user: z.string() }),\n z.string(),\n z.boolean(),\n z.array(z.string()),\n z.array(z.boolean()),\n ],\n {\n error: (issue) => {\n if (typeof issue.input === \"object\" && issue.input !== null) {\n const keys = Object.keys(issue.input);\n if (keys.length === 1) {\n return `\"${keys[0]}\" ${GQL_PERMISSION_INVALID_OPERAND_MESSAGE}`;\n }\n return \"Operand object must have exactly 1 key\";\n }\n return \"Invalid operand in gqlPermission\";\n },\n },\n);\n\nconst RecordPermissionOperandSchema = z.union([\n GqlPermissionOperandSchema,\n z.strictObject({ record: z.string() }),\n z.strictObject({ oldRecord: z.string() }),\n z.strictObject({ newRecord: z.string() }),\n]);\n\nconst PermissionOperatorSchema = z.enum([\"=\", \"!=\", \"in\", \"not in\", \"hasAny\", \"not hasAny\"]);\n\nconst RecordPermissionConditionSchema = z\n .tuple([RecordPermissionOperandSchema, PermissionOperatorSchema, RecordPermissionOperandSchema])\n .readonly();\n\nconst GqlPermissionConditionSchema = z\n .tuple([GqlPermissionOperandSchema, PermissionOperatorSchema, GqlPermissionOperandSchema])\n .readonly();\n\nconst ActionPermissionSchema = z.union([\n // Object format: { conditions, description?, permit? }\n z.strictObject({\n conditions: z.union([\n RecordPermissionConditionSchema,\n z.array(RecordPermissionConditionSchema).readonly(),\n ]),\n description: z.string().optional(),\n permit: z.boolean().optional(),\n }),\n // Single condition tuple: [operand, operator, operand]\n z\n .tuple([RecordPermissionOperandSchema, PermissionOperatorSchema, RecordPermissionOperandSchema])\n .readonly(),\n // Single condition tuple with permit: [operand, operator, operand, permit]\n z\n .tuple([\n RecordPermissionOperandSchema,\n PermissionOperatorSchema,\n RecordPermissionOperandSchema,\n z.boolean(),\n ])\n .readonly(),\n // Multiple conditions with optional trailing permit\n z\n .array(z.union([RecordPermissionConditionSchema, z.boolean()]))\n .refine(\n (arr) => {\n const boolIndex = arr.findIndex((item) => typeof item === \"boolean\");\n return boolIndex === -1 || boolIndex === arr.length - 1;\n },\n { message: \"Boolean permit flag must only appear at the end\" },\n )\n .readonly(),\n]);\n\nconst GqlPermissionActionSchema = z.enum([\n \"read\",\n \"create\",\n \"update\",\n \"delete\",\n \"aggregate\",\n \"bulkUpsert\",\n]);\n\nconst GqlPermissionPolicySchema = z.strictObject({\n conditions: z.array(GqlPermissionConditionSchema).readonly(),\n actions: z.union([z.literal(\"all\"), z.array(GqlPermissionActionSchema).readonly()]),\n permit: z.boolean().optional(),\n description: z.string().optional(),\n});\n\nexport const RawPermissionsSchema = z.strictObject({\n record: z\n .strictObject({\n create: z.array(ActionPermissionSchema).readonly(),\n read: z.array(ActionPermissionSchema).readonly(),\n update: z.array(ActionPermissionSchema).readonly(),\n delete: z.array(ActionPermissionSchema).readonly(),\n })\n .optional(),\n gql: z.array(GqlPermissionPolicySchema).readonly().optional(),\n});\n\nexport const TailorDBTypeSchema = z.strictObject({\n name: z.string(),\n fields: z.record(z.string(), TailorDBFieldSchema),\n // oxlint-disable-next-line zod/prefer-strict-object, tailor-zod/require-object-policy-comment -- Keep z.object().strict() so zinfer preserves the RawPermissions alias in generated types.\n metadata: z\n .object({\n name: z.string(),\n description: z.string().optional(),\n settings: TailorDBTypeSettingsSchema.optional(),\n permissions: RawPermissionsSchema,\n files: z.record(z.string(), z.string()),\n indexes: z\n .record(\n z.string(),\n z.strictObject({\n fields: z.array(z.string()),\n unique: z.boolean().optional(),\n }),\n )\n .optional(),\n typeHook: z\n .strictObject({\n create: functionSchema.optional(),\n update: functionSchema.optional(),\n })\n .optional(),\n typeValidate: functionSchema.optional(),\n })\n .strict(),\n});\n\nconst TailorDBMigrationConfigSchema = z.strictObject({\n directory: z.string().describe(\"Directory containing migration files\"),\n machineUser: z.string().optional().describe(\"Machine user name for migration execution\"),\n});\n\n/**\n * Schema for TailorDB service configuration.\n * Normalizes gqlOperations from alias (\"query\") to object format.\n */\nexport const TailorDBServiceConfigSchema = z.strictObject({\n files: z.array(z.string()).describe(\"Glob patterns for TailorDB type definition files\"),\n ignores: z.array(z.string()).optional().describe(\"Glob patterns to exclude from type discovery\"),\n migration: TailorDBMigrationConfigSchema.optional().describe(\"Migration configuration\"),\n gqlOperations: GqlOperationsSchema.optional().describe(\n \"Default GraphQL operations for all types in this service\",\n ),\n});\n","import { isSdkBranded } from \"#/utils/brand\";\nimport { TailorDBTypeSchema } from \"./schema\";\n\nconst TAILORDB_TYPE_SCHEMA_KEYS = TailorDBTypeSchema.keyof().options;\n\nexport function stripTailorDBTypeBuilderHelpers(type: unknown): unknown {\n if (!isSdkBranded(type, \"tailordb-type\")) {\n return type;\n }\n\n const config: Record<string, unknown> = {};\n const input = type as Record<string, unknown>;\n for (const key of TAILORDB_TYPE_SCHEMA_KEYS) {\n if (Object.prototype.hasOwnProperty.call(input, key)) {\n config[key] = input[key];\n }\n }\n return config;\n}\n","import { z } from \"zod\";\n\nexport const AuthConnectionOAuth2ConfigSchema = z.strictObject({\n providerUrl: z.string().describe(\"OAuth2 provider URL\"),\n issuerUrl: z.string().describe(\"OAuth2 issuer URL\"),\n clientId: z.string().describe(\"OAuth2 client ID\"),\n clientSecret: z.string().describe(\"OAuth2 client secret\"),\n authUrl: z.string().optional().describe(\"OAuth2 authorization endpoint override\"),\n tokenUrl: z.string().optional().describe(\"OAuth2 token endpoint override\"),\n});\n\nexport const AuthConnectionConfigSchema = AuthConnectionOAuth2ConfigSchema.extend({\n type: z.literal(\"oauth2\").describe(\"Connection type\"),\n});\n","import { z } from \"zod\";\nimport { functionSchema } from \"../common\";\n\nconst TailorFieldTypeSchema = z.enum([\n \"uuid\",\n \"string\",\n \"boolean\",\n \"integer\",\n \"float\",\n \"decimal\",\n \"enum\",\n \"date\",\n \"datetime\",\n \"time\",\n \"nested\",\n]);\n\nconst AllowedValueSchema = z.strictObject({\n value: z.string().describe(\"The allowed value\"),\n description: z.string().optional().describe(\"Description of the allowed value\"),\n});\n\nconst FieldMetadataSchema = z.strictObject({\n required: z.boolean().optional().describe(\"Whether the field is required\"),\n array: z.boolean().optional().describe(\"Whether the field is an array\"),\n description: z.string().optional().describe(\"Field description\"),\n allowedValues: z.array(AllowedValueSchema).optional().describe(\"Allowed values for enum fields\"),\n hooks: z\n .strictObject({\n create: functionSchema.optional().describe(\"Hook function called on creation\"),\n update: functionSchema.optional().describe(\"Hook function called on update\"),\n })\n .optional()\n .describe(\"Lifecycle hooks\"),\n validate: z.array(functionSchema).optional().describe(\"Validation functions for the field\"),\n typeName: z.string().optional().describe(\"Type name for nested or enum fields\"),\n default: z.unknown().optional().describe(\"Default value for the field on create\"),\n});\n\n// strip unknown keys\nexport const TailorFieldSchema = z.object({\n type: TailorFieldTypeSchema.describe(\"Field data type\"),\n metadata: FieldMetadataSchema.describe(\"Field metadata configuration\"),\n get fields() {\n return z.record(z.string(), TailorFieldSchema);\n },\n});\n","import { z } from \"zod\";\nimport { AuthConnectionConfigSchema } from \"#/parser/service/auth-connection/index\";\nimport { TailorFieldSchema } from \"#/parser/service/field/schema\";\nimport { stripTailorDBTypeBuilderHelpers } from \"#/parser/service/tailordb/builder-helpers\";\nimport { TailorDBTypeSchema } from \"#/parser/service/tailordb/index\";\nimport type { ValueOperand } from \"#/configure/services/auth/types\";\nimport type { TailorDBInstance } from \"#/configure/services/tailordb/types\";\n\nexport const AuthInvokerObjectSchema = z.strictObject({\n namespace: z.string().describe(\"Auth namespace\"),\n machineUserName: z.string().describe(\"Machine user name for authentication\"),\n});\n\nexport const AuthInvokerSchema = z.union([\n z.string().describe(\"Machine user name (namespace auto-resolved from auth service)\"),\n AuthInvokerObjectSchema,\n]);\n\nconst secretValueSchema = z.strictObject({\n vaultName: z.string().describe(\"Vault name containing the secret\"),\n secretKey: z.string().describe(\"Key of the secret in the vault\"),\n});\n\nexport const OIDCSchema = z.strictObject({\n name: z.string().describe(\"Identity provider name\"),\n kind: z.literal(\"OIDC\"),\n clientID: z.string().describe(\"OAuth2 client ID\"),\n clientSecret: secretValueSchema.describe(\"OAuth2 client secret\"),\n providerURL: z.string().describe(\"OIDC provider URL\"),\n issuerURL: z.string().optional().describe(\"OIDC issuer URL (defaults to providerURL)\"),\n usernameClaim: z.string().optional().describe(\"JWT claim to use as username\"),\n});\n\nexport const SAMLSchema = z\n .strictObject({\n name: z.string().describe(\"Identity provider name\"),\n kind: z.literal(\"SAML\"),\n enableSignRequest: z.boolean().default(false).describe(\"Enable signing of SAML requests\"),\n metadataURL: z\n .string()\n .optional()\n .describe(\"URL to fetch SAML metadata (mutually exclusive with rawMetadata)\"),\n rawMetadata: z\n .string()\n .optional()\n .describe(\"Raw SAML metadata XML (mutually exclusive with metadataURL)\"),\n defaultRedirectURL: z\n .string()\n .optional()\n .describe(\"URL to redirect to when SAML ACS receives a response with an empty RelayState.\"),\n })\n\n .refine((value) => {\n const hasMetadata = value.metadataURL !== undefined;\n const hasRaw = value.rawMetadata !== undefined;\n return hasMetadata !== hasRaw;\n }, \"Provide either metadataURL or rawMetadata\");\n\nexport const IDTokenSchema = z.strictObject({\n name: z.string().describe(\"Identity provider name\"),\n kind: z.literal(\"IDToken\"),\n providerURL: z.string().describe(\"ID token provider URL\"),\n issuerURL: z.string().optional().describe(\"ID token issuer URL\"),\n clientID: z.string().describe(\"Client ID for ID token validation\"),\n usernameClaim: z.string().optional().describe(\"JWT claim to use as username\"),\n});\n\nexport const BuiltinIdPSchema = z.strictObject({\n name: z.string().describe(\"Identity provider name\"),\n kind: z.literal(\"BuiltInIdP\"),\n namespace: z.string().describe(\"IdP namespace\"),\n clientName: z.string().describe(\"OAuth2 client name in the IdP\"),\n});\n\nexport const IdProviderSchema = z.discriminatedUnion(\"kind\", [\n OIDCSchema,\n SAMLSchema,\n IDTokenSchema,\n BuiltinIdPSchema,\n]);\n\nexport const OAuth2ClientGrantTypeSchema = z\n .union([z.literal(\"authorization_code\"), z.literal(\"refresh_token\")])\n .describe(\"OAuth2 grant type\");\n\nexport const OAuth2ClientSchema = z\n .strictObject({\n description: z.string().optional().describe(\"Client description\"),\n grantTypes: z\n .array(OAuth2ClientGrantTypeSchema)\n .default([\"authorization_code\", \"refresh_token\"])\n .describe(\"Allowed OAuth2 grant types\"),\n redirectURIs: z\n .array(\n z.union([\n z.templateLiteral([\"https://\", z.string()]),\n z.templateLiteral([\"http://\", z.string()]),\n z.templateLiteral([z.string(), \":url\"]),\n z.templateLiteral([z.string(), \":url/\", z.string()]),\n ]),\n )\n .describe(\"Allowed redirect URIs\"),\n clientType: z\n .union([z.literal(\"confidential\"), z.literal(\"public\"), z.literal(\"browser\")])\n .optional()\n .describe(\"OAuth2 client type\"),\n accessTokenLifetimeSeconds: z\n .number()\n .int()\n .min(60, \"Minimum access token lifetime is 60 seconds\")\n .max(86400, \"Maximum access token lifetime is 1 day (86400 seconds)\")\n .optional()\n .describe(\"Access token lifetime in seconds (60-86400)\")\n .transform((val) => (val ? { seconds: BigInt(val), nanos: 0 } : undefined)),\n refreshTokenLifetimeSeconds: z\n .number()\n .int()\n .min(60, \"Minimum refresh token lifetime is 60 seconds\")\n .max(604800, \"Maximum refresh token lifetime is 7 days (604800 seconds)\")\n .optional()\n .describe(\"Refresh token lifetime in seconds (60-604800)\")\n .transform((val) => (val ? { seconds: BigInt(val), nanos: 0 } : undefined)),\n requireDpop: z\n .boolean()\n .optional()\n .describe(\"Require DPoP (Demonstrating Proof-of-Possession) for token requests\"),\n })\n\n .refine((data) => !(data.clientType === \"browser\" && data.requireDpop === true), {\n message: \"requireDpop cannot be set to true for browser clients as they don't support DPoP\",\n path: [\"requireDpop\"],\n });\n\nexport const SCIMAuthorizationSchema = z.strictObject({\n type: z.union([z.literal(\"oauth2\"), z.literal(\"bearer\")]).describe(\"SCIM authorization type\"),\n bearerSecret: secretValueSchema\n .optional()\n .describe(\"Bearer token secret (required for bearer type)\"),\n});\n\nexport const SCIMAttributeTypeSchema = z\n .union([\n z.literal(\"string\"),\n z.literal(\"number\"),\n z.literal(\"boolean\"),\n z.literal(\"datetime\"),\n z.literal(\"complex\"),\n ])\n .describe(\"SCIM attribute data type\");\n\nexport const SCIMAttributeSchema = z.strictObject({\n type: SCIMAttributeTypeSchema.describe(\"Attribute data type\"),\n name: z.string().describe(\"Attribute name\"),\n description: z.string().optional().describe(\"Attribute description\"),\n mutability: z\n .union([z.literal(\"readOnly\"), z.literal(\"readWrite\"), z.literal(\"writeOnly\")])\n .optional()\n .describe(\"Attribute mutability\"),\n required: z.boolean().optional().describe(\"Whether the attribute is required\"),\n multiValued: z.boolean().optional().describe(\"Whether the attribute can have multiple values\"),\n uniqueness: z\n .union([z.literal(\"none\"), z.literal(\"server\"), z.literal(\"global\")])\n .optional()\n .describe(\"Uniqueness constraint\"),\n canonicalValues: z.array(z.string()).nullable().optional().describe(\"List of canonical values\"),\n get subAttributes() {\n return z.array(SCIMAttributeSchema).nullable().optional();\n },\n});\n\nconst SCIMSchemaSchema = z.strictObject({\n name: z.string().describe(\"SCIM schema name\"),\n attributes: z.array(SCIMAttributeSchema).describe(\"Schema attributes\"),\n});\n\nexport const SCIMAttributeMappingSchema = z.strictObject({\n tailorDBField: z.string().describe(\"TailorDB field name to map to\"),\n scimPath: z.string().describe(\"SCIM attribute path\"),\n});\n\nexport const SCIMResourceSchema = z.strictObject({\n name: z.string().describe(\"SCIM resource name\"),\n tailorDBNamespace: z.string().describe(\"TailorDB namespace for the resource\"),\n tailorDBType: z.string().describe(\"TailorDB type name for the resource\"),\n coreSchema: SCIMSchemaSchema.describe(\"Core SCIM schema definition\"),\n attributeMapping: z.array(SCIMAttributeMappingSchema).describe(\"Attribute mapping configuration\"),\n});\n\nexport const SCIMSchema = z.strictObject({\n machineUserName: z.string().describe(\"Machine user name for SCIM operations\"),\n authorization: SCIMAuthorizationSchema.describe(\"SCIM authorization configuration\"),\n resources: z.array(SCIMResourceSchema).describe(\"SCIM resource definitions\"),\n});\n\nexport const TenantProviderSchema = z.strictObject({\n namespace: z.string().describe(\"TailorDB namespace for the tenant type\"),\n type: z.string().describe(\"TailorDB type name for tenants\"),\n signatureField: z.string().describe(\"Field used as the tenant signature\"),\n});\n\nconst UserProfileSchema = z.strictObject({\n namespace: z.string().optional().describe(\"TailorDB namespace where the user type is defined\"),\n type: z\n .custom<TailorDBInstance>()\n .transform(stripTailorDBTypeBuilderHelpers)\n .pipe(TailorDBTypeSchema),\n usernameField: z.string(),\n attributes: z.record(z.string(), z.literal(true)).optional(),\n attributeList: z.array(z.string()).optional(),\n});\n\nconst ValueOperandSchema: z.ZodType<ValueOperand> = z.union([\n z.string(),\n z.boolean(),\n z.array(z.string()),\n z.array(z.boolean()),\n]);\n\nconst MachineUserSchema = z.strictObject({\n // null/undefined values mean \"attribute not set\" and are dropped so\n // downstream (deploy, drift diff) only ever sees concrete values.\n attributes: z\n .record(z.string(), ValueOperandSchema.nullish())\n .transform(\n (attributes): Record<string, ValueOperand> =>\n Object.fromEntries(\n Object.entries(attributes).filter(\n (entry): entry is [string, ValueOperand] => entry[1] != null,\n ),\n ),\n )\n .optional(),\n attributeList: z.array(z.uuid()).optional(),\n});\n\nconst BeforeLoginHookSchema = z.strictObject({\n handler: z.function(),\n invoker: z.string(),\n});\n\nconst AuthConfigBaseSchema = z.strictObject({\n name: z.string().describe(\"Auth service name\"),\n hooks: z\n .strictObject({\n beforeLogin: BeforeLoginHookSchema.optional().describe(\"Before login auth hook\"),\n })\n .optional()\n .describe(\"Auth hooks\"),\n machineUsers: z\n .record(z.string(), MachineUserSchema)\n .optional()\n .describe(\"Machine user definitions\"),\n oauth2Clients: z\n .record(z.string(), OAuth2ClientSchema)\n .optional()\n .describe(\"OAuth2 client definitions\"),\n idProvider: IdProviderSchema.optional().describe(\"Identity provider configuration\"),\n scim: SCIMSchema.optional().describe(\"SCIM provisioning configuration\"),\n tenantProvider: TenantProviderSchema.optional().describe(\"Multi-tenant provider configuration\"),\n connections: z\n .record(z.string(), AuthConnectionConfigSchema)\n .optional()\n .describe(\"Auth connection definitions for external OAuth2 providers\"),\n publishSessionEvents: z.boolean().optional().describe(\"Enable publishing session events\"),\n});\n\nexport const AuthConfigSchema = z\n .xor(\n [\n AuthConfigBaseSchema.extend({\n userProfile: UserProfileSchema.optional().describe(\"User profile configuration\"),\n machineUserAttributes: z.undefined().optional(),\n }),\n AuthConfigBaseSchema.extend({\n userProfile: z.undefined().optional(),\n machineUserAttributes: z\n .record(z.string(), TailorFieldSchema)\n .describe(\"Machine user attribute fields\"),\n }),\n ],\n {\n error: (iss) => {\n // zod may report error codes not covered by its type definitions\n // oxlint-disable-next-line typescript/no-unnecessary-condition\n if (iss.code !== \"invalid_union\") return undefined;\n // zod may report error codes not covered by its type definitions\n // oxlint-disable-next-line typescript/no-unnecessary-condition\n if (iss.errors.length < 2) return undefined;\n const isOnlyMutexViolation = iss.errors.every((variantErrors) =>\n variantErrors.every(\n (e) =>\n e.path.length === 1 &&\n (e.path[0] === \"userProfile\" || e.path[0] === \"machineUserAttributes\"),\n ),\n );\n if (isOnlyMutexViolation) {\n return \"Specify either `userProfile` or `machineUserAttributes`, not both.\";\n }\n return undefined;\n },\n },\n )\n .brand(\"AuthConfig\");\n","import { z } from \"zod\";\nimport { AuthInvokerSchema } from \"../auth\";\nimport { functionSchema } from \"../common\";\nimport type { JsonValue } from \"#/types/helpers\";\n\nexport const TailorDBTriggerSchema = z.strictObject({\n kind: z.literal(\"tailordb\").describe(\"TailorDB record event trigger\"),\n events: z\n .array(\n z.enum([\n \"tailordb.type_record.created\",\n \"tailordb.type_record.updated\",\n \"tailordb.type_record.deleted\",\n ]),\n )\n .min(1)\n .transform((arr) => [...new Set(arr)])\n .describe(\"TailorDB event types to trigger on\"),\n typeName: z.string().describe(\"TailorDB type name to watch for events\"),\n condition: functionSchema.optional().describe(\"Condition function to filter events\"),\n});\n\nexport const ResolverExecutedTriggerSchema = z.strictObject({\n kind: z.literal(\"resolverExecuted\"),\n resolverName: z.string().describe(\"Name of the resolver to trigger on\"),\n condition: functionSchema.optional().describe(\"Condition function to filter events\"),\n});\n\nexport const ScheduleTriggerSchema = z.strictObject({\n kind: z.literal(\"schedule\"),\n cron: z.string().describe(\"CRON expression for the schedule\"),\n timezone: z\n .string()\n .optional()\n .default(\"UTC\")\n .describe(\"Timezone for the CRON schedule (default: UTC)\"),\n});\n\nexport const IncomingWebhookTriggerResponseSchema = z.strictObject({\n body: functionSchema.optional().describe(\"Function returning the response body\"),\n statusCode: z.number().int().optional().describe(\"HTTP status code for the response\"),\n});\n\nexport const IncomingWebhookTriggerSchema = z.strictObject({\n kind: z.literal(\"incomingWebhook\"),\n response: IncomingWebhookTriggerResponseSchema.optional().describe(\"Response configuration\"),\n});\n\nexport const IdpUserTriggerSchema = z.strictObject({\n kind: z.literal(\"idpUser\").describe(\"IdP user event trigger\"),\n events: z\n .array(z.enum([\"idp.user.created\", \"idp.user.updated\", \"idp.user.deleted\"]))\n .min(1)\n .transform((arr) => [...new Set(arr)])\n .describe(\"IdP user event types to trigger on\"),\n idp: z\n .string()\n .optional()\n .describe(\n \"IdP namespace name to subscribe to. If omitted, the project's only IdP is used; throws when multiple IdPs exist.\",\n ),\n});\n\nexport const AuthAccessTokenTriggerSchema = z.strictObject({\n kind: z.literal(\"authAccessToken\").describe(\"Auth access token event trigger\"),\n events: z\n .array(\n z.enum([\n \"auth.access_token.issued\",\n \"auth.access_token.refreshed\",\n \"auth.access_token.revoked\",\n ]),\n )\n .min(1)\n .transform((arr) => [...new Set(arr)])\n .describe(\"Auth access token event types to trigger on\"),\n});\n\nconst workflowNameSchema = z\n .string()\n .refine((value) => value.trim().length > 0, \"Workflow name cannot be blank\")\n .describe(\"Workflow name to subscribe to.\");\n\nexport const WorkflowExecutionTriggerSchema = z.strictObject({\n kind: z.literal(\"workflowExecution\").describe(\"Workflow execution event trigger\"),\n events: z\n .array(\n z.enum([\n \"workflow.workflow_execution.started\",\n \"workflow.workflow_execution.completed\",\n \"workflow.workflow_execution.retried\",\n \"workflow.workflow_execution.resumed\",\n \"workflow.workflow_execution.wait_started\",\n \"workflow.workflow_execution.wait_resolved\",\n ]),\n )\n .min(1)\n .transform((arr) => [...new Set(arr)])\n .describe(\"Workflow execution event types to trigger on\"),\n workflowName: workflowNameSchema,\n condition: functionSchema.optional().describe(\"Condition function to filter events\"),\n});\n\nexport const WorkflowJobExecutionTriggerSchema = z.strictObject({\n kind: z.literal(\"workflowJobExecution\").describe(\"Workflow job execution event trigger\"),\n events: z\n .array(\n z.enum([\n \"workflow.workflow_execution.job_execution.started\",\n \"workflow.workflow_execution.job_execution.completed\",\n \"workflow.workflow_execution.job_execution.wait_started\",\n \"workflow.workflow_execution.job_execution.wait_resolved\",\n ]),\n )\n .min(1)\n .transform((arr) => [...new Set(arr)])\n .describe(\"Workflow job execution event types to trigger on\"),\n workflowName: workflowNameSchema,\n condition: functionSchema.optional().describe(\"Condition function to filter events\"),\n});\n\nexport const TriggerSchema = z.discriminatedUnion(\"kind\", [\n TailorDBTriggerSchema,\n ResolverExecutedTriggerSchema,\n ScheduleTriggerSchema,\n IncomingWebhookTriggerSchema,\n IdpUserTriggerSchema,\n AuthAccessTokenTriggerSchema,\n WorkflowExecutionTriggerSchema,\n WorkflowJobExecutionTriggerSchema,\n]);\n\nexport const FunctionOperationSchema = z.strictObject({\n kind: z.enum([\"function\", \"jobFunction\"]),\n body: functionSchema.describe(\"Function implementation\"),\n invoker: AuthInvokerSchema.optional().describe(\"Invoker for the function execution\"),\n});\n\nexport const GqlOperationSchema = z.strictObject({\n kind: z.literal(\"graphql\"),\n appName: z.string().optional().describe(\"Target application name for the GraphQL query\"),\n query: z.preprocess((val) => String(val), z.string().describe(\"GraphQL query string\")),\n variables: functionSchema.optional().describe(\"Function to compute GraphQL variables\"),\n invoker: AuthInvokerSchema.optional().describe(\"Invoker for the GraphQL execution\"),\n});\n\nexport const WebhookOperationSchema = z.strictObject({\n kind: z.literal(\"webhook\"),\n url: functionSchema.describe(\"Function returning the webhook URL\"),\n requestBody: functionSchema.optional().describe(\"Function to compute the request body\"),\n headers: z\n .record(\n z.string(),\n z.union([z.string(), z.strictObject({ vault: z.string(), key: z.string() })]),\n )\n .optional()\n .describe(\"HTTP headers for the webhook request\"),\n});\n\nexport const JsonValueSchema: z.ZodType<JsonValue, JsonValue> = z.lazy(() =>\n z.union([\n z.string(),\n z.number(),\n z.boolean(),\n z.null(),\n z.array(JsonValueSchema),\n z.record(z.string(), JsonValueSchema),\n ]),\n);\n\nexport const WorkflowInputSchema: z.ZodType<\n Exclude<JsonValue, null>,\n Exclude<JsonValue, null>\n> = z.union([\n z.string(),\n z.number(),\n z.boolean(),\n z.array(JsonValueSchema),\n z.record(z.string(), JsonValueSchema),\n]);\n\nexport const WorkflowOperationArgsSchema = z\n .union([WorkflowInputSchema, functionSchema])\n .describe(\"Arguments to pass to the workflow\");\n\nconst workflowOperationShape = {\n kind: z.literal(\"workflow\"),\n args: WorkflowOperationArgsSchema.optional(),\n invoker: AuthInvokerSchema.optional().describe(\"Invoker for the workflow execution\"),\n};\n\nconst WorkflowOperationByNameSchema = z.strictObject({\n ...workflowOperationShape,\n workflowName: z.string().describe(\"Name of the workflow to execute\"),\n workflow: z.never().optional(),\n});\n\nconst WorkflowOperationByReferenceSchema = z\n .strictObject({\n ...workflowOperationShape,\n workflow: z.looseObject({ name: z.string() }),\n workflowName: z.string().optional(),\n })\n .transform(({ workflow, ...operation }) => ({\n ...operation,\n workflowName: workflow.name,\n }));\n\nexport const WorkflowOperationSchema = z.union([\n WorkflowOperationByReferenceSchema,\n WorkflowOperationByNameSchema,\n]);\n\nexport const OperationSchema = z.union([\n FunctionOperationSchema,\n GqlOperationSchema,\n WebhookOperationSchema,\n WorkflowOperationSchema,\n]);\n\nexport const ExecutorSchema = z.strictObject({\n name: z.string().describe(\"Executor name\"),\n description: z.string().optional().describe(\"Executor description\"),\n disabled: z.boolean().optional().default(false).describe(\"Whether the executor is disabled\"),\n trigger: TriggerSchema.describe(\"Event trigger configuration\"),\n operation: OperationSchema.describe(\"Operation to execute when triggered\"),\n});\n","import { pathToFileURL } from \"node:url\";\nimport { ExecutorSchema } from \"#/parser/service/executor/index\";\nimport { isSdkBranded } from \"#/utils/brand\";\nimport type { Executor } from \"#/types/executor.generated\";\n\nexport function stripExecutorTriggerArgs(executor: unknown): unknown {\n if (!isSdkBranded(executor, \"executor\")) {\n return executor;\n }\n\n const trigger = (executor as { trigger?: unknown }).trigger;\n if (trigger === null || typeof trigger !== \"object\" || !(\"__args\" in trigger)) {\n return executor;\n }\n\n const { __args: _args, ...triggerConfig } = trigger as Record<string, unknown>;\n return { ...(executor as Record<string, unknown>), trigger: triggerConfig };\n}\n\n/**\n * Load and validate an executor definition from a file.\n * @param executorFilePath - Path to the executor file\n * @returns Parsed executor or null if invalid\n */\nexport async function loadExecutor(executorFilePath: string): Promise<Executor | null> {\n const executorModule = await import(pathToFileURL(executorFilePath).href);\n const executor = executorModule.default;\n\n const parseResult = ExecutorSchema.safeParse(stripExecutorTriggerArgs(executor));\n if (!parseResult.success) {\n return null;\n }\n\n return parseResult.data;\n}\n","import { pathToFileURL } from \"node:url\";\nimport * as path from \"pathe\";\nimport { loadFilesWithIgnores } from \"#/cli/services/file-loader\";\nimport { logger, styles } from \"#/cli/shared/logger\";\nimport { ExecutorSchema } from \"#/parser/service/executor/index\";\nimport { isSdkBranded } from \"#/utils/brand\";\nimport { stripExecutorTriggerArgs } from \"./loader\";\nimport type { ExecutorServiceConfig } from \"#/configure/config/types\";\nimport type { Executor } from \"#/types/executor.generated\";\n\n/**\n * Information about a plugin-generated executor converted to Executor format\n */\nexport interface PluginExecutor {\n /** The executor in standard Executor format */\n executor: Executor;\n /** Plugin ID that generated this executor */\n pluginId: string;\n /** Source type name (for type-attached executors) */\n sourceTypeName?: string;\n}\n\nexport type ExecutorService = {\n readonly config: ExecutorServiceConfig;\n readonly executors: Record<string, Executor>;\n readonly pluginExecutors: ReadonlyArray<PluginExecutor>;\n loadExecutors: () => Promise<Record<string, Executor> | undefined>;\n loadPluginExecutorFiles: (filePaths: string[]) => Promise<void>;\n};\n\n/**\n * Parameters for creating an ExecutorService\n */\nexport interface CreateExecutorServiceParams {\n /** The executor service configuration */\n config: ExecutorServiceConfig;\n /** Directory the config's file patterns are resolved against */\n baseDir: string;\n}\n\n/**\n * Creates a new ExecutorService instance.\n * @param params - Parameters for creating the service\n * @returns A new ExecutorService instance\n */\nexport function createExecutorService(params: CreateExecutorServiceParams): ExecutorService {\n const { config, baseDir } = params;\n const executors: Record<string, Executor> = {};\n const pluginExecutors: PluginExecutor[] = [];\n let loadPromise: Promise<Record<string, Executor> | undefined> | undefined;\n\n const loadExecutorForFile = async (executorFile: string): Promise<Executor | undefined> => {\n try {\n const executorModule = await import(pathToFileURL(executorFile).href);\n const result = ExecutorSchema.safeParse(stripExecutorTriggerArgs(executorModule.default));\n if (result.success) {\n const relativePath = path.relative(process.cwd(), executorFile);\n logger.log(\n `Executor: ${styles.successBright(`\"${result.data.name}\"`)} loaded from ${styles.path(relativePath)}`,\n );\n executors[executorFile] = result.data;\n return result.data;\n }\n if (isSdkBranded(executorModule.default, \"executor\")) {\n throw result.error;\n }\n } catch (error) {\n const relativePath = path.relative(process.cwd(), executorFile);\n logger.error(`Failed to load executor from ${styles.bold(relativePath)}`);\n logger.error(String(error));\n throw error;\n }\n return undefined;\n };\n\n return {\n config,\n get executors() {\n return executors;\n },\n get pluginExecutors() {\n return pluginExecutors;\n },\n loadExecutors: async () => {\n if (!loadPromise) {\n loadPromise = (async () => {\n if (config.files.length === 0) {\n return undefined;\n }\n\n const executorFiles = loadFilesWithIgnores(config, baseDir);\n\n logger.newline();\n logger.log(`Found ${styles.highlight(executorFiles.length.toString())} executor files`);\n\n await Promise.all(executorFiles.map((executorFile) => loadExecutorForFile(executorFile)));\n assertUniqueExecutorNames(executors);\n return executors;\n })();\n }\n return loadPromise;\n },\n loadPluginExecutorFiles: async (filePaths: string[]) => {\n if (filePaths.length === 0) return;\n\n logger.newline();\n logger.log(\n `Loading ${styles.highlight(filePaths.length.toString())} plugin-generated executor files`,\n );\n\n for (const filePath of filePaths) {\n const executor = await loadExecutorForFile(filePath);\n if (executor) {\n // Track as plugin executor (plugin ID is extracted from file path)\n // File path format: .tailor/plugin/{executor-name}.ts\n pluginExecutors.push({\n executor,\n pluginId: \"plugin-generated\",\n sourceTypeName: undefined,\n });\n }\n }\n assertUniqueExecutorNames(executors);\n },\n };\n}\n\n/**\n * Assert that every loaded executor has a unique name.\n * Executors are stored by source file, so two files declaring the same\n * `name` would otherwise silently share a single bundle cache entry.\n * @param executors - Loaded executors keyed by source file\n */\nfunction assertUniqueExecutorNames(executors: Record<string, Executor>): void {\n const seenNames = new Map<string, string>();\n for (const [file, executor] of Object.entries(executors)) {\n const relativePath = path.relative(process.cwd(), file);\n const existing = seenNames.get(executor.name);\n if (existing) {\n throw new Error(\n `Duplicate executor name \"${executor.name}\" found:\\n` +\n ` - ${existing}\\n` +\n ` - ${relativePath}\\n` +\n `Each executor must have a unique name.`,\n );\n }\n seenNames.set(executor.name, relativePath);\n }\n}\n"],"mappings":";;;;;;;;AAIA,MAAa,iBAAgD,EAAE,QAC5D,QAAQ,OAAO,QAAQ,UAC1B;;;;ACGA,MAAM,0BAA0B,CAAC,gBAAgB,cAAc;AAQ/D,MAAM,kCAAkB,IAAI,IAAY;;;;;;;;AASxC,SAAgB,qBAAqB,QAAwB,SAA2B;CACtF,IAAI,OAAO,MAAM,WAAW,GAC1B,OAAO,CAAC;CAGV,MAAM,WAAW,aAAa,QAAQ,OAAO;CAC7C,MAAM,sBAAsB,OAAO,MAAM,OAAO,YAAY,KAAK,WAAW,OAAO,CAAC;CACpF,IAAI,SAAS,qBAAqB,YAAY,QAAQ,IAAI,KAAK,qBAC7D,OAAO,SAAS;CAalB,MAAM,cAAc,GAAG,QAAQ,IAAI,OAAO,MAAM,KAAK,IAAI;CACzD,IAAI,CAAC,gBAAgB,IAAI,WAAW,GAAG;EACrC,gBAAgB,IAAI,WAAW;EAC/B,OAAO,KACL,qBAAqB,OAAO,MAAM,KAAK,IAAI,EAAE,iBAAiB,QAAQ,wJAGxE;CACF;CACA,OAAO,aAAa,QAAQ,QAAQ,IAAI,CAAC,CAAC,CAAC;AAC7C;AAQA,SAAS,aAAa,QAAwB,SAAgC;CAM5E,MAAM,mBAAmB,OAAO,YAAY;CAC5C,MAAM,iBAAiB,OAAO,WAAW;CACzC,MAAM,yBAAyB,mBAC3B,iBACA,eAAe,KAAK,kBAAkB,KAAK,QAAQ,SAAS,aAAa,CAAC;CAE9E,MAAM,QAAkB,CAAC;CACzB,IAAI,oBAAoB;CACxB,KAAK,MAAM,WAAW,OAAO,OAAO;EAClC,MAAM,kBAAkB,KAAK,QAAQ,SAAS,OAAO;EACrD,IAAI;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,QACT,aAAa,yCAExB;EAEF,UAAU,IAAI,SAAS,MAAM,YAAY;CAC3C;AACF"}
|
|
@@ -1,75 +0,0 @@
|
|
|
1
|
-
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2
|
-
|
|
3
|
-
//#region src/configure/services/workflow/test-env-key.ts
|
|
4
|
-
/**
|
|
5
|
-
* Typed accessors for the test-time globalThis slot used to pass `env` from
|
|
6
|
-
* `mockWorkflow().setEnv()` (in `@tailor-platform/sdk/vitest`) to
|
|
7
|
-
* `runWorkflowLocally()` job bodies. The slot key is private to this
|
|
8
|
-
* module; callers go through the get/set/clear functions below so both sides
|
|
9
|
-
* share the same access path.
|
|
10
|
-
*
|
|
11
|
-
* Lives in its own file (with no `@/` imports) so `vitest/mock.ts` can load
|
|
12
|
-
* it from nested Vitest configs that do not resolve `@/` aliases.
|
|
13
|
-
* @internal
|
|
14
|
-
*/
|
|
15
|
-
const SLOT_KEY = "__tailorWorkflowTestEnv";
|
|
16
|
-
let invokerStorage;
|
|
17
|
-
function workflowInvokerStorage() {
|
|
18
|
-
if (!invokerStorage) invokerStorage = new AsyncLocalStorage();
|
|
19
|
-
return invokerStorage;
|
|
20
|
-
}
|
|
21
|
-
/**
|
|
22
|
-
* Read the test-time env slot.
|
|
23
|
-
* @returns Current env, or `undefined` when unset.
|
|
24
|
-
* @internal
|
|
25
|
-
*/
|
|
26
|
-
function readWorkflowTestEnv() {
|
|
27
|
-
return globalThis[SLOT_KEY];
|
|
28
|
-
}
|
|
29
|
-
/**
|
|
30
|
-
* Write the test-time env slot.
|
|
31
|
-
* @param env - Env value to expose to `runWorkflowLocally()` job bodies.
|
|
32
|
-
* @internal
|
|
33
|
-
*/
|
|
34
|
-
function writeWorkflowTestEnv(env) {
|
|
35
|
-
globalThis[SLOT_KEY] = env;
|
|
36
|
-
}
|
|
37
|
-
/**
|
|
38
|
-
* Clear the test-time env slot.
|
|
39
|
-
* @internal
|
|
40
|
-
*/
|
|
41
|
-
function clearWorkflowTestEnv() {
|
|
42
|
-
delete globalThis[SLOT_KEY];
|
|
43
|
-
}
|
|
44
|
-
function withWorkflowTestInvoker(invoker, run) {
|
|
45
|
-
return workflowInvokerStorage().run(invoker, run);
|
|
46
|
-
}
|
|
47
|
-
function readRuntimeInvoker() {
|
|
48
|
-
const runtime = globalThis.tailor?.context?.getInvoker;
|
|
49
|
-
const raw = runtime?.();
|
|
50
|
-
if (!raw) return null;
|
|
51
|
-
return {
|
|
52
|
-
id: raw.id,
|
|
53
|
-
type: raw.type,
|
|
54
|
-
workspaceId: raw.workspaceId,
|
|
55
|
-
attributes: raw.attributeMap ?? (Array.isArray(raw.attributes) ? {} : raw.attributes ?? {}),
|
|
56
|
-
attributeList: raw.attributeList ?? (Array.isArray(raw.attributes) ? raw.attributes : [])
|
|
57
|
-
};
|
|
58
|
-
}
|
|
59
|
-
function buildJobContext() {
|
|
60
|
-
const storedInvoker = invokerStorage?.getStore();
|
|
61
|
-
const invoker = storedInvoker === void 0 ? readRuntimeInvoker() : storedInvoker;
|
|
62
|
-
const fromGlobal = readWorkflowTestEnv();
|
|
63
|
-
if (fromGlobal !== void 0) return {
|
|
64
|
-
env: { ...fromGlobal },
|
|
65
|
-
invoker
|
|
66
|
-
};
|
|
67
|
-
return {
|
|
68
|
-
env: {},
|
|
69
|
-
invoker
|
|
70
|
-
};
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
//#endregion
|
|
74
|
-
export { writeWorkflowTestEnv as a, withWorkflowTestInvoker as i, clearWorkflowTestEnv as n, readWorkflowTestEnv as r, buildJobContext as t };
|
|
75
|
-
//# sourceMappingURL=test-env-key-D7UkZp99.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"test-env-key-D7UkZp99.mjs","names":[],"sources":["../src/configure/services/workflow/test-env-key.ts"],"sourcesContent":["/**\n * Typed accessors for the test-time globalThis slot used to pass `env` from\n * `mockWorkflow().setEnv()` (in `@tailor-platform/sdk/vitest`) to\n * `runWorkflowLocally()` job bodies. The slot key is private to this\n * module; callers go through the get/set/clear functions below so both sides\n * share the same access path.\n *\n * Lives in its own file (with no `@/` imports) so `vitest/mock.ts` can load\n * it from nested Vitest configs that do not resolve `@/` aliases.\n * @internal\n */\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport type { TailorEnv, TailorPrincipal } from \"../../../runtime/types\";\n\nconst SLOT_KEY = \"__tailorWorkflowTestEnv\";\n\ntype AsyncLocalStorageLike<T> = {\n getStore(): T | undefined;\n run<R>(store: T, callback: () => R): R;\n};\n\nlet invokerStorage: AsyncLocalStorageLike<TailorPrincipal | null> | undefined;\n\nfunction workflowInvokerStorage(): AsyncLocalStorageLike<TailorPrincipal | null> {\n if (!invokerStorage) {\n invokerStorage = new AsyncLocalStorage<TailorPrincipal | null>();\n }\n return invokerStorage;\n}\n\n/**\n * Read the test-time env slot.\n * @returns Current env, or `undefined` when unset.\n * @internal\n */\nexport function readWorkflowTestEnv(): TailorEnv | undefined {\n return (globalThis as unknown as Record<string, TailorEnv | undefined>)[SLOT_KEY];\n}\n\n/**\n * Write the test-time env slot.\n * @param env - Env value to expose to `runWorkflowLocally()` job bodies.\n * @internal\n */\nexport function writeWorkflowTestEnv(env: TailorEnv): void {\n (globalThis as unknown as Record<string, TailorEnv>)[SLOT_KEY] = env;\n}\n\n/**\n * Clear the test-time env slot.\n * @internal\n */\nexport function clearWorkflowTestEnv(): void {\n delete (globalThis as unknown as Record<string, unknown>)[SLOT_KEY];\n}\n\nexport function withWorkflowTestInvoker<T>(invoker: TailorPrincipal | null, run: () => T): T {\n return workflowInvokerStorage().run(invoker, run);\n}\n\ntype RuntimeInvoker = {\n id: string;\n type: \"user\" | \"machine_user\";\n workspaceId: string;\n attributes?: string[] | TailorPrincipal[\"attributes\"];\n attributeMap?: TailorPrincipal[\"attributes\"];\n attributeList?: TailorPrincipal[\"attributeList\"];\n};\n\nfunction readRuntimeInvoker(): TailorPrincipal | null {\n const runtime = (\n globalThis as unknown as {\n tailor?: { context?: { getInvoker?: () => RuntimeInvoker | null } };\n }\n ).tailor?.context?.getInvoker;\n const raw = runtime?.();\n if (!raw) return null;\n return {\n id: raw.id,\n type: raw.type,\n workspaceId: raw.workspaceId,\n attributes: raw.attributeMap ?? (Array.isArray(raw.attributes) ? {} : (raw.attributes ?? {})),\n attributeList: (raw.attributeList ??\n (Array.isArray(raw.attributes) ? raw.attributes : [])) as TailorPrincipal[\"attributeList\"],\n };\n}\n\n// Shallow-copied to isolate against cross-trigger mutation.\nexport function buildJobContext(): { env: TailorEnv; invoker: TailorPrincipal | null } {\n const storedInvoker = invokerStorage?.getStore();\n const invoker = storedInvoker === undefined ? readRuntimeInvoker() : storedInvoker;\n const fromGlobal = readWorkflowTestEnv();\n if (fromGlobal !== undefined) return { env: { ...fromGlobal }, invoker };\n return { env: {} as TailorEnv, invoker };\n}\n"],"mappings":";;;;;;;;;;;;;;AAcA,MAAM,WAAW;AAOjB,IAAI;AAEJ,SAAS,yBAAwE;CAC/E,IAAI,CAAC,gBACH,iBAAiB,IAAI,kBAA0C;CAEjE,OAAO;AACT;;;;;;AAOA,SAAgB,sBAA6C;CAC3D,OAAQ,WAAgE;AAC1E;;;;;;AAOA,SAAgB,qBAAqB,KAAsB;CACzD,AAAC,WAAoD,YAAY;AACnE;;;;;AAMA,SAAgB,uBAA6B;CAC3C,OAAQ,WAAkD;AAC5D;AAEA,SAAgB,wBAA2B,SAAiC,KAAiB;CAC3F,OAAO,uBAAuB,CAAC,CAAC,IAAI,SAAS,GAAG;AAClD;AAWA,SAAS,qBAA6C;CACpD,MAAM,UACJ,WAGA,QAAQ,SAAS;CACnB,MAAM,MAAM,UAAU;CACtB,IAAI,CAAC,KAAK,OAAO;CACjB,OAAO;EACL,IAAI,IAAI;EACR,MAAM,IAAI;EACV,aAAa,IAAI;EACjB,YAAY,IAAI,iBAAiB,MAAM,QAAQ,IAAI,UAAU,IAAI,CAAC,IAAK,IAAI,cAAc,CAAC;EAC1F,eAAgB,IAAI,kBACjB,MAAM,QAAQ,IAAI,UAAU,IAAI,IAAI,aAAa,CAAC;CACvD;AACF;AAGA,SAAgB,kBAAuE;CACrF,MAAM,gBAAgB,gBAAgB,SAAS;CAC/C,MAAM,UAAU,kBAAkB,SAAY,mBAAmB,IAAI;CACrE,MAAM,aAAa,oBAAoB;CACvC,IAAI,eAAe,QAAW,OAAO;EAAE,KAAK,EAAE,GAAG,WAAW;EAAG;CAAQ;CACvE,OAAO;EAAE,KAAK,CAAC;EAAgB;CAAQ;AACzC"}
|