@tailor-platform/sdk 2.21.0 → 2.23.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 +52 -0
- package/agent-skills/tailor/SKILL.md +3 -1
- package/dist/aigateway-DsWDjzk4.mjs.map +1 -1
- package/dist/application-BtZ8hmx9.mjs +1 -0
- package/dist/{application-D4913edS.mjs → application-m2G91kKI.mjs} +29 -29
- package/dist/application-m2G91kKI.mjs.map +1 -0
- package/dist/assert-WeXvmG4j.mjs.map +1 -1
- package/dist/authconnection-CynFBIv8.mjs.map +1 -1
- package/dist/brand-C8nMKhJC.mjs.map +1 -1
- package/dist/cli/commands/deploy/app-id-lock.d.mts +31 -0
- package/dist/cli/lib.d.mts +2 -2
- package/dist/cli/lib.mjs +1 -1
- package/dist/cli/lib.mjs.map +1 -1
- package/dist/cli/main.mjs +41 -41
- package/dist/cli/main.mjs.map +1 -1
- package/dist/cli/shared/client.d.mts +17 -2
- package/dist/cli/shared/logger.d.mts +9 -0
- package/dist/cli/shared/tailordb-namespaces.d.mts +1 -1
- package/dist/completion/zsh-worker.zsh +13 -7
- package/dist/configure/config/index.d.mts +2 -0
- package/dist/configure/index.mjs.map +1 -1
- package/dist/context-D0QjfxzD.mjs.map +1 -1
- package/dist/crashreport-CBaRJl5h.mjs +1 -0
- package/dist/{crashreport-BAz-ph5O.mjs → crashreport-DFpRn-LS.mjs} +4 -4
- package/dist/crashreport-DFpRn-LS.mjs.map +1 -0
- package/dist/date-Dri6Yas-.mjs.map +1 -1
- package/dist/errors-CpvSChyL.mjs +7 -0
- package/dist/errors-CpvSChyL.mjs.map +1 -0
- package/dist/es-builtins-SfvXRVoG.mjs.map +1 -1
- package/dist/field-parse-DhnFs9WG.mjs.map +1 -1
- package/dist/file-DKBOj5q4.mjs.map +1 -1
- package/dist/globals-BCmGX05J.mjs.map +1 -1
- package/dist/guards-yDXyKC9F.mjs +2 -0
- package/dist/guards-yDXyKC9F.mjs.map +1 -0
- package/dist/iconv-DlFMt2gW.mjs.map +1 -1
- package/dist/idp-G_ojPBB5.mjs.map +1 -1
- package/dist/interceptor-DQg3cR_9.mjs.map +1 -1
- package/dist/kysely/index.mjs.map +1 -1
- package/dist/kysely-type-C-iyFFH7.mjs.map +1 -1
- package/dist/logger-DP2BjQ93.mjs.map +1 -1
- package/dist/logger-Db-YRTwK.mjs +9 -0
- package/dist/logger-Db-YRTwK.mjs.map +1 -0
- package/dist/{manager-C0dE7pd0.mjs → manager-8-JOvuLl.mjs} +2 -2
- package/dist/manager-8-JOvuLl.mjs.map +1 -0
- package/dist/multiline-EyzjEwn9.mjs.map +1 -1
- package/dist/node-builtins-DYfhPBnz.mjs.map +1 -1
- package/dist/package-json-C690ceex.mjs.map +1 -1
- package/dist/platform-serialize-DkiTdHOt.mjs.map +1 -1
- package/dist/plugin/builtin/enum-constants/index.mjs.map +1 -1
- package/dist/plugin/builtin/file-utils/index.mjs.map +1 -1
- package/dist/plugin/index.mjs +1 -1
- package/dist/plugin/index.mjs.map +1 -1
- package/dist/register-ts-hook-ztnEFW6n.mjs +922 -0
- package/dist/register-ts-hook-ztnEFW6n.mjs.map +1 -0
- package/dist/registry-BijIDRVA.mjs.map +1 -1
- package/dist/repl-editor-DGJBfIt1.mjs.map +1 -1
- package/dist/schema-CRtAmDcl.mjs.map +1 -1
- package/dist/secret-file-C9wp_FCX.mjs.map +1 -1
- package/dist/secretmanager-5olfnI1b.mjs.map +1 -1
- package/dist/secretmanager-vHQoXdQz.mjs.map +1 -1
- package/dist/seed/index.mjs +7 -6
- package/dist/seed/index.mjs.map +1 -1
- package/dist/seed-C3P_T_Eh.mjs.map +1 -1
- package/dist/service-Bx-7Lz06.mjs +1 -0
- package/dist/{service-BrGSi2IQ.mjs → service-CL1Bp4It.mjs} +3 -3
- package/dist/service-CL1Bp4It.mjs.map +1 -0
- package/dist/{service-8xznUrPU.mjs → service-DFmt9UJP.mjs} +2 -2
- package/dist/service-DFmt9UJP.mjs.map +1 -0
- package/dist/service_pb-ZClWtj1X.mjs +2 -0
- package/dist/service_pb-ZClWtj1X.mjs.map +1 -0
- package/dist/service_pb-dB3RrGeh.mjs +1 -0
- package/dist/tailor-proto/src/tailor/v1/function_pb.d.mts +83 -1
- package/dist/tailor-proto/src/tailor/v1/function_resource_pb.d.mts +7 -1
- package/dist/tailor-proto/src/tailor/v1/service_pb.d.mts +79 -7
- package/dist/tailor-proto/src/tailor/v1/workflow_pb.d.mts +40 -1
- package/dist/tailor-proto/src/tailor/v1/workflow_resource_pb.d.mts +119 -2
- package/dist/tailor-proto/src/tailor/v1/workspace_pb.d.mts +7 -0
- package/dist/tailordb-ddl-DqInYupv.mjs.map +1 -1
- package/dist/telemetry-Bklv9kQY.mjs.map +1 -1
- package/dist/type-source--ZNcV8RJ.mjs.map +1 -1
- package/dist/user-agent-vdHYF3QL.mjs.map +1 -1
- package/dist/utils/test/index.mjs.map +1 -1
- package/dist/vitest/environment.mjs.map +1 -1
- package/dist/vitest/index.mjs.map +1 -1
- package/dist/vitest/mocks/file.d.mts +1 -1
- package/dist/vitest/setup.mjs.map +1 -1
- package/dist/wait-point-invoker-eiP-IIux.mjs.map +1 -1
- package/dist/wait-point-registry-B-ESkTZX.mjs.map +1 -1
- package/dist/workflow-Cs9ISw6j.mjs.map +1 -1
- package/dist/{workspace_resource_pb-D2njwgsE.mjs → workspace_resource_pb-CxR_6fyN.mjs} +2 -2
- package/dist/workspace_resource_pb-CxR_6fyN.mjs.map +1 -0
- package/docs/cli/application.md +23 -5
- package/docs/cli/function.md +2 -2
- package/docs/cli-reference.md +22 -12
- package/docs/configuration.md +1 -1
- package/docs/github-actions.md +90 -24
- package/docs/migration/v2.md +70 -5
- package/docs/plugin/index.md +1 -1
- package/package.json +10 -10
- package/dist/application-D4913edS.mjs.map +0 -1
- package/dist/application-DBHaxmJE.mjs +0 -1
- package/dist/crashreport-BAz-ph5O.mjs.map +0 -1
- package/dist/crashreport-BfOkOFgc.mjs +0 -1
- package/dist/errors-sNtg2Mv3.mjs +0 -7
- package/dist/errors-sNtg2Mv3.mjs.map +0 -1
- package/dist/guards-DsX7dJCP.mjs +0 -2
- package/dist/guards-DsX7dJCP.mjs.map +0 -1
- package/dist/logger-Cp5U2IDI.mjs +0 -9
- package/dist/logger-Cp5U2IDI.mjs.map +0 -1
- package/dist/manager-C0dE7pd0.mjs.map +0 -1
- package/dist/register-ts-hook-YtsAGTMD.mjs +0 -921
- package/dist/register-ts-hook-YtsAGTMD.mjs.map +0 -1
- package/dist/service-8xznUrPU.mjs.map +0 -1
- package/dist/service-BrGSi2IQ.mjs.map +0 -1
- package/dist/service-DWMm-4Vm.mjs +0 -1
- package/dist/service_pb-DNskuJQC.mjs +0 -1
- package/dist/service_pb-y2GYIgfs.mjs +0 -2
- package/dist/service_pb-y2GYIgfs.mjs.map +0 -1
- package/dist/workspace_resource_pb-D2njwgsE.mjs.map +0 -1
package/dist/seed/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../../src/seed/record-lines.ts","../../src/seed/index.ts"],"sourcesContent":["import { readFile } from \"node:fs/promises\";\nimport type { ValidationErrorDetail } from \"@toiroakr/lines-db\";\n\n/**\n * Resolve the 1-based physical line a JSONL record occupies.\n *\n * The seed reader drops blank and whitespace-only lines before indexing its\n * records, so a record's index is not its line number once a file contains\n * one. Reported locations have to point at the line a reader would open.\n * @param content - Raw JSONL file contents\n * @param recordIndex - 0-based index among the file's non-blank lines\n * @returns 1-based physical line, or undefined when the file holds no such record\n */\nexport function physicalLineOfRecord(content: string, recordIndex: number): number | undefined {\n const lines = content.split(\"\\n\");\n let remaining = recordIndex;\n for (const [index, line] of lines.entries()) {\n if (line.trim().length === 0) continue;\n if (remaining === 0) return index + 1;\n remaining -= 1;\n }\n return undefined;\n}\n\n/**\n * Locate the first reported error in its own file.\n *\n * Errors are reported per record, so the index is mapped back to a physical\n * line; a file that cannot be re-read yields the file alone rather than a\n * guessed line.\n * @param errors - Validation errors in the order the validator reported them\n * @returns Location of the first error, or undefined when there is none\n */\nexport async function firstErrorLocation(\n errors: readonly ValidationErrorDetail[],\n): Promise<{ file: string; line?: number } | undefined> {\n const first = errors[0];\n if (!first) return undefined;\n try {\n const content = await readFile(first.file, \"utf-8\");\n return { file: first.file, line: physicalLineOfRecord(content, first.rowIndex) };\n } catch {\n return { file: first.file };\n }\n}\n","/**\n * Seed integration module for generated seed code.\n *\n * Re-exports `@toiroakr/lines-db` through a single import path\n * to avoid phantom dependency issues with pnpm, and provides\n * seed-specific utility functions used by the code generator.\n */\n\nimport { readdir, readFile, stat, writeFile } from \"node:fs/promises\";\nimport { pathToFileURL } from \"node:url\";\nimport { LinesDB, ErrorFormatter, findSchemaFile } from \"@toiroakr/lines-db\";\n// `pathe`, not `node:path`: the file paths reported back are printed and returned\n// to the caller, and these stay separator-stable across platforms.\nimport { basename, dirname, join } from \"pathe\";\nimport { firstErrorLocation } from \"./record-lines\";\nimport type { JsonObject, ValidationErrorDetail } from \"@toiroakr/lines-db\";\n\nexport { defineSchema } from \"@toiroakr/lines-db\";\nexport type { ForeignKeyDefinition, IndexDefinition } from \"@toiroakr/lines-db\";\n\n/** Fields `fillSeedData` writes when the caller names none. */\nconst DEFAULT_FILL_FIELDS = [\"id\"];\n\ntype SeedDataTarget = {\n dataDir: string;\n tableName?: string;\n};\n\ntype ValidateSeedDataOptions = {\n /** Resolved absolute path to a data directory or a .jsonl file */\n path: string;\n /** Show verbose error output */\n verbose?: boolean;\n};\n\ntype ValidateSeedResult =\n | { valid: true; output: string }\n | {\n valid: false;\n output: string;\n error: string;\n /** Where the first reported error sits, for tooling that links to source. */\n location?: { file: string; line?: number };\n };\n\n/**\n * A JSONL seed file that received values.\n */\ntype FilledSeedFile = {\n /** Name of the seeded table, matching the JSONL file name */\n table: string;\n /** Absolute path to the updated JSONL file */\n file: string;\n /** Fields that were written back to the file */\n fields: string[];\n /** How many rows were missing at least one of those fields */\n count: number;\n};\n\ntype FillSeedDataOptions = {\n /** Resolved absolute path to a data directory or a .jsonl file */\n path: string;\n /** Fields to fill. Defaults to `id`. */\n fields?: readonly string[];\n};\n\ntype FillSeedDataResult = {\n output: string;\n filled: FilledSeedFile[];\n};\n\nasync function resolveSeedDataTarget(resolvedPath: string): Promise<SeedDataTarget> {\n const stats = await stat(resolvedPath);\n if (stats.isDirectory()) {\n return { dataDir: resolvedPath };\n }\n if (stats.isFile() && resolvedPath.endsWith(\".jsonl\")) {\n return { dataDir: dirname(resolvedPath), tableName: basename(resolvedPath, \".jsonl\") };\n }\n throw new Error(`Invalid path: ${resolvedPath}. Must be a directory or .jsonl file.`);\n}\n\nasync function listSeedTables(dataDir: string): Promise<string[]> {\n const entries = await readdir(dataDir);\n return entries\n .filter((entry) => entry.endsWith(\".jsonl\"))\n .map((entry) => basename(entry, \".jsonl\"))\n .toSorted();\n}\n\nfunction formatWarnings(warnings: string[]): string[] {\n if (warnings.length === 0) {\n return [];\n }\n return [...warnings.map((warning) => `⚠ ${warning}`), \"\"];\n}\n\nfunction formatValidationErrors(errors: ValidationErrorDetail[], verbose: boolean): string {\n const formatter = new ErrorFormatter({ verbose });\n const errorLines: string[] = [];\n const errorsByFile = new Map<string, ValidationErrorDetail[]>();\n for (const error of errors) {\n const fileErrors = errorsByFile.get(error.file) || [];\n fileErrors.push(error);\n errorsByFile.set(error.file, fileErrors);\n }\n for (const [file, fileErrors] of errorsByFile) {\n errorLines.push(formatter.formatErrorHeader(fileErrors.length, file));\n errorLines.push(\"\");\n const validationErrors = fileErrors.filter(\n (e) => e.type !== \"foreignKey\" || !e.foreignKeyError,\n );\n const foreignKeyErrors = fileErrors.filter((e) => e.type === \"foreignKey\" && e.foreignKeyError);\n if (validationErrors.length > 0) {\n errorLines.push(\n formatter.formatValidationErrors(\n validationErrors.map((e) => ({\n file: e.file,\n rowIndex: e.rowIndex,\n issues: e.issues,\n })),\n ),\n );\n }\n for (const fkError of foreignKeyErrors) {\n if (fkError.foreignKeyError) {\n errorLines.push(\n formatter.formatForeignKeyError({\n file: fkError.file,\n rowIndex: fkError.rowIndex,\n column: fkError.foreignKeyError.column,\n value: fkError.foreignKeyError.value,\n referencedTable: fkError.foreignKeyError.referencedTable,\n referencedColumn: fkError.foreignKeyError.referencedColumn,\n }),\n );\n }\n }\n errorLines.push(\"\");\n }\n\n return errorLines.join(\"\\n\");\n}\n\n/**\n * Validate JSONL seed data against schema definitions.\n * Resolves the given path (directory or `.jsonl` file), validates the rows it\n * holds, and returns formatted output and error messages.\n * @param options - Validation options including path and verbose flag\n * @returns Validation result with output messages and optional error details\n */\nexport async function validateSeedData(\n options: ValidateSeedDataOptions,\n): Promise<ValidateSeedResult> {\n const { path: resolvedPath, verbose = false } = options;\n const { dataDir, tableName } = await resolveSeedDataTarget(resolvedPath);\n\n const db = LinesDB.create({ dataDir });\n let result;\n try {\n result = await db.initialize({ tableName, detailedValidate: true });\n } finally {\n await db.close();\n }\n\n const outputLines = formatWarnings(result.warnings);\n\n if (result.valid) {\n outputLines.push(\"✓ All records are valid\");\n return { valid: true, output: outputLines.join(\"\\n\") };\n }\n\n return {\n valid: false,\n output: outputLines.join(\"\\n\"),\n error: formatValidationErrors(result.errors, verbose),\n location: await firstErrorLocation(result.errors),\n };\n}\n\n// A row's own value for a field, or undefined when the row has none.\nfunction ownValue(row: Record<string, unknown>, field: string): unknown {\n return Object.hasOwn(row, field) ? row[field] : undefined;\n}\n\n// Not `row[field] = value`: a field named `__proto__` goes through the inherited\n// setter, which leaves no own property for the serializer to read back.\nfunction setField(row: JsonObject, field: string, value: JsonObject[string]): void {\n Object.defineProperty(row, field, {\n value,\n enumerable: true,\n writable: true,\n configurable: true,\n });\n}\n\nfunction isBlank(value: unknown): boolean {\n if (value === undefined || value === null) {\n return true;\n }\n if (typeof value !== \"object\" || Array.isArray(value)) {\n return false;\n }\n // A nested field the row never had comes back as an object whose keys carry no\n // value of their own, and writing that into the line fills nothing in.\n return Object.values(value).every(isBlank);\n}\n\n/** A JSONL line, kept as text so an untouched line is written back verbatim. */\ntype SeedLine = {\n text: string;\n /** Line separator the file used after this line, kept so CRLF survives. */\n eol: string;\n row: JsonObject | undefined;\n};\n\nfunction splitLines(content: string): SeedLine[] {\n if (content === \"\") {\n return [];\n }\n return content.split(\"\\n\").map((raw, index, all) => {\n const eol = index === all.length - 1 ? \"\" : \"\\n\";\n const text = raw.endsWith(\"\\r\") ? raw.slice(0, -1) : raw;\n const carriage = raw.endsWith(\"\\r\") ? \"\\r\" : \"\";\n let row: JsonObject | undefined;\n if (text.trim() !== \"\") {\n try {\n const parsed: unknown = JSON.parse(text);\n row =\n parsed !== null && typeof parsed === \"object\" && !Array.isArray(parsed)\n ? (parsed as JsonObject)\n : undefined;\n } catch {\n row = undefined;\n }\n }\n return { text, eol: `${carriage}${eol}`, row };\n });\n}\n\n// Keys go in the order the hook produced them, which is the order the table\n// declares its fields. Keys the table does not declare follow the declared ones.\nfunction serializeRow(row: JsonObject, fieldOrder: string[]): string {\n const rank = new Map(fieldOrder.map((field, index) => [field, index]));\n const rankOf = (key: string): number => rank.get(key) ?? fieldOrder.length;\n return JSON.stringify(\n Object.fromEntries(Object.entries(row).toSorted(([a], [b]) => rankOf(a) - rankOf(b))),\n );\n}\n\ntype SeedHook = (row: unknown) => Record<string, unknown>;\n\nasync function loadSeedHook(dataDir: string, table: string): Promise<SeedHook | undefined> {\n const schemaPath = await findSchemaFile(dataDir, table);\n if (!schemaPath) {\n return undefined;\n }\n const loaded: unknown = await import(pathToFileURL(schemaPath).href);\n const hook = (loaded as { hook?: unknown }).hook;\n if (typeof hook !== \"function\") {\n throw new Error(\n `${schemaPath} does not export \\`hook\\`. Run \\`tailor generate\\` to regenerate the seed schema files.`,\n );\n }\n return hook as SeedHook;\n}\n\n/**\n * Fill in the values a record gets on create for the JSONL seed data rows that\n * are missing them, so a row can be referenced by `id` or carry a timestamp\n * before it is ever seeded.\n *\n * The values come from the table's own create-time behavior — its `id`, its field\n * defaults, and its create hooks — applied to each row on its own. Nothing is\n * validated, so a row can be filled while the data around it is still\n * incomplete: that is what lets you get the ids you need in order to write the\n * rows that reference them. Run `validateSeedData` when the data is ready.\n *\n * Only the named fields are written, and only into a row that has no value for\n * them, so a value already in the file is never replaced. A line that gains\n * nothing is written back exactly as it was, byte for byte; a line that does get\n * a value is re-serialized with its keys in the order the table declares its\n * fields, so a filled-in `id` lands at the front. A field the table gives no\n * value to — one it does not declare, or one the platform assigns such as a\n * serial field — is skipped, so one field list covers a whole data directory.\n *\n * The values are read from the schema files generated next to the data, and all\n * of them are read before anything is written: a file that predates the current\n * generator stops the run with nothing filled in anywhere.\n * @param options - Fill options including path and fields\n * @returns Which files received which fields\n */\nexport async function fillSeedData(options: FillSeedDataOptions): Promise<FillSeedDataResult> {\n const { path: resolvedPath, fields = DEFAULT_FILL_FIELDS } = options;\n if (fields.length === 0) {\n throw new Error(\"No fields to fill. Name at least one field.\");\n }\n const { dataDir, tableName } = await resolveSeedDataTarget(resolvedPath);\n const tables = tableName ? [tableName] : await listSeedTables(dataDir);\n\n const warnings: string[] = [];\n const filled: FilledSeedFile[] = [];\n const producedFields = new Set<string>();\n\n // Every hook loads before anything is written, so a schema file that predates\n // `tailor generate` stops the run instead of leaving half the files filled.\n const hooks: { table: string; hook: SeedHook }[] = [];\n for (const table of tables) {\n const hook = await loadSeedHook(dataDir, table);\n if (!hook) {\n warnings.push(`No schema file for ${table}, so nothing can be filled in there`);\n continue;\n }\n hooks.push({ table, hook });\n }\n\n // Every line is decided before any file is written, so a hook that throws on\n // one table cannot leave another one already rewritten.\n const writes: { file: string; content: string }[] = [];\n for (const { table, hook } of hooks) {\n const file = join(dataDir, `${table}.jsonl`);\n const lines = splitLines(await readFile(file, \"utf-8\"));\n\n const written = new Set<string>();\n const unreadable: number[] = [];\n let count = 0;\n let fieldOrder: string[] = [];\n for (const [index, line] of lines.entries()) {\n const row = line.row;\n if (!row) {\n if (line.text.trim() !== \"\") {\n unreadable.push(index + 1);\n }\n continue;\n }\n const hooked = hook(row);\n fieldOrder = Object.keys(hooked);\n const gained = fields.filter((field) => {\n const value = ownValue(hooked, field);\n if (isBlank(value)) {\n return false;\n }\n producedFields.add(field);\n return isBlank(ownValue(row, field));\n });\n if (gained.length === 0) {\n continue;\n }\n for (const field of gained) {\n setField(row, field, hooked[field] as JsonObject[string]);\n written.add(field);\n }\n line.text = serializeRow(row, fieldOrder);\n count += 1;\n }\n\n if (unreadable.length > 0) {\n warnings.push(\n `${file}: line(s) ${unreadable.join(\", \")} are not JSON objects, so nothing was filled in there`,\n );\n }\n\n if (count === 0) {\n continue;\n }\n writes.push({ file, content: lines.map((line) => `${line.text}${line.eol}`).join(\"\") });\n filled.push({ table, file, fields: [...written], count });\n }\n\n for (const { file, content } of writes) {\n await writeFile(file, content);\n }\n\n const unproducedFields = fields.filter((field) => !producedFields.has(field));\n if (tables.length > 0 && unproducedFields.length > 0) {\n warnings.push(`No seed data produces a value for: ${unproducedFields.join(\", \")}`);\n }\n\n const outputLines = formatWarnings(warnings);\n outputLines.push(\n filled.length === 0\n ? \"\\u2713 Nothing to fill\"\n : filled\n .map(\n ({ file, fields: tableFields, count }) =>\n `\\u2713 ${file}: filled ${tableFields.join(\", \")} in ${count} row(s)`,\n )\n .join(\"\\n\"),\n );\n\n return { output: outputLines.join(\"\\n\"), filled };\n}\n"],"mappings":"0RAaA,SAAgB,qBAAqB,EAAiB,EAAyC,CAC7F,IAAM,EAAQ,EAAQ,MAAM;CAAI,EAC5B,EAAY,EAChB,IAAK,GAAM,CAAC,EAAO,KAAS,EAAM,QAAQ,EACpC,KAAK,KAAK,CAAC,CAAC,SAAW,EAC3B,IAAI,IAAc,EAAG,OAAO,EAAQ,EACpC,GADoC,CAIxC,CAWA,eAAsB,mBACpB,EACsD,CACtD,IAAM,EAAQ,EAAO,GAChB,KACL,GAAI,CACF,IAAM,EAAU,MAAM,EAAS,EAAM,KAAM,OAAO,EAClD,MAAO,CAAE,KAAM,EAAM,KAAM,KAAM,qBA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AAM,KAAS,EAClB,SAAS,EAAK,EAAO,EAAO,EAA4B,EACxD,EAAQ,IAAI,CAAK,EAEnB,EAAK,KAAO,aAAa,EAAK,CAAU,EACxC,GAAS,CAFT,CAGF,CAEI,EAAW,OAAS,GACtB,EAAS,KACP,GAAG,EAAK,YAAY,EAAW,KAAK,IAAI,EAAE,sDAC5C,EAGE,IAAU,IAGd,EAAO,KAAK,CAAE,OAAM,QAAS,EAAM,IAAK,GAAS,GAAG,EAAK,OAAO,EAAK,KAAK,CAAC,CAAC,KAAK,EAAE,CAAE,CAAC,EACtF,EAAO,KAAK,CAAE,QAAO,OAAM,OAAQ,CAAC,GAAG,CAAO,EAAG,OAAM,CAAC,EAC1D,CAEA,IAAK,GAAM,CAAE,OAAM,aAAa,EAC9B,MAAM,EAAU,EAAM,CAAO,EAG/B,IAAM,EAAmB,EAAO,OAAQ,GAAU,CAAC,EAAe,IAAI,CAAK,CAAC,EACxE,EAAO,OAAS,GAAK,EAAiB,OAAS,GACjD,EAAS,KAAK,sCAAsC,EAAiB,KAAK,IAAI,GAAG,EAGnF,IAAM,EAAc,eAAe,CAAQ,EAY3C,OAXA,EAAY,KACV,EAAO,SAAW,EACd,oBACA,EACG,KACE,CAAE,OAAM,OAAQ,EAAa,WAC5B,UAAU,EAAK,WAAW,EAAY,KAAK,IAAI,EAAE,MAAM,EAAM,QACjE,CAAC,CACA,KAAK;CAAI,CAClB,EAEO,CAAE,OAAQ,EAAY,KAAK;CAAI,EAAG,QAAO,CAClD"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["lines","content","remaining","recordIndex","index","line","first","errors","readFile","DEFAULT_FILL_FIELDS","stats","stat","resolvedPath","dirname","basename","readdir","dataDir","entry","warnings","warning","error","formatter","ErrorFormatter","errorLines","errorsByFile","fileErrors","file","validationErrors","foreignKeyErrors","fkError","options","db","LinesDB","initialized","unwrap","message","result","outputLines","verbose","row","field","value","eol","all","text","raw","carriage","parsed","rank","fieldOrder","key","a","b","schemaPath","findSchemaFile","table","hook","pathToFileURL","fields","tables","tableName","filled","producedFields","hooks","writes","join","written","unreadable","count","hooked","gained","writeFile","unproducedFields","tableFields","defineSchema"],"sources":["../../src/seed/record-lines.ts","../../src/seed/index.ts"],"sourcesContent":["import { readFile } from \"node:fs/promises\";\nimport type { ValidationErrorDetail } from \"@toiroakr/lines-db\";\n\n/**\n * Resolve the 1-based physical line a JSONL record occupies.\n *\n * The seed reader drops blank and whitespace-only lines before indexing its\n * records, so a record's index is not its line number once a file contains\n * one. Reported locations have to point at the line a reader would open.\n * @param content - Raw JSONL file contents\n * @param recordIndex - 0-based index among the file's non-blank lines\n * @returns 1-based physical line, or undefined when the file holds no such record\n */\nexport function physicalLineOfRecord(content: string, recordIndex: number): number | undefined {\n const lines = content.split(\"\\n\");\n let remaining = recordIndex;\n for (const [index, line] of lines.entries()) {\n if (line.trim().length === 0) continue;\n if (remaining === 0) return index + 1;\n remaining -= 1;\n }\n return undefined;\n}\n\n/**\n * Locate the first reported error in its own file.\n *\n * Errors are reported per record, so the index is mapped back to a physical\n * line; a file that cannot be re-read yields the file alone rather than a\n * guessed line.\n * @param errors - Validation errors in the order the validator reported them\n * @returns Location of the first error, or undefined when there is none\n */\nexport async function firstErrorLocation(\n errors: readonly ValidationErrorDetail[],\n): Promise<{ file: string; line?: number } | undefined> {\n const first = errors[0];\n if (!first) return undefined;\n try {\n const content = await readFile(first.file, \"utf-8\");\n return { file: first.file, line: physicalLineOfRecord(content, first.rowIndex) };\n } catch {\n return { file: first.file };\n }\n}\n","/**\n * Seed integration module for generated seed code.\n *\n * Re-exports `@toiroakr/lines-db` through a single import path\n * to avoid phantom dependency issues with pnpm, and provides\n * seed-specific utility functions used by the code generator.\n */\n\nimport { readdir, readFile, stat, writeFile } from \"node:fs/promises\";\nimport { pathToFileURL } from \"node:url\";\nimport { LinesDB, ErrorFormatter, findSchemaFile, unwrap } from \"@toiroakr/lines-db\";\n// `pathe`, not `node:path`: the file paths reported back are printed and returned\n// to the caller, and these stay separator-stable across platforms.\nimport { basename, dirname, join } from \"pathe\";\nimport { firstErrorLocation } from \"./record-lines\";\nimport type { JsonObject, JsonlParseError, ValidationErrorDetail } from \"@toiroakr/lines-db\";\n\nexport { defineSchema } from \"@toiroakr/lines-db\";\nexport type { ForeignKeyDefinition, IndexDefinition } from \"@toiroakr/lines-db\";\n\n/** Fields `fillSeedData` writes when the caller names none. */\nconst DEFAULT_FILL_FIELDS = [\"id\"];\n\ntype SeedDataTarget = {\n dataDir: string;\n tableName?: string;\n};\n\ntype ValidateSeedDataOptions = {\n /** Resolved absolute path to a data directory or a .jsonl file */\n path: string;\n /** Show verbose error output */\n verbose?: boolean;\n};\n\ntype ValidateSeedResult =\n | { valid: true; output: string }\n | {\n valid: false;\n output: string;\n error: string;\n /** Where the first reported error sits, for tooling that links to source. */\n location?: { file: string; line?: number };\n };\n\n/**\n * A JSONL seed file that received values.\n */\ntype FilledSeedFile = {\n /** Name of the seeded table, matching the JSONL file name */\n table: string;\n /** Absolute path to the updated JSONL file */\n file: string;\n /** Fields that were written back to the file */\n fields: string[];\n /** How many rows were missing at least one of those fields */\n count: number;\n};\n\ntype FillSeedDataOptions = {\n /** Resolved absolute path to a data directory or a .jsonl file */\n path: string;\n /** Fields to fill. Defaults to `id`. */\n fields?: readonly string[];\n};\n\ntype FillSeedDataResult = {\n output: string;\n filled: FilledSeedFile[];\n};\n\nasync function resolveSeedDataTarget(resolvedPath: string): Promise<SeedDataTarget> {\n const stats = await stat(resolvedPath);\n if (stats.isDirectory()) {\n return { dataDir: resolvedPath };\n }\n if (stats.isFile() && resolvedPath.endsWith(\".jsonl\")) {\n return { dataDir: dirname(resolvedPath), tableName: basename(resolvedPath, \".jsonl\") };\n }\n throw new Error(`Invalid path: ${resolvedPath}. Must be a directory or .jsonl file.`);\n}\n\nasync function listSeedTables(dataDir: string): Promise<string[]> {\n const entries = await readdir(dataDir);\n return entries\n .filter((entry) => entry.endsWith(\".jsonl\"))\n .map((entry) => basename(entry, \".jsonl\"))\n .toSorted();\n}\n\nfunction formatWarnings(warnings: string[]): string[] {\n if (warnings.length === 0) {\n return [];\n }\n return [...warnings.map((warning) => `⚠ ${warning}`), \"\"];\n}\n\nfunction isJsonlParseError(error: Error): error is JsonlParseError {\n return error.name === \"JsonlParseError\";\n}\n\nfunction formatValidationErrors(errors: ValidationErrorDetail[], verbose: boolean): string {\n const formatter = new ErrorFormatter({ verbose });\n const errorLines: string[] = [];\n const errorsByFile = new Map<string, ValidationErrorDetail[]>();\n for (const error of errors) {\n const fileErrors = errorsByFile.get(error.file) || [];\n fileErrors.push(error);\n errorsByFile.set(error.file, fileErrors);\n }\n for (const [file, fileErrors] of errorsByFile) {\n errorLines.push(formatter.formatErrorHeader(fileErrors.length, file));\n errorLines.push(\"\");\n const validationErrors = fileErrors.filter(\n (e) => e.type !== \"foreignKey\" || !e.foreignKeyError,\n );\n const foreignKeyErrors = fileErrors.filter((e) => e.type === \"foreignKey\" && e.foreignKeyError);\n if (validationErrors.length > 0) {\n errorLines.push(\n formatter.formatValidationErrors(\n validationErrors.map((e) => ({\n file: e.file,\n rowIndex: e.rowIndex,\n issues: e.issues,\n })),\n ),\n );\n }\n for (const fkError of foreignKeyErrors) {\n if (fkError.foreignKeyError) {\n errorLines.push(\n formatter.formatForeignKeyError({\n file: fkError.file,\n rowIndex: fkError.rowIndex,\n column: fkError.foreignKeyError.column,\n value: fkError.foreignKeyError.value,\n referencedTable: fkError.foreignKeyError.referencedTable,\n referencedColumn: fkError.foreignKeyError.referencedColumn,\n }),\n );\n }\n }\n errorLines.push(\"\");\n }\n\n return errorLines.join(\"\\n\");\n}\n\n/**\n * Validate JSONL seed data against schema definitions.\n * Resolves the given path (directory or `.jsonl` file), validates the rows it\n * holds, and returns formatted output and error messages.\n * @param options - Validation options including path and verbose flag\n * @returns Validation result with output messages and optional error details\n */\nexport async function validateSeedData(\n options: ValidateSeedDataOptions,\n): Promise<ValidateSeedResult> {\n const { path: resolvedPath, verbose = false } = options;\n const { dataDir, tableName } = await resolveSeedDataTarget(resolvedPath);\n\n const db = LinesDB.create({ dataDir });\n let initialized;\n try {\n initialized = await db.initialize({ tableName, detailedValidate: true });\n } finally {\n unwrap(await db.close());\n }\n if (!initialized.ok && isJsonlParseError(initialized.error)) {\n const { file, line, message } = initialized.error;\n return {\n valid: false,\n output: \"\",\n error: [\n new ErrorFormatter({ verbose }).formatErrorHeader(1, file),\n \"\",\n ` Line ${line}: ${message}`,\n \"\",\n ].join(\"\\n\"),\n location: { file, line },\n };\n }\n const result = unwrap(initialized);\n\n const outputLines = formatWarnings(result.warnings);\n\n if (result.valid) {\n outputLines.push(\"✓ All records are valid\");\n return { valid: true, output: outputLines.join(\"\\n\") };\n }\n\n return {\n valid: false,\n output: outputLines.join(\"\\n\"),\n error: formatValidationErrors(result.errors, verbose),\n location: await firstErrorLocation(result.errors),\n };\n}\n\n// A row's own value for a field, or undefined when the row has none.\nfunction ownValue(row: Record<string, unknown>, field: string): unknown {\n return Object.hasOwn(row, field) ? row[field] : undefined;\n}\n\n// Not `row[field] = value`: a field named `__proto__` goes through the inherited\n// setter, which leaves no own property for the serializer to read back.\nfunction setField(row: JsonObject, field: string, value: JsonObject[string]): void {\n Object.defineProperty(row, field, {\n value,\n enumerable: true,\n writable: true,\n configurable: true,\n });\n}\n\nfunction isBlank(value: unknown): boolean {\n if (value === undefined || value === null) {\n return true;\n }\n if (typeof value !== \"object\" || Array.isArray(value)) {\n return false;\n }\n // A nested field the row never had comes back as an object whose keys carry no\n // value of their own, and writing that into the line fills nothing in.\n return Object.values(value).every(isBlank);\n}\n\n/** A JSONL line, kept as text so an untouched line is written back verbatim. */\ntype SeedLine = {\n text: string;\n /** Line separator the file used after this line, kept so CRLF survives. */\n eol: string;\n row: JsonObject | undefined;\n};\n\nfunction splitLines(content: string): SeedLine[] {\n if (content === \"\") {\n return [];\n }\n return content.split(\"\\n\").map((raw, index, all) => {\n const eol = index === all.length - 1 ? \"\" : \"\\n\";\n const text = raw.endsWith(\"\\r\") ? raw.slice(0, -1) : raw;\n const carriage = raw.endsWith(\"\\r\") ? \"\\r\" : \"\";\n let row: JsonObject | undefined;\n if (text.trim() !== \"\") {\n try {\n const parsed: unknown = JSON.parse(text);\n row =\n parsed !== null && typeof parsed === \"object\" && !Array.isArray(parsed)\n ? (parsed as JsonObject)\n : undefined;\n } catch {\n row = undefined;\n }\n }\n return { text, eol: `${carriage}${eol}`, row };\n });\n}\n\n// Keys go in the order the hook produced them, which is the order the table\n// declares its fields. Keys the table does not declare follow the declared ones.\nfunction serializeRow(row: JsonObject, fieldOrder: string[]): string {\n const rank = new Map(fieldOrder.map((field, index) => [field, index]));\n const rankOf = (key: string): number => rank.get(key) ?? fieldOrder.length;\n return JSON.stringify(\n Object.fromEntries(Object.entries(row).toSorted(([a], [b]) => rankOf(a) - rankOf(b))),\n );\n}\n\ntype SeedHook = (row: unknown) => Record<string, unknown>;\n\nasync function loadSeedHook(dataDir: string, table: string): Promise<SeedHook | undefined> {\n const schemaPath = await findSchemaFile(dataDir, table);\n if (!schemaPath) {\n return undefined;\n }\n const loaded: unknown = await import(pathToFileURL(schemaPath).href);\n const hook = (loaded as { hook?: unknown }).hook;\n if (typeof hook !== \"function\") {\n throw new Error(\n `${schemaPath} does not export \\`hook\\`. Run \\`tailor generate\\` to regenerate the seed schema files.`,\n );\n }\n return hook as SeedHook;\n}\n\n/**\n * Fill in the values a record gets on create for the JSONL seed data rows that\n * are missing them, so a row can be referenced by `id` or carry a timestamp\n * before it is ever seeded.\n *\n * The values come from the table's own create-time behavior — its `id`, its field\n * defaults, and its create hooks — applied to each row on its own. Nothing is\n * validated, so a row can be filled while the data around it is still\n * incomplete: that is what lets you get the ids you need in order to write the\n * rows that reference them. Run `validateSeedData` when the data is ready.\n *\n * Only the named fields are written, and only into a row that has no value for\n * them, so a value already in the file is never replaced. A line that gains\n * nothing is written back exactly as it was, byte for byte; a line that does get\n * a value is re-serialized with its keys in the order the table declares its\n * fields, so a filled-in `id` lands at the front. A field the table gives no\n * value to — one it does not declare, or one the platform assigns such as a\n * serial field — is skipped, so one field list covers a whole data directory.\n *\n * The values are read from the schema files generated next to the data, and all\n * of them are read before anything is written: a file that predates the current\n * generator stops the run with nothing filled in anywhere.\n * @param options - Fill options including path and fields\n * @returns Which files received which fields\n */\nexport async function fillSeedData(options: FillSeedDataOptions): Promise<FillSeedDataResult> {\n const { path: resolvedPath, fields = DEFAULT_FILL_FIELDS } = options;\n if (fields.length === 0) {\n throw new Error(\"No fields to fill. Name at least one field.\");\n }\n const { dataDir, tableName } = await resolveSeedDataTarget(resolvedPath);\n const tables = tableName ? [tableName] : await listSeedTables(dataDir);\n\n const warnings: string[] = [];\n const filled: FilledSeedFile[] = [];\n const producedFields = new Set<string>();\n\n // Every hook loads before anything is written, so a schema file that predates\n // `tailor generate` stops the run instead of leaving half the files filled.\n const hooks: { table: string; hook: SeedHook }[] = [];\n for (const table of tables) {\n const hook = await loadSeedHook(dataDir, table);\n if (!hook) {\n warnings.push(`No schema file for ${table}, so nothing can be filled in there`);\n continue;\n }\n hooks.push({ table, hook });\n }\n\n // Every line is decided before any file is written, so a hook that throws on\n // one table cannot leave another one already rewritten.\n const writes: { file: string; content: string }[] = [];\n for (const { table, hook } of hooks) {\n const file = join(dataDir, `${table}.jsonl`);\n const lines = splitLines(await readFile(file, \"utf-8\"));\n\n const written = new Set<string>();\n const unreadable: number[] = [];\n let count = 0;\n let fieldOrder: string[] = [];\n for (const [index, line] of lines.entries()) {\n const row = line.row;\n if (!row) {\n if (line.text.trim() !== \"\") {\n unreadable.push(index + 1);\n }\n continue;\n }\n const hooked = hook(row);\n fieldOrder = Object.keys(hooked);\n const gained = fields.filter((field) => {\n const value = ownValue(hooked, field);\n if (isBlank(value)) {\n return false;\n }\n producedFields.add(field);\n return isBlank(ownValue(row, field));\n });\n if (gained.length === 0) {\n continue;\n }\n for (const field of gained) {\n setField(row, field, hooked[field] as JsonObject[string]);\n written.add(field);\n }\n line.text = serializeRow(row, fieldOrder);\n count += 1;\n }\n\n if (unreadable.length > 0) {\n warnings.push(\n `${file}: line(s) ${unreadable.join(\", \")} are not JSON objects, so nothing was filled in there`,\n );\n }\n\n if (count === 0) {\n continue;\n }\n writes.push({ file, content: lines.map((line) => `${line.text}${line.eol}`).join(\"\") });\n filled.push({ table, file, fields: [...written], count });\n }\n\n for (const { file, content } of writes) {\n await writeFile(file, content);\n }\n\n const unproducedFields = fields.filter((field) => !producedFields.has(field));\n if (tables.length > 0 && unproducedFields.length > 0) {\n warnings.push(`No seed data produces a value for: ${unproducedFields.join(\", \")}`);\n }\n\n const outputLines = formatWarnings(warnings);\n outputLines.push(\n filled.length === 0\n ? \"\\u2713 Nothing to fill\"\n : filled\n .map(\n ({ file, fields: tableFields, count }) =>\n `\\u2713 ${file}: filled ${tableFields.join(\", \")} in ${count} row(s)`,\n )\n .join(\"\\n\"),\n );\n\n return { output: outputLines.join(\"\\n\"), filled };\n}\n"],"mappings":"sSAaA,SAAgB,qBAAqB,EAAiB,EAAyC,CAC7F,IAAMA,EAAQC,EAAQ,MAAM;CAAI,EAC5BC,EAAYC,EAChB,IAAK,GAAM,CAACC,EAAOC,KAASL,EAAM,QAAQ,EACxC,GAAIK,EAAK,KAAK,CAAC,CAAC,SAAW,EAC3B,IAAIH,IAAc,EAAG,OAAOE,EAAQ,EACpC,GADoC,CAIxC,CAWA,eAAsB,mBACpB,EACsD,CACtD,IAAME,EAAQC,EAAO,GACrB,GAAKD,EACL,GAAI,CACF,IAAML,EAAU,MAAMO,EAASF,EAAM,KAAM,OAAO,EAClD,MAAO,CAAE,KAAMA,EAAM,KAAM,KAAM,qBAAqBL,EAASK,EAAM,QAAQ,CAAE,CACjF,MAAQ,CACN,MAAO,CAAE,KAAMA,EAAM,IAAK,CAC5B,CACF,CCvBA,MAAMG,EAAsB,CAAC,IAAI,EAkDjC,eAAe,sBAAsB,EAA+C,CAClF,IAAMC,EAAQ,MAAMC,EAAKC,CAAY,EACrC,GAAIF,EAAM,YAAY,EACpB,M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,EAAY,KACVwB,EAAO,SAAW,EACd,oBACAA,EACG,KACE,CAAE,OAAM,OAAQY,EAAa,WAC5B,UAAU/C,EAAK,WAAW+C,EAAY,KAAK,IAAI,EAAE,MAAML,EAAM,QACjE,CAAC,CACA,KAAK;CAAI,CAClB,EAEO,CAAE,OAAQ/B,EAAY,KAAK;CAAI,EAAG,QAAO,CAClD"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"seed-C3P_T_Eh.mjs","names":[],"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 userTableName: 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 { tableName, usernameField } = auth.userProfile;\n\n return {\n name: \"_User\",\n dependencies: [tableName],\n dataFile: \"data/_User.jsonl\",\n idpNamespace: auth.idProvider.namespace,\n schema: {\n usernameField,\n userTableName: tableName,\n },\n };\n}\n\n/**\n * Generates the server-side IDP seed script code.\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 // Rows may arrive as one chunk of a larger dataset; report row numbers\n // relative to the whole dataset so they match the source JSONL.\n const offset = typeof input.offset === \"number\" ? input.offset : 0;\n const total = typeof input.total === \"number\" ? input.total : input.users.length;\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] \\${offset + i + 1}/\\${total}: \\${input.users[i].name}\\`);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n errors.push(\\`Row \\${offset + i + 1} (\\${input.users[i].name}): \\${message}\\`);\n console.error(\\`[_User] Row \\${offset + i + 1} 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\nconst listIdpUsersFunction = ml /* ts */ `\n async function listUsers(client) {\n let after = undefined;\n const users = [];\n do {\n const response = await client.users(after ? { after } : undefined);\n for (const user of response.users || []) {\n users.push({ id: user.id, name: user.name });\n }\n after = response.nextPageToken;\n } while (after);\n console.log(\\`Found \\${users.length} IDP users to delete\\`);\n return users;\n }\n`;\n\n/**\n * Generates the server-side script that lists every IdP user for truncation.\n * @param idpNamespace - The IDP namespace name\n * @returns Script code string\n */\nexport function generateIdpListUsersScriptCode(idpNamespace: string): string {\n return ml /* ts */ `\n ${listIdpUsersFunction}\n\n export async function main() {\n const client = new tailor.idp.Client({ namespace: \"${idpNamespace}\" });\n const users = await listUsers(client);\n return { success: true, users };\n }\n `;\n}\n\n/**\n * Generates the server-side IDP truncation script code.\n * Deletes the users passed in `input.users` (one chunk of the listing produced by\n * {@link generateIdpListUsersScriptCode}), or every user when no chunk is passed so\n * older seed plugins that call it without input keep working. A user that is already\n * gone counts as deleted.\n * @param idpNamespace - The IDP namespace name\n * @returns Script code string\n */\nexport function generateIdpTruncateScriptCode(idpNamespace: string): string {\n return ml /* ts */ `\n ${listIdpUsersFunction}\n\n export async function main(input) {\n const client = new tailor.idp.Client({ namespace: \"${idpNamespace}\" });\n const errors = [];\n let deleted = 0;\n let notFound = 0;\n const users = Array.isArray(input.users) ? input.users : await listUsers(client);\n const offset = typeof input.offset === \"number\" ? input.offset : 0;\n const total = typeof input.total === \"number\" ? input.total : users.length;\n\n for (let i = 0; i < users.length; i++) {\n const user = users[i];\n try {\n await client.deleteUser(user.id);\n deleted++;\n console.log(\\`[_User] Deleted \\${offset + i + 1}/\\${total}: \\${user.name}\\`);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n if (/user not found/i.test(message)) {\n notFound++;\n console.log(\\`[_User] Already deleted \\${offset + i + 1}/\\${total}: \\${user.name}\\`);\n continue;\n }\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 notFound,\n total: users.length,\n errors,\n };\n }\n `;\n}\n\ntype GenerateIdpUserSchemaFileOptions = {\n usernameField: string;\n userTableName: string;\n /**\n * When `true` (default), emit a foreign key from `_User.name` to the\n * userProfile table'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.userTableName - TailorDB user table 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, userTableName, 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: \"${userTableName}\",\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 table)\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 { isPluginGeneratedTable } from \"#/parser/service/tailordb/type-source\";\nimport ml from \"#/utils/multiline\";\nimport type {\n ParsedField,\n PluginGeneratedTableSource,\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 tables to generate lines-db metadata\n * @param type - Parsed TailorDB table\n * @param source - Source file info\n * @returns Generated lines-db metadata\n */\nexport function processLinesDb(type: TailorDBType, source: TypeSourceInfoEntry): LinesDbMetadata {\n if (isPluginGeneratedTable(source)) {\n // Plugin-generated table\n return processLinesDbForPluginTable(type, source);\n }\n\n // User-defined table\n if (!source.filePath) {\n throw new Error(`Missing source info for table ${type.name}`);\n }\n if (!source.exportName) {\n throw new Error(`Missing export name for table ${type.name}`);\n }\n\n const { optionalFields, omitFields, indexes, foreignKeys } = extractFieldMetadata(type);\n\n return {\n tableName: 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 tables\n * @param type - Parsed TailorDB table\n * @param source - Plugin-generated table source info\n * @returns Generated lines-db metadata with plugin source\n */\nfunction processLinesDbForPluginTable(\n type: TailorDBType,\n source: PluginGeneratedTableSource,\n): LinesDbMetadata {\n const { optionalFields, omitFields, indexes, foreignKeys } = extractFieldMetadata(type);\n\n return {\n tableName: type.name,\n exportName: source.exportName,\n importPath: \"\",\n optionalFields,\n omitFields,\n foreignKeys,\n indexes,\n pluginSource: source,\n };\n}\n\n/**\n * Whether the platform produces a value for the field on create when a row omits it,\n * either from a create hook or from a schema default. Such fields stay optional in seed\n * data even when the table marks them required.\n * @param field - Parsed TailorDB field\n * @returns True when a seed row does not have to supply the field\n */\nfunction isGeneratedOnCreate(field: ParsedField): boolean {\n return field.config.hooks?.create !== undefined || field.config.default !== undefined;\n}\n\n/**\n * Extract field metadata from TailorDB table\n * @param type - Parsed TailorDB table\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 generated on create, or serial\n for (const [fieldName, field] of Object.entries(type.fields)) {\n if (isGeneratedOnCreate(field)) {\n optionalFields.push(fieldName);\n }\n // Serial fields are auto-generated, so they are excluded from the seed schema entirely\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 * Parameters for generating a user-defined table's schema file\n */\nexport interface UserTableSchemaParams {\n /** Relative import path to the table's source file */\n typeImportPath: string;\n /**\n * Relative path from the schema output to tailor.config.ts. Set when plugins are\n * attached to the table: the schema then loads the table through `getExtendedTable`\n * so the fields those plugins add are part of the seed schema.\n */\n configImportPath?: string;\n}\n\nfunction generateSchemaTypeCode(\n tableVariable: string,\n optionalFields: string[],\n omitFields: string[],\n): string {\n return ml /* ts */ `\n const schemaType = t.object({\n ...${tableVariable}.pickFields(${JSON.stringify(optionalFields)}, { optional: true }),\n ...${tableVariable}.omitFields(${JSON.stringify([...optionalFields, ...omitFields])}),\n });\n `;\n}\n\n/**\n * Generates the schema file content for lines-db (for user-defined tables with import)\n * @param metadata - lines-db metadata\n * @param params - Import paths for the table and, when plugins are attached, the config\n * @returns Schema file contents\n */\nexport function generateLinesDbSchemaFile(\n metadata: LinesDbMetadata,\n params: UserTableSchemaParams,\n): string {\n const { exportName, optionalFields, omitFields, foreignKeys, indexes } = metadata;\n const { typeImportPath, configImportPath } = params;\n\n const schemaOptionsCode = generateSchemaOptions(foreignKeys, indexes);\n\n if (configImportPath === undefined) {\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 \"${typeImportPath}\";\n\n ${generateSchemaTypeCode(exportName, optionalFields, omitFields)}\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 // The source file exports the table without the fields its plugins add, so the\n // schema is built from the table `getExtendedTable` returns instead.\n return ml /* ts */ `\n import { join } from \"node:path\";\n import { t } from \"@tailor-platform/sdk\";\n import { getExtendedTable } from \"@tailor-platform/sdk/plugin\";\n import { defineSchema } from \"@tailor-platform/sdk/seed\";\n import { createTailorDBHook, createStandardSchema } from \"@tailor-platform/sdk/test\";\n import { ${exportName} as sourceTable } from ${JSON.stringify(typeImportPath)};\n\n const configPath = join(import.meta.dirname, ${JSON.stringify(configImportPath)});\n const table = await getExtendedTable(configPath, sourceTable);\n\n ${generateSchemaTypeCode(\"table\", optionalFields, omitFields)}\n\n export const hook = createTailorDBHook(table);\n\n export const schema = defineSchema(\n createStandardSchema(schemaType, hook, table),${schemaOptionsCode}\n );\n\n `;\n}\n\n/**\n * Parameters for generating a plugin-generated table's 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 table file (for table-attached plugins) */\n originalImportPath?: string;\n}\n\n/**\n * Generates the schema file content using getGeneratedTable API\n * (for plugin-generated tables)\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 { tableName, exportName, optionalFields, omitFields, foreignKeys, indexes, pluginSource } =\n metadata;\n\n if (!pluginSource) {\n throw new Error(`pluginSource is required for plugin-generated table \"${tableName}\"`);\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 // Table-attached plugin (e.g., changeset): import the original table and use getGeneratedTable(configPath, pluginId, table, kind)\n if (pluginSource.originalExportName && originalImportPath && pluginSource.generatedTableKind) {\n return ml /* ts */ `\n import { join } from \"node:path\";\n import { t } from \"@tailor-platform/sdk\";\n import { getGeneratedTable } 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 getGeneratedTable(configPath, \"${pluginSource.pluginId}\", ${pluginSource.originalExportName}, \"${pluginSource.generatedTableKind}\");\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 getGeneratedTable(configPath, pluginId, null, kind)\n // For namespace plugins, generatedTableKind is required\n if (!pluginSource.generatedTableKind) {\n throw new Error(\n `Namespace plugin \"${pluginSource.pluginId}\" must provide generatedTableKind for table \"${tableName}\"`,\n );\n }\n\n return ml /* ts */ `\n import { join } from \"node:path\";\n import { t } from \"@tailor-platform/sdk\";\n import { getGeneratedTable } 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 getGeneratedTable(configPath, \"${pluginSource.pluginId}\", null, \"${pluginSource.generatedTableKind}\");\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\ndeclare module \"@tailor-platform/sdk/plugin\" {\n interface PluginConfigRegistry {\n \"@tailor-platform/seed\": SeedPluginOptions;\n }\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 [tableName, type] of Object.entries(ns.tables)) {\n const source = assertDefined(\n ns.sourceInfo.get(tableName),\n `source info missing for table: ${tableName}`,\n );\n const linesDb = processLinesDb(type, source);\n\n // Add reverse FK from userProfile table to _User (opt-out via disableIdpUserSync.userToIdp: true)\n if (\n idpUserSyncFKs.emitUserToIdpFK &&\n idpUser &&\n tableName === idpUser.schema.userTableName\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.tableName}.jsonl`),\n content: \"\",\n skipIfExists: true,\n });\n\n const schemaOutputPath = path.join(\n ctx.pluginConfig.distPath,\n \"data\",\n `${linesDb.tableName}.schema.ts`,\n );\n\n // Plugin-generated table: use getGeneratedTable 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 // A table with plugins attached may carry fields the source file does not\n // declare, so its schema loads the table through the config.\n const hasPlugins = (ns.pluginAttachments.get(tableName)?.length ?? 0) > 0;\n const configImportPath = hasPlugins\n ? path.relative(path.dirname(schemaOutputPath), ctx.configPath)\n : undefined;\n const schemaContent = generateLinesDbSchemaFile(linesDb, {\n typeImportPath,\n configImportPath,\n });\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 userTableName: idpUser.schema.userTableName,\n includeUserProfileFK: idpUserSyncFKs.emitIdpToUserFK,\n }),\n });\n }\n\n return { files };\n },\n };\n}\n"],"mappings":"yJAmBA,SAAgB,eAAe,EAAuD,CAEpF,GAAI,EAAK,YAAY,OAAS,cAAgB,CAAC,EAAK,YAClD,OAGF,GAAM,CAAE,YAAW,iBAAkB,EAAK,YAE1C,MAAO,CACL,KAAM,QACN,aAAc,CAAC,CAAS,EACxB,SAAU,mBACV,aAAc,EAAK,WAAW,UAC9B,OAAQ,CACN,gBACA,cAAe,CACjB,CACF,CACF,CAQA,SAAgB,0BAA0B,EAA8B,CACtE,MAAO,EAAY;;2DAEsC,EAAa;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkExE,CAEA,MAAM,EAAuB,CAAY;;;;;;;;;;;;;;EAqBzC,SAAgB,+BAA+B,EAA8B,CAC3E,MAAO,EAAY;MACf,EAAqB;;;2DAGgC,EAAa;;;;GAKxE,CAWA,SAAgB,8BAA8B,EAA8B,CAC1E,MAAO,EAAY;MACf,EAAqB;;;2DAGgC,EAAa;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCxE,CAyBA,SAAgB,0BAA0B,EAAmD,CAC3F,GAAM,CAAE,gBAAe,gBAAe,uBAAuB,IAAS,EAChE,EAAa,EACf,CAAE;;;;;;;;;sBASc,EAAc;uBACb,EAAc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AM,EAE5E,EAAM,KAAK,CACT,KAAM,EACN,QAAS,CACX,CAAC,CACH,KAAO,CAEL,IAAM,EAAe,EAAK,SAAS,EAAK,QAAQ,CAAgB,EAAG,EAAQ,UAAU,EAU/E,EAAgB,0BAA0B,EAAS,CACvD,eAVqB,EAAa,QAAQ,QAAS,EAAE,CAAC,CAAC,WAAW,GAAG,EACnE,EAAa,QAAQ,QAAS,EAAE,EAChC,KAAK,EAAa,QAAQ,QAAS,EAAE,IASvC,kBANkB,EAAG,kBAAkB,IAAI,CAAS,CAAC,EAAE,QAAU,GAAK,EAEpE,EAAK,SAAS,EAAK,QAAQ,CAAgB,EAAG,EAAI,UAAU,EAC5D,IAAA,EAIJ,CAAC,EAED,EAAM,KAAK,CACT,KAAM,EACN,QAAS,CACX,CAAC,CACH,CACF,CAsBF,OAnBI,IAEF,EAAM,KAAK,CACT,KAAM,EAAK,KAAK,EAAI,aAAa,SAAU,EAAQ,QAAQ,EAC3D,QAAS,GACT,aAAc,EAChB,CAAC,EAGD,EAAM,KAAK,CACT,KAAM,EAAK,KAAK,EAAI,aAAa,SAAU,OAAQ,GAAG,EAAQ,KAAK,WAAW,EAC9E,QAAS,0BAA0B,CACjC,cAAe,EAAQ,OAAO,cAC9B,cAAe,EAAQ,OAAO,cAC9B,qBAAsB,EAAe,eACvC,CAAC,CACH,CAAC,GAGI,CAAE,OAAM,CACjB,CACF,CACF"}
|
|
1
|
+
{"version":3,"file":"seed-C3P_T_Eh.mjs","names":["assertDefined","isPluginGeneratedTable","path","auth","tableName","idpNamespace","listIdpUsersFunction","options","schemaBody","includeUserProfileFK","userTableName","usernameField","source","type","field","optionalFields","omitFields","indexes","foreignKeys","fieldName","indexName","indexDef","schemaOptions","fk","index","option","tableVariable","metadata","params","schemaOptionsCode","configImportPath","exportName","typeImportPath","pluginSource","schemaTypeCode","originalImportPath","SeedGeneratorID","files","idpUser","ctx","idpUserSyncFKs","ns","linesDb","schemaOutputPath","relativePath","schemaContent"],"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 userTableName: 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 { tableName, usernameField } = auth.userProfile;\n\n return {\n name: \"_User\",\n dependencies: [tableName],\n dataFile: \"data/_User.jsonl\",\n idpNamespace: auth.idProvider.namespace,\n schema: {\n usernameField,\n userTableName: tableName,\n },\n };\n}\n\n/**\n * Generates the server-side IDP seed script code.\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 // Rows may arrive as one chunk of a larger dataset; report row numbers\n // relative to the whole dataset so they match the source JSONL.\n const offset = typeof input.offset === \"number\" ? input.offset : 0;\n const total = typeof input.total === \"number\" ? input.total : input.users.length;\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] \\${offset + i + 1}/\\${total}: \\${input.users[i].name}\\`);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n errors.push(\\`Row \\${offset + i + 1} (\\${input.users[i].name}): \\${message}\\`);\n console.error(\\`[_User] Row \\${offset + i + 1} 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\nconst listIdpUsersFunction = ml /* ts */ `\n async function listUsers(client) {\n let after = undefined;\n const users = [];\n do {\n const response = await client.users(after ? { after } : undefined);\n for (const user of response.users || []) {\n users.push({ id: user.id, name: user.name });\n }\n after = response.nextPageToken;\n } while (after);\n console.log(\\`Found \\${users.length} IDP users to delete\\`);\n return users;\n }\n`;\n\n/**\n * Generates the server-side script that lists every IdP user for truncation.\n * @param idpNamespace - The IDP namespace name\n * @returns Script code string\n */\nexport function generateIdpListUsersScriptCode(idpNamespace: string): string {\n return ml /* ts */ `\n ${listIdpUsersFunction}\n\n export async function main() {\n const client = new tailor.idp.Client({ namespace: \"${idpNamespace}\" });\n const users = await listUsers(client);\n return { success: true, users };\n }\n `;\n}\n\n/**\n * Generates the server-side IDP truncation script code.\n * Deletes the users passed in `input.users` (one chunk of the listing produced by\n * {@link generateIdpListUsersScriptCode}), or every user when no chunk is passed so\n * older seed plugins that call it without input keep working. A user that is already\n * gone counts as deleted.\n * @param idpNamespace - The IDP namespace name\n * @returns Script code string\n */\nexport function generateIdpTruncateScriptCode(idpNamespace: string): string {\n return ml /* ts */ `\n ${listIdpUsersFunction}\n\n export async function main(input) {\n const client = new tailor.idp.Client({ namespace: \"${idpNamespace}\" });\n const errors = [];\n let deleted = 0;\n let notFound = 0;\n const users = Array.isArray(input.users) ? input.users : await listUsers(client);\n const offset = typeof input.offset === \"number\" ? input.offset : 0;\n const total = typeof input.total === \"number\" ? input.total : users.length;\n\n for (let i = 0; i < users.length; i++) {\n const user = users[i];\n try {\n await client.deleteUser(user.id);\n deleted++;\n console.log(\\`[_User] Deleted \\${offset + i + 1}/\\${total}: \\${user.name}\\`);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n if (/user not found/i.test(message)) {\n notFound++;\n console.log(\\`[_User] Already deleted \\${offset + i + 1}/\\${total}: \\${user.name}\\`);\n continue;\n }\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 notFound,\n total: users.length,\n errors,\n };\n }\n `;\n}\n\ntype GenerateIdpUserSchemaFileOptions = {\n usernameField: string;\n userTableName: string;\n /**\n * When `true` (default), emit a foreign key from `_User.name` to the\n * userProfile table'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.userTableName - TailorDB user table 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, userTableName, 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: \"${userTableName}\",\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 table)\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 { isPluginGeneratedTable } from \"#/parser/service/tailordb/type-source\";\nimport ml from \"#/utils/multiline\";\nimport type {\n ParsedField,\n PluginGeneratedTableSource,\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 tables to generate lines-db metadata\n * @param type - Parsed TailorDB table\n * @param source - Source file info\n * @returns Generated lines-db metadata\n */\nexport function processLinesDb(type: TailorDBType, source: TypeSourceInfoEntry): LinesDbMetadata {\n if (isPluginGeneratedTable(source)) {\n // Plugin-generated table\n return processLinesDbForPluginTable(type, source);\n }\n\n // User-defined table\n if (!source.filePath) {\n throw new Error(`Missing source info for table ${type.name}`);\n }\n if (!source.exportName) {\n throw new Error(`Missing export name for table ${type.name}`);\n }\n\n const { optionalFields, omitFields, indexes, foreignKeys } = extractFieldMetadata(type);\n\n return {\n tableName: 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 tables\n * @param type - Parsed TailorDB table\n * @param source - Plugin-generated table source info\n * @returns Generated lines-db metadata with plugin source\n */\nfunction processLinesDbForPluginTable(\n type: TailorDBType,\n source: PluginGeneratedTableSource,\n): LinesDbMetadata {\n const { optionalFields, omitFields, indexes, foreignKeys } = extractFieldMetadata(type);\n\n return {\n tableName: type.name,\n exportName: source.exportName,\n importPath: \"\",\n optionalFields,\n omitFields,\n foreignKeys,\n indexes,\n pluginSource: source,\n };\n}\n\n/**\n * Whether the platform produces a value for the field on create when a row omits it,\n * either from a create hook or from a schema default. Such fields stay optional in seed\n * data even when the table marks them required.\n * @param field - Parsed TailorDB field\n * @returns True when a seed row does not have to supply the field\n */\nfunction isGeneratedOnCreate(field: ParsedField): boolean {\n return field.config.hooks?.create !== undefined || field.config.default !== undefined;\n}\n\n/**\n * Extract field metadata from TailorDB table\n * @param type - Parsed TailorDB table\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 generated on create, or serial\n for (const [fieldName, field] of Object.entries(type.fields)) {\n if (isGeneratedOnCreate(field)) {\n optionalFields.push(fieldName);\n }\n // Serial fields are auto-generated, so they are excluded from the seed schema entirely\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 * Parameters for generating a user-defined table's schema file\n */\nexport interface UserTableSchemaParams {\n /** Relative import path to the table's source file */\n typeImportPath: string;\n /**\n * Relative path from the schema output to tailor.config.ts. Set when plugins are\n * attached to the table: the schema then loads the table through `getExtendedTable`\n * so the fields those plugins add are part of the seed schema.\n */\n configImportPath?: string;\n}\n\nfunction generateSchemaTypeCode(\n tableVariable: string,\n optionalFields: string[],\n omitFields: string[],\n): string {\n return ml /* ts */ `\n const schemaType = t.object({\n ...${tableVariable}.pickFields(${JSON.stringify(optionalFields)}, { optional: true }),\n ...${tableVariable}.omitFields(${JSON.stringify([...optionalFields, ...omitFields])}),\n });\n `;\n}\n\n/**\n * Generates the schema file content for lines-db (for user-defined tables with import)\n * @param metadata - lines-db metadata\n * @param params - Import paths for the table and, when plugins are attached, the config\n * @returns Schema file contents\n */\nexport function generateLinesDbSchemaFile(\n metadata: LinesDbMetadata,\n params: UserTableSchemaParams,\n): string {\n const { exportName, optionalFields, omitFields, foreignKeys, indexes } = metadata;\n const { typeImportPath, configImportPath } = params;\n\n const schemaOptionsCode = generateSchemaOptions(foreignKeys, indexes);\n\n if (configImportPath === undefined) {\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 \"${typeImportPath}\";\n\n ${generateSchemaTypeCode(exportName, optionalFields, omitFields)}\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 // The source file exports the table without the fields its plugins add, so the\n // schema is built from the table `getExtendedTable` returns instead.\n return ml /* ts */ `\n import { join } from \"node:path\";\n import { t } from \"@tailor-platform/sdk\";\n import { getExtendedTable } from \"@tailor-platform/sdk/plugin\";\n import { defineSchema } from \"@tailor-platform/sdk/seed\";\n import { createTailorDBHook, createStandardSchema } from \"@tailor-platform/sdk/test\";\n import { ${exportName} as sourceTable } from ${JSON.stringify(typeImportPath)};\n\n const configPath = join(import.meta.dirname, ${JSON.stringify(configImportPath)});\n const table = await getExtendedTable(configPath, sourceTable);\n\n ${generateSchemaTypeCode(\"table\", optionalFields, omitFields)}\n\n export const hook = createTailorDBHook(table);\n\n export const schema = defineSchema(\n createStandardSchema(schemaType, hook, table),${schemaOptionsCode}\n );\n\n `;\n}\n\n/**\n * Parameters for generating a plugin-generated table's 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 table file (for table-attached plugins) */\n originalImportPath?: string;\n}\n\n/**\n * Generates the schema file content using getGeneratedTable API\n * (for plugin-generated tables)\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 { tableName, exportName, optionalFields, omitFields, foreignKeys, indexes, pluginSource } =\n metadata;\n\n if (!pluginSource) {\n throw new Error(`pluginSource is required for plugin-generated table \"${tableName}\"`);\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 // Table-attached plugin (e.g., changeset): import the original table and use getGeneratedTable(configPath, pluginId, table, kind)\n if (pluginSource.originalExportName && originalImportPath && pluginSource.generatedTableKind) {\n return ml /* ts */ `\n import { join } from \"node:path\";\n import { t } from \"@tailor-platform/sdk\";\n import { getGeneratedTable } 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 getGeneratedTable(configPath, \"${pluginSource.pluginId}\", ${pluginSource.originalExportName}, \"${pluginSource.generatedTableKind}\");\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 getGeneratedTable(configPath, pluginId, null, kind)\n // For namespace plugins, generatedTableKind is required\n if (!pluginSource.generatedTableKind) {\n throw new Error(\n `Namespace plugin \"${pluginSource.pluginId}\" must provide generatedTableKind for table \"${tableName}\"`,\n );\n }\n\n return ml /* ts */ `\n import { join } from \"node:path\";\n import { t } from \"@tailor-platform/sdk\";\n import { getGeneratedTable } 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 getGeneratedTable(configPath, \"${pluginSource.pluginId}\", null, \"${pluginSource.generatedTableKind}\");\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\ndeclare module \"@tailor-platform/sdk/plugin\" {\n interface PluginConfigRegistry {\n \"@tailor-platform/seed\": SeedPluginOptions;\n }\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 [tableName, type] of Object.entries(ns.tables)) {\n const source = assertDefined(\n ns.sourceInfo.get(tableName),\n `source info missing for table: ${tableName}`,\n );\n const linesDb = processLinesDb(type, source);\n\n // Add reverse FK from userProfile table to _User (opt-out via disableIdpUserSync.userToIdp: true)\n if (\n idpUserSyncFKs.emitUserToIdpFK &&\n idpUser &&\n tableName === idpUser.schema.userTableName\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.tableName}.jsonl`),\n content: \"\",\n skipIfExists: true,\n });\n\n const schemaOutputPath = path.join(\n ctx.pluginConfig.distPath,\n \"data\",\n `${linesDb.tableName}.schema.ts`,\n );\n\n // Plugin-generated table: use getGeneratedTable 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 // A table with plugins attached may carry fields the source file does not\n // declare, so its schema loads the table through the config.\n const hasPlugins = (ns.pluginAttachments.get(tableName)?.length ?? 0) > 0;\n const configImportPath = hasPlugins\n ? path.relative(path.dirname(schemaOutputPath), ctx.configPath)\n : undefined;\n const schemaContent = generateLinesDbSchemaFile(linesDb, {\n typeImportPath,\n configImportPath,\n });\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 userTableName: idpUser.schema.userTableName,\n includeUserProfileFK: idpUserSyncFKs.emitIdpToUserFK,\n }),\n });\n }\n\n return { files };\n },\n };\n}\n"],"mappings":"yJAmBA,SAAgB,eAAe,EAAuD,CAEpF,GAAIG,EAAK,YAAY,OAAS,cAAgB,CAACA,EAAK,YAClD,OAGF,GAAM,CAAE,YAAW,iBAAkBA,EAAK,YAE1C,MAAO,CACL,KAAM,QACN,aAAc,CAACC,CAAS,EACxB,SAAU,mBACV,aAAcD,EAAK,WAAW,UAC9B,OAAQ,CACN,gBACA,cAAeC,CACjB,CACF,CACF,CAQA,SAAgB,0BAA0B,EAA8B,CACtE,MAAO,EAAY;;2DAEsCC,EAAa;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkExE,CAEA,MAAMC,EAAuB,CAAY;;;;;;;;;;;;;;EAqBzC,SAAgB,+BAA+B,EAA8B,CAC3E,MAAO,EAAY;MACfA,EAAqB;;;2DAGgCD,EAAa;;;;GAKxE,CAWA,SAAgB,8BAA8B,EAA8B,CAC1E,MAAO,EAAY;MACfC,EAAqB;;;2DAGgCD,EAAa;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCxE,CAyBA,SAAgB,0BAA0B,EAAmD,CAC3F,GAAM,CAAE,gBAAe,gBAAe,uBAAuB,IAASE,EAChEC,EAAaC,EACf,CAAE;;;;;;;;;sBAScC,EAAc;uBACbC,EAAc;;;;MAK/B,CAAE;;;;;MAON,MAAO,EAAY;;;;;;;;;;;;;;;;UAgBXH,EAAW;;;;KAKrB,CC5PA,SAAgB,eAAe,EAAoB,EAA8C,CAC/F,GAAIP,EAAuBW,CAAM,EAE/B,OAAO,6BAA6BC,EAAMD,CAAM,EAIlD,GAAI,CAACA,EAAO,SACV,MAAU,MAAM,iCAAiCC,EAAK,MAAM,EAE9D,GAAI,CAACD,EAAO,WACV,MAAU,MAAM,iCAAiCC,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KAAO,CAEL,IAAMD,EAAe1C,EAAK,SAASA,EAAK,QAAQyC,CAAgB,EAAGD,EAAQ,UAAU,EAU/EG,EAAgB,0BAA0BH,EAAS,CACvD,eAVqBE,EAAa,QAAQ,QAAS,EAAE,CAAC,CAAC,WAAW,GAAG,EACnEA,EAAa,QAAQ,QAAS,EAAE,EAChC,KAAKA,EAAa,QAAQ,QAAS,EAAE,IASvC,kBANkBH,EAAG,kBAAkB,IAAIrC,CAAS,CAAC,EAAE,QAAU,GAAK,EAEpEF,EAAK,SAASA,EAAK,QAAQyC,CAAgB,EAAGJ,EAAI,UAAU,EAC5D,IAAA,EAIJ,CAAC,EAEDF,EAAM,KAAK,CACT,KAAMM,EACN,QAASE,CACX,CAAC,CACH,CACF,CAsBF,OAnBIP,IAEFD,EAAM,KAAK,CACT,KAAMnC,EAAK,KAAKqC,EAAI,aAAa,SAAUD,EAAQ,QAAQ,EAC3D,QAAS,GACT,aAAc,EAChB,CAAC,EAGDD,EAAM,KAAK,CACT,KAAMnC,EAAK,KAAKqC,EAAI,aAAa,SAAU,OAAQ,GAAGD,EAAQ,KAAK,WAAW,EAC9E,QAAS,0BAA0B,CACjC,cAAeA,EAAQ,OAAO,cAC9B,cAAeA,EAAQ,OAAO,cAC9B,qBAAsBE,EAAe,eACvC,CAAC,CACH,CAAC,GAGI,CAAE,OAAM,CACjB,CACF,CACF"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{t as e}from"./service-CL1Bp4It.mjs";export{e as createExecutorService};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{n as e}from"./brand-C8nMKhJC.mjs";import{i as t,n}from"./logger-
|
|
1
|
+
import{n as e}from"./brand-C8nMKhJC.mjs";import{i as t,o as n}from"./logger-Db-YRTwK.mjs";import*as r from"pathe";import{z as i}from"zod";import*as a from"node:fs";import{pathToFileURL as o}from"node:url";const s=i.custom(e=>typeof e==`function`),c=`tailorImportNonce`;let l=0;function beginUserModuleRun(){l+=1}function currentImportNonce(){return l===0?void 0:String(l)}function importUserModule(e){let t=o(e),n=currentImportNonce();return n&&t.searchParams.set(c,n),import(t.href)}const ee=[`**/*.test.ts`,`**/*.spec.ts`],u=/* @__PURE__ */ new Set;function loadFilesWithIgnores(e,n){if(e.files.length===0)return[];let i=resolveFiles(e,n),a=e.files.every(e=>r.isAbsolute(e));if(i.matchedAnyPattern||n===process.cwd()||a)return i.files;let o=`${n}\0${e.files.join(`\0`)}`;return u.has(o)||(u.add(o),t.warn(`No files matched "${e.files.join(`, `)}" relative to "${n}"; falling back to process.cwd(). Update this config's file patterns to be relative to its own directory before v2, when this fallback will be removed.`)),resolveFiles(e,process.cwd()).files}function resolveFiles(e,n){let i=e.ignores===void 0,o=e.ignores??ee,s=i?o:o.map(e=>r.resolve(n,e)),c=[],l=!1;for(let i of e.files){let e=r.resolve(n,i);try{let t=a.globSync(e);t.length>0&&(l=!0);let n=t.filter(e=>!s.some(t=>r.matchesGlob(e,t)));c.push(...n)}catch(e){l=!0,t.warn(`Failed to glob pattern "${i}": ${String(e)}`)}}return{files:c,matchedAnyPattern:l}}const d=Object.keys({uuid:!0,string:!0,boolean:!0,integer:!0,float:!0,decimal:!0,enum:!0,date:!0,datetime:!0,time:!0,nested:!0}),f=i.enum(d),p={"1-1":`1-1`,oneToOne:`1-1`,"n-1":`n-1`,manyToOne:`n-1`,"N-1":`n-1`,keyOnly:`keyOnly`},m=Object.keys(p);function fieldRef(e){return`Field "${e.fieldName}" on table "${e.tableName}"`}function validateRelationConfig(e,t){if(!e.type)throw Error(`${fieldRef(t)} has a relation but is missing the required 'type' property. Valid values: ${m.join(`, `)}.`);if(!(e.type in p))throw Error(`${fieldRef(t)} has invalid relation type '${e.type}'. Valid values: ${m.join(`, `)}.`);if(e.toward.table!==`self`&&!t.allTableNames.has(e.toward.table))throw Error(`${fieldRef(t)} references unknown table "${e.toward.table}".`)}function processRelationMetadata(e,t,n=!1){let r=p[e.type]===`1-1`,i=e.toward.key??`id`,a=e.toward.table===`self`?t.tableName:e.toward.table,o=!n,s=!n&&r;return{index:o,foreignKey:!0,relationType:e.type,unique:s,foreignKeyType:a,foreignKeyField:i}}function buildRelationInfo(e,t){if(e.type===`keyOnly`)return;let n=p[e.type]===`1-1`,r=e.toward.key??`id`,i=e.toward.table===`self`?t.tableName:e.toward.table,a=e.toward.as;return a||=t.fieldName.replace(/(ID|Id|id)$/u,``),{targetType:i,forwardName:a,backwardName:e.backward??``,key:r,unique:n}}function applyRelationMetadataToFieldConfig(e,t){return{...e,index:t.index,foreignKey:t.foreignKey,unique:t.unique,foreignKeyType:t.foreignKeyType,foreignKeyField:t.foreignKeyField}}function normalizeGqlOperations(e){return e===`query`?{create:!1,update:!1,delete:!1,read:!0}:e}const h=i.union([i.literal(`query`),i.strictObject({create:i.boolean().optional().describe(`Enable create mutation (default: true)`),update:i.boolean().optional().describe(`Enable update mutation (default: true)`),delete:i.boolean().optional().describe(`Enable delete mutation (default: true)`),read:i.boolean().optional().describe(`Enable read queries - get, list, aggregation (default: true)`)})]).describe(`Configuration for GraphQL operations on a TailorDB table.
|
|
2
2
|
All operations are enabled by default (undefined or true = enabled, false = disabled).`).transform(e=>normalizeGqlOperations(e)),g=i.strictObject({value:i.string(),description:i.string().optional()}),_=i.strictObject({required:i.boolean().optional().describe(`Whether the field is required`),array:i.boolean().optional().describe(`Whether the field is an array`),description:i.string().optional().describe(`Field description`),typeName:i.string().optional().describe(`Type name for nested or enum fields`),allowedValues:i.array(g).optional().describe(`Allowed values for enum fields`),index:i.boolean().optional().describe(`Whether the field is indexed for faster queries`),unique:i.boolean().optional().describe(`Whether the field value must be unique`),vector:i.boolean().optional().describe(`Whether the field is a vector field for similarity search`),foreignKey:i.boolean().optional().describe(`Whether the field is a foreign key`),foreignKeyType:i.string().optional().describe(`Target table name for foreign key relations`),foreignKeyField:i.string().optional().describe(`Target field name for foreign key relations`),hooks:i.strictObject({create:s.optional().describe(`Hook function called on record creation`),update:s.optional().describe(`Hook function called on record update`)}).optional().describe(`Lifecycle hooks for the field`),validate:i.array(s).optional().describe(`Validation functions for the field`),serial:i.strictObject({start:i.number().describe(`Starting value for the serial sequence`),maxValue:i.number().optional().describe(`Maximum value for the serial sequence`),format:i.string().optional().describe(`Format string for serial value (string type only)`)}).optional().describe(`Serial (auto-increment) configuration`),scale:i.number().int().min(0).max(12).optional().describe(`Decimal scale (number of digits after decimal point, 0-12)`),default:i.unknown().optional().describe(`Default value for the field on create`)}),te=i.enum(m),ne=i.strictObject({type:te.describe(`Relation cardinality type`),toward:i.strictObject({table:i.string().describe(`Target table name, or 'self' for self-relations`),as:i.string().optional().describe(`Custom forward relation name`),key:i.string().optional().describe(`Target field to join on (default: 'id')`)}),backward:i.string().optional().describe(`Backward relation name on the target table`)}),v=i.lazy(()=>i.object({type:f,fields:i.record(i.string(),v).optional(),metadata:_,rawRelation:ne.optional()})),y=i.strictObject({pluralForm:i.string().optional().describe(`Custom plural form of the table name for GraphQL`),aggregation:i.boolean().optional().describe(`Enable aggregation queries for this table`),bulkUpsert:i.boolean().optional().describe(`Enable bulk upsert mutation for this table`),gqlOperations:h.optional().describe(`Configure GraphQL operations for this table. Use "query" for read-only mode, or an object for granular control.`),publishEvents:i.boolean().optional().describe(`Enable publishing events for this table.
|
|
3
3
|
When enabled, record creation/update/deletion events are published.
|
|
4
4
|
If not specified, this is automatically set to true when an executor uses this table
|
|
5
5
|
with recordCreated/recordUpdated/recordDeleted triggers. If explicitly set to false
|
|
6
|
-
while an executor uses this table, an error will be thrown during apply.`)}),b=i.union([i.strictObject({user:i.string()}),i.string(),i.boolean(),i.array(i.string()),i.array(i.boolean())],{error:e=>{if(typeof e.input==`object`&&e.input!==null){let t=Object.keys(e.input);return t.length===1?`"${t[0]}" operand is not supported in gqlPermission. Use permission() for record-level conditions.`:`Operand object must have exactly 1 key`}return`Invalid operand in gqlPermission`}}),x=i.union([b,i.strictObject({record:i.string()}),i.strictObject({oldRecord:i.string()}),i.strictObject({newRecord:i.string()})]),S=i.enum([`=`,`!=`,`in`,`not in`,`hasAny`,`not hasAny`]),C=i.tuple([x,S,x]).readonly(),re=i.tuple([b,S,b]).readonly(),w=i.union([i.strictObject({conditions:i.union([C,i.array(C).readonly()]),description:i.string().optional(),permit:i.boolean().optional()}),i.tuple([x,S,x]).readonly(),i.tuple([x,S,x,i.boolean()]).readonly(),i.array(i.union([C,i.boolean()])).refine(e=>{let t=e.findIndex(e=>typeof e==`boolean`);return t===-1||t===e.length-1},{message:`Boolean permit flag must only appear at the end`}).readonly()]),ie=i.enum([`read`,`create`,`update`,`delete`,`aggregate`,`bulkUpsert`]),ae=i.strictObject({conditions:i.array(re).readonly(),actions:i.union([i.literal(`all`),i.array(ie).readonly()]),permit:i.boolean().optional(),description:i.string().optional()}),oe=i.strictObject({record:i.strictObject({create:i.array(w).readonly(),read:i.array(w).readonly(),update:i.array(w).readonly(),delete:i.array(w).readonly()}).optional(),gql:i.array(ae).readonly().optional()}),T=i.strictObject({name:i.string(),fields:i.record(i.string(),v),metadata:i.object({name:i.string(),description:i.string().optional(),settings:y.optional(),permissions:oe,files:i.record(i.string(),i.string()),indexes:i.record(i.string(),i.strictObject({fields:i.array(i.string()),unique:i.boolean().optional()})).optional(),typeHook:i.strictObject({create:s.optional(),update:s.optional()}).optional(),typeValidate:s.optional()}).strict()}),E=i.strictObject({directory:i.string().describe(`Directory containing migration files`),machineUser:i.string().optional().describe(`Machine user name for migration execution`)}),D=i.strictObject({files:i.array(i.string()).describe(`Glob patterns for TailorDB table definition files`),ignores:i.array(i.string()).optional().describe(`Glob patterns to exclude from table discovery`),migration:E.optional().describe(`Migration configuration`),gqlOperations:h.optional().describe(`Default GraphQL operations for all tables in this service`)}),O=T.keyof().options;function stripTailorDBTypeBuilderHelpers(t){return e(t,`tailordb-type`)?pickTailorDBTypeSchemaKeys(t):t}function pickTailorDBTypeSchemaKeys(e){if(typeof e!=`object`||!e)return e;let t={},n=e;for(let e of O)Object.prototype.hasOwnProperty.call(n,e)&&(t[e]=n[e]);return t}const k=i.strictObject({providerUrl:i.string().describe(`OAuth2 provider URL`),issuerUrl:i.string().describe(`OAuth2 issuer URL`),clientId:i.string().describe(`OAuth2 client ID`),clientSecret:i.string().describe(`OAuth2 client secret`),authUrl:i.string().optional().describe(`OAuth2 authorization endpoint override`),tokenUrl:i.string().optional().describe(`OAuth2 token endpoint override`)}).extend({type:i.literal(`oauth2`).describe(`Connection type`)}),A=i.strictObject({value:i.string().describe(`The allowed value`),description:i.string().optional().describe(`Description of the allowed value`)}),j=i.strictObject({as:i.enum([`string`,`date`,`temporal`]).optional().describe(`Date value representation`),required:i.boolean().optional().describe(`Whether the field is required`),array:i.boolean().optional().describe(`Whether the field is an array`),description:i.string().optional().describe(`Field description`),allowedValues:i.array(A).optional().describe(`Allowed values for enum fields`),hooks:i.strictObject({create:s.optional().describe(`Hook function called on creation`),update:s.optional().describe(`Hook function called on update`)}).optional().describe(`Lifecycle hooks`),validate:i.array(s).optional().describe(`Validation functions for the field`),typeName:i.string().optional().describe(`Type name for nested or enum fields`),default:i.unknown().optional().describe(`Default value for the field on create`)}),M=i.object({type:f.describe(`Field data type`),metadata:j.describe(`Field metadata configuration`),get fields(){return i.record(i.string(),M)}}),N=i.strictObject({namespace:i.string().describe(`Auth namespace`),machineUserName:i.string().describe(`Machine user name for authentication`)}),P=i.union([i.string().describe(`Machine user name (namespace auto-resolved from auth service)`),N]),F=i.strictObject({vaultName:i.string().describe(`Vault name containing the secret`),secretKey:i.string().describe(`Key of the secret in the vault`)}),I=i.strictObject({name:i.string().describe(`Identity provider name`),kind:i.literal(`OIDC`),clientID:i.string().describe(`OAuth2 client ID`),clientSecret:F.describe(`OAuth2 client secret`),providerURL:i.string().describe(`OIDC provider URL`),issuerURL:i.string().optional().describe(`OIDC issuer URL (defaults to providerURL)`),usernameClaim:i.string().optional().describe(`JWT claim to use as username`)}),L=i.strictObject({name:i.string().describe(`Identity provider name`),kind:i.literal(`SAML`),enableSignRequest:i.boolean().default(!1).describe(`Enable signing of SAML requests`),metadataURL:i.string().optional().describe(`URL to fetch SAML metadata (mutually exclusive with rawMetadata)`),rawMetadata:i.string().optional().describe(`Raw SAML metadata XML (mutually exclusive with metadataURL)`),defaultRedirectURL:i.string().optional().describe(`URL to redirect to when SAML ACS receives a response with an empty RelayState.`)}).refine(e=>e.metadataURL!==void 0!=(e.rawMetadata!==void 0),`Provide either metadataURL or rawMetadata`),R=i.strictObject({name:i.string().describe(`Identity provider name`),kind:i.literal(`IDToken`),providerURL:i.string().describe(`ID token provider URL`),issuerURL:i.string().optional().describe(`ID token issuer URL`),clientID:i.string().describe(`Client ID for ID token validation`),usernameClaim:i.string().optional().describe(`JWT claim to use as username`)}),z=i.strictObject({name:i.string().describe(`Identity provider name`),kind:i.literal(`BuiltInIdP`),namespace:i.string().describe(`IdP namespace`),clientName:i.string().describe(`OAuth2 client name in the IdP`)}),B=i.discriminatedUnion(`kind`,[I,L,R,z]),V=i.union([i.literal(`authorization_code`),i.literal(`refresh_token`)]).describe(`OAuth2 grant type`),H=i.strictObject({description:i.string().optional().describe(`Client description`),grantTypes:i.array(V).default([`authorization_code`,`refresh_token`]).describe(`Allowed OAuth2 grant types`),redirectURIs:i.array(i.union([i.templateLiteral([`https://`,i.string()]),i.templateLiteral([`http://`,i.string()]),i.templateLiteral([i.string(),`:url`]),i.templateLiteral([i.string(),`:url/`,i.string()])])).describe(`Allowed redirect URIs`),clientType:i.union([i.literal(`confidential`),i.literal(`public`),i.literal(`browser`)]).optional().describe(`OAuth2 client type`),accessTokenLifetimeSeconds:i.number().int().min(60,`Minimum access token lifetime is 60 seconds`).max(86400,`Maximum access token lifetime is 1 day (86400 seconds)`).optional().describe(`Access token lifetime in seconds (60-86400)`).transform(e=>e?{seconds:BigInt(e),nanos:0}:void 0),refreshTokenLifetimeSeconds:i.number().int().min(60,`Minimum refresh token lifetime is 60 seconds`).max(604800,`Maximum refresh token lifetime is 7 days (604800 seconds)`).optional().describe(`Refresh token lifetime in seconds (60-604800)`).transform(e=>e?{seconds:BigInt(e),nanos:0}:void 0),requireDpop:i.boolean().optional().describe(`Require DPoP (Demonstrating Proof-of-Possession) for token requests`)}).refine(e=>e.clientType!==`browser`||e.requireDpop!==!0,{message:`requireDpop cannot be set to true for browser clients as they don't support DPoP`,path:[`requireDpop`]}),U=i.strictObject({type:i.union([i.literal(`oauth2`),i.literal(`bearer`)]).describe(`SCIM authorization type`),bearerSecret:F.optional().describe(`Bearer token secret (required for bearer type)`)}),W=i.union([i.literal(`string`),i.literal(`number`),i.literal(`boolean`),i.literal(`datetime`),i.literal(`complex`)]).describe(`SCIM attribute data type`),G=i.strictObject({type:W.describe(`Attribute data type`),name:i.string().describe(`Attribute name`),description:i.string().optional().describe(`Attribute description`),mutability:i.union([i.literal(`readOnly`),i.literal(`readWrite`),i.literal(`writeOnly`)]).optional().describe(`Attribute mutability`),required:i.boolean().optional().describe(`Whether the attribute is required`),multiValued:i.boolean().optional().describe(`Whether the attribute can have multiple values`),uniqueness:i.union([i.literal(`none`),i.literal(`server`),i.literal(`global`)]).optional().describe(`Uniqueness constraint`),canonicalValues:i.array(i.string()).nullable().optional().describe(`List of canonical values`),get subAttributes(){return i.array(G).nullable().optional()}}),K=i.strictObject({name:i.string().describe(`SCIM schema name`),attributes:i.array(G).describe(`Schema attributes`)}),q=i.strictObject({tailorDBField:i.string().describe(`TailorDB field name to map to`),scimPath:i.string().describe(`SCIM attribute path`)}),se=i.strictObject({name:i.string().describe(`SCIM resource name`),tailorDBNamespace:i.string().describe(`TailorDB namespace for the resource`),tailorDBType:i.string().describe(`TailorDB table name for the resource`),coreSchema:K.describe(`Core SCIM schema definition`),attributeMapping:i.array(q).describe(`Attribute mapping configuration`)}),ce=i.strictObject({machineUserName:i.string().describe(`Machine user name for SCIM operations`),authorization:U.describe(`SCIM authorization configuration`),resources:i.array(se).describe(`SCIM resource definitions`)}),le=i.strictObject({namespace:i.string().describe(`TailorDB namespace for the tenant table`),type:i.string().describe(`TailorDB table name for tenants`),signatureField:i.string().describe(`Field used as the tenant signature`)}),ue=i.strictObject({namespace:i.string().optional().describe(`TailorDB namespace where the user table is defined`),type:i.custom().transform(stripTailorDBTypeBuilderHelpers).pipe(T),usernameField:i.string(),attributes:i.record(i.string(),i.literal(!0)).optional(),attributeList:i.array(i.string()).optional()}),de=i.union([i.string(),i.boolean(),i.array(i.string()),i.array(i.boolean())]),fe=i.strictObject({attributes:i.record(i.string(),de.nullish()).transform(e=>Object.fromEntries(Object.entries(e).filter(e=>e[1]!=null))).optional(),attributeList:i.array(i.uuid()).optional()}),pe=i.strictObject({handler:i.function(),invoker:i.string()}),J=i.strictObject({name:i.string().describe(`Auth service name`),hooks:i.strictObject({beforeLogin:pe.optional().describe(`Before login auth hook`)}).optional().describe(`Auth hooks`),machineUsers:i.record(i.string(),fe).optional().describe(`Machine user definitions`),oauth2Clients:i.record(i.string(),H).optional().describe(`OAuth2 client definitions`),idProvider:B.optional().describe(`Identity provider configuration`),scim:ce.optional().describe(`SCIM provisioning configuration`),tenantProvider:le.optional().describe(`Multi-tenant provider configuration`),connections:i.record(i.string(),k).optional().describe(`Auth connection definitions for external OAuth2 providers`),publishSessionEvents:i.boolean().optional().describe(`Enable publishing session events`)}),me=i.xor([J.extend({userProfile:ue.optional().describe(`User profile configuration`),machineUserAttributes:i.undefined().optional()}),J.extend({userProfile:i.undefined().optional(),machineUserAttributes:i.record(i.string(),M).describe(`Machine user attribute fields`)})],{error:e=>{if(e.code===`invalid_union`&&!(e.errors.length<2)&&e.errors.every(e=>e.every(e=>e.path.length===1&&(e.path[0]===`userProfile`||e.path[0]===`machineUserAttributes`))))return"Specify either `userProfile` or `machineUserAttributes`, not both."}}),he=i.strictObject({kind:i.literal(`tailordb`).describe(`TailorDB record event trigger`),events:i.array(i.enum([`tailordb.type_record.created`,`tailordb.type_record.updated`,`tailordb.type_record.deleted`])).min(1).transform(e=>[...new Set(e)]).describe(`TailorDB event types to trigger on`),tableName:i.string().describe(`TailorDB table name to watch for events`),condition:s.optional().describe(`Condition function to filter events`)}),ge=i.strictObject({kind:i.literal(`resolverExecuted`),resolverName:i.string().describe(`Name of the resolver to trigger on`),condition:s.optional().describe(`Condition function to filter events`)}),_e=i.strictObject({kind:i.literal(`schedule`),cron:i.string().describe(`CRON expression for the schedule`),timezone:i.string().optional().default(`UTC`).describe(`Timezone for the CRON schedule (default: UTC)`)}),ve=i.strictObject({body:s.optional().describe(`Function returning the response body`),statusCode:i.number().int().optional().describe(`HTTP status code for the response`)}),ye=i.strictObject({kind:i.literal(`incomingWebhook`),response:ve.optional().describe(`Response configuration`)}),be=i.strictObject({kind:i.literal(`idpUser`).describe(`IdP user event trigger`),events:i.array(i.enum([`idp.user.created`,`idp.user.updated`,`idp.user.deleted`])).min(1).transform(e=>[...new Set(e)]).describe(`IdP user event types to trigger on`),idp:i.string().optional().describe(`IdP namespace name to subscribe to. If omitted, the project's only IdP is used; throws when multiple IdPs exist.`)}),xe=i.strictObject({kind:i.literal(`authAccessToken`).describe(`Auth access token event trigger`),events:i.array(i.enum([`auth.access_token.issued`,`auth.access_token.refreshed`,`auth.access_token.revoked`])).min(1).transform(e=>[...new Set(e)]).describe(`Auth access token event types to trigger on`)}),Y=i.string().refine(e=>e.trim().length>0,`Workflow name cannot be blank`).describe(`Workflow name to subscribe to.`),Se=i.strictObject({kind:i.literal(`workflowExecution`).describe(`Workflow execution event trigger`),events:i.array(i.enum([`workflow.workflow_execution.started`,`workflow.workflow_execution.completed`,`workflow.workflow_execution.retried`,`workflow.workflow_execution.resumed`,`workflow.workflow_execution.wait_started`,`workflow.workflow_execution.wait_resolved`])).min(1).transform(e=>[...new Set(e)]).describe(`Workflow execution event types to trigger on`),workflowName:Y,condition:s.optional().describe(`Condition function to filter events`)}),Ce=i.strictObject({kind:i.literal(`workflowJobExecution`).describe(`Workflow job execution event trigger`),events:i.array(i.enum([`workflow.workflow_execution.job_execution.started`,`workflow.workflow_execution.job_execution.completed`,`workflow.workflow_execution.job_execution.wait_started`,`workflow.workflow_execution.job_execution.wait_resolved`])).min(1).transform(e=>[...new Set(e)]).describe(`Workflow job execution event types to trigger on`),workflowName:Y,condition:s.optional().describe(`Condition function to filter events`)}),X=i.discriminatedUnion(`kind`,[he,ge,_e,ye,be,xe,Se,Ce]),we=i.strictObject({kind:i.enum([`function`,`jobFunction`]),body:s.describe(`Function implementation`),invoker:P.optional().describe(`Invoker for the function execution`)}),Te=i.strictObject({kind:i.literal(`graphql`),appName:i.string().optional().describe(`Target application name for the GraphQL query`),query:i.preprocess(e=>String(e),i.string().describe(`GraphQL query string`)),variables:s.optional().describe(`Function to compute GraphQL variables`),invoker:P.optional().describe(`Invoker for the GraphQL execution`)}),Ee=i.strictObject({kind:i.literal(`webhook`),url:s.describe(`Function returning the webhook URL`),requestBody:s.optional().describe(`Function to compute the request body`),headers:i.record(i.string(),i.union([i.string(),i.strictObject({vault:i.string(),key:i.string()})])).optional().describe(`HTTP headers for the webhook request`)}),Z=i.lazy(()=>i.union([i.string(),i.number(),i.boolean(),i.null(),i.array(Z),i.record(i.string(),Z)])),De=i.union([i.string(),i.number(),i.boolean(),i.array(Z),i.record(i.string(),Z)]),Oe=i.union([De,s]).describe(`Arguments to pass to the workflow`),Q={kind:i.literal(`workflow`),args:Oe.optional(),invoker:P.optional().describe(`Invoker for the workflow execution`)},ke=i.strictObject({...Q,workflowName:i.string().describe(`Name of the workflow to execute`),workflow:i.never().optional()}),Ae=i.strictObject({...Q,workflow:i.looseObject({name:i.string()}),workflowName:i.string().optional()}).transform(({workflow:e,...t})=>({...t,workflowName:e.name})),je=i.union([Ae,ke]),Me=i.union([we,Te,Ee,je]),$=i.strictObject({name:i.string().describe(`Executor name`),description:i.string().optional().describe(`Executor description`),disabled:i.boolean().optional().default(!1).describe(`Whether the executor is disabled`),trigger:X.describe(`Event trigger configuration`),operation:Me.describe(`Operation to execute when triggered`)});function stripExecutorTriggerArgs(t){if(!e(t,`executor`))return t;let n=t.trigger;if(typeof n!=`object`||!n||!(`__args`in n))return t;let{__args:r,...i}=n;return{...t,trigger:i}}async function loadExecutor(e){let t=(await importUserModule(e)).default,n=$.safeParse(stripExecutorTriggerArgs(t));return n.success?n.data:null}function createExecutorService(i){let{config:a,baseDir:o}=i,s={},c=[],l,loadExecutorForFile=async i=>{try{let a=await importUserModule(i),o=$.safeParse(stripExecutorTriggerArgs(a.default));if(o.success){let e=r.relative(process.cwd(),i);return n.debug(`Executor: ${t.successBright(`"${o.data.name}"`)} loaded from ${t.path(e)}`),s[i]=o.data,o.data}if(e(a.default,`executor`))throw o.error}catch(e){let a=r.relative(process.cwd(),i);throw n.error(`Failed to load executor from ${t.bold(a)}`),n.error(String(e)),e}};return{config:a,get executors(){return s},get pluginExecutors(){return c},loadExecutors:async()=>(l||=(async()=>{if(a.files.length===0)return;let e=loadFilesWithIgnores(a,o);return n.newline(),n.log(`Found ${t.highlight(e.length.toString())} executor files`),await Promise.all(e.map(e=>loadExecutorForFile(e))),assertUniqueExecutorNames(s),s})(),await l??(Object.keys(s).length>0?s:void 0)),loadPluginExecutorFiles:async e=>{if(e.length!==0){n.newline(),n.log(`Loading ${t.highlight(e.length.toString())} plugin-generated executor files`);for(let t of e){let e=await loadExecutorForFile(t);e&&c.push({executor:e,pluginId:`plugin-generated`,sourceTableName:void 0})}assertUniqueExecutorNames(s)}}}}function assertUniqueExecutorNames(e){let t=/* @__PURE__ */ new Map;for(let[n,i]of Object.entries(e)){let e=r.relative(process.cwd(),n),a=t.get(i.name);if(a)throw Error(`Duplicate executor name "${i.name}" found:\n - ${a}\n - ${e}\nEach executor must have a unique name.`);t.set(i.name,e)}}export{c as _,me as a,importUserModule as b,pickTailorDBTypeSchemaKeys as c,T as d,applyRelationMetadataToFieldConfig as f,loadFilesWithIgnores as g,validateRelationConfig as h,$ as i,stripTailorDBTypeBuilderHelpers as l,processRelationMetadata as m,loadExecutor as n,P as o,buildRelationInfo as p,stripExecutorTriggerArgs as r,M as s,createExecutorService as t,D as u,beginUserModuleRun as v,s as x,currentImportNonce as y};
|
|
7
|
-
//# sourceMappingURL=service-
|
|
6
|
+
while an executor uses this table, an error will be thrown during apply.`)}),b=i.union([i.strictObject({user:i.string()}),i.string(),i.boolean(),i.array(i.string()),i.array(i.boolean())],{error:e=>{if(typeof e.input==`object`&&e.input!==null){let t=Object.keys(e.input);return t.length===1?`"${t[0]}" operand is not supported in gqlPermission. Use permission() for record-level conditions.`:`Operand object must have exactly 1 key`}return`Invalid operand in gqlPermission`}}),x=i.union([b,i.strictObject({record:i.string()}),i.strictObject({oldRecord:i.string()}),i.strictObject({newRecord:i.string()})]),S=i.enum([`=`,`!=`,`in`,`not in`,`hasAny`,`not hasAny`]),C=i.tuple([x,S,x]).readonly(),re=i.tuple([b,S,b]).readonly(),w=i.union([i.strictObject({conditions:i.union([C,i.array(C).readonly()]),description:i.string().optional(),permit:i.boolean().optional()}),i.tuple([x,S,x]).readonly(),i.tuple([x,S,x,i.boolean()]).readonly(),i.array(i.union([C,i.boolean()])).refine(e=>{let t=e.findIndex(e=>typeof e==`boolean`);return t===-1||t===e.length-1},{message:`Boolean permit flag must only appear at the end`}).readonly()]),ie=i.enum([`read`,`create`,`update`,`delete`,`aggregate`,`bulkUpsert`]),ae=i.strictObject({conditions:i.array(re).readonly(),actions:i.union([i.literal(`all`),i.array(ie).readonly()]),permit:i.boolean().optional(),description:i.string().optional()}),oe=i.strictObject({record:i.strictObject({create:i.array(w).readonly(),read:i.array(w).readonly(),update:i.array(w).readonly(),delete:i.array(w).readonly()}).optional(),gql:i.array(ae).readonly().optional()}),T=i.strictObject({name:i.string(),fields:i.record(i.string(),v),metadata:i.object({name:i.string(),description:i.string().optional(),settings:y.optional(),permissions:oe,files:i.record(i.string(),i.string()),indexes:i.record(i.string(),i.strictObject({fields:i.array(i.string()),unique:i.boolean().optional()})).optional(),typeHook:i.strictObject({create:s.optional(),update:s.optional()}).optional(),typeValidate:s.optional()}).strict()}),E=i.strictObject({directory:i.string().describe(`Directory containing migration files`),machineUser:i.string().optional().describe(`Machine user name for migration execution`)}),D=i.strictObject({files:i.array(i.string()).describe(`Glob patterns for TailorDB table definition files`),ignores:i.array(i.string()).optional().describe(`Glob patterns to exclude from table discovery`),migration:E.optional().describe(`Migration configuration`),gqlOperations:h.optional().describe(`Default GraphQL operations for all tables in this service`)}),O=T.keyof().options;function stripTailorDBTypeBuilderHelpers(t){return e(t,`tailordb-type`)?pickTailorDBTypeSchemaKeys(t):t}function pickTailorDBTypeSchemaKeys(e){if(typeof e!=`object`||!e)return e;let t={},n=e;for(let e of O)Object.prototype.hasOwnProperty.call(n,e)&&(t[e]=n[e]);return t}const k=i.strictObject({providerUrl:i.string().describe(`OAuth2 provider URL`),issuerUrl:i.string().describe(`OAuth2 issuer URL`),clientId:i.string().describe(`OAuth2 client ID`),clientSecret:i.string().describe(`OAuth2 client secret`),authUrl:i.string().optional().describe(`OAuth2 authorization endpoint override`),tokenUrl:i.string().optional().describe(`OAuth2 token endpoint override`)}).extend({type:i.literal(`oauth2`).describe(`Connection type`)}),A=i.strictObject({value:i.string().describe(`The allowed value`),description:i.string().optional().describe(`Description of the allowed value`)}),j=i.strictObject({as:i.enum([`string`,`date`,`temporal`]).optional().describe(`Date value representation`),required:i.boolean().optional().describe(`Whether the field is required`),array:i.boolean().optional().describe(`Whether the field is an array`),description:i.string().optional().describe(`Field description`),allowedValues:i.array(A).optional().describe(`Allowed values for enum fields`),hooks:i.strictObject({create:s.optional().describe(`Hook function called on creation`),update:s.optional().describe(`Hook function called on update`)}).optional().describe(`Lifecycle hooks`),validate:i.array(s).optional().describe(`Validation functions for the field`),typeName:i.string().optional().describe(`Type name for nested or enum fields`),default:i.unknown().optional().describe(`Default value for the field on create`)}),M=i.object({type:f.describe(`Field data type`),metadata:j.describe(`Field metadata configuration`),get fields(){return i.record(i.string(),M)}}),N=i.strictObject({namespace:i.string().describe(`Auth namespace`),machineUserName:i.string().describe(`Machine user name for authentication`)}),P=i.union([i.string().describe(`Machine user name (namespace auto-resolved from auth service)`),N]),F=i.strictObject({vaultName:i.string().describe(`Vault name containing the secret`),secretKey:i.string().describe(`Key of the secret in the vault`)}),I=i.strictObject({name:i.string().describe(`Identity provider name`),kind:i.literal(`OIDC`),clientID:i.string().describe(`OAuth2 client ID`),clientSecret:F.describe(`OAuth2 client secret`),providerURL:i.string().describe(`OIDC provider URL`),issuerURL:i.string().optional().describe(`OIDC issuer URL (defaults to providerURL)`),usernameClaim:i.string().optional().describe(`JWT claim to use as username`)}),L=i.strictObject({name:i.string().describe(`Identity provider name`),kind:i.literal(`SAML`),enableSignRequest:i.boolean().default(!1).describe(`Enable signing of SAML requests`),metadataURL:i.string().optional().describe(`URL to fetch SAML metadata (mutually exclusive with rawMetadata)`),rawMetadata:i.string().optional().describe(`Raw SAML metadata XML (mutually exclusive with metadataURL)`),defaultRedirectURL:i.string().optional().describe(`URL to redirect to when SAML ACS receives a response with an empty RelayState.`)}).refine(e=>e.metadataURL!==void 0!=(e.rawMetadata!==void 0),`Provide either metadataURL or rawMetadata`),R=i.strictObject({name:i.string().describe(`Identity provider name`),kind:i.literal(`IDToken`),providerURL:i.string().describe(`ID token provider URL`),issuerURL:i.string().optional().describe(`ID token issuer URL`),clientID:i.string().describe(`Client ID for ID token validation`),usernameClaim:i.string().optional().describe(`JWT claim to use as username`)}),z=i.strictObject({name:i.string().describe(`Identity provider name`),kind:i.literal(`BuiltInIdP`),namespace:i.string().describe(`IdP namespace`),clientName:i.string().describe(`OAuth2 client name in the IdP`)}),B=i.discriminatedUnion(`kind`,[I,L,R,z]),V=i.union([i.literal(`authorization_code`),i.literal(`refresh_token`)]).describe(`OAuth2 grant type`),H=i.strictObject({description:i.string().optional().describe(`Client description`),grantTypes:i.array(V).default([`authorization_code`,`refresh_token`]).describe(`Allowed OAuth2 grant types`),redirectURIs:i.array(i.union([i.templateLiteral([`https://`,i.string()]),i.templateLiteral([`http://`,i.string()]),i.templateLiteral([i.string(),`:url`]),i.templateLiteral([i.string(),`:url/`,i.string()])])).describe(`Allowed redirect URIs`),clientType:i.union([i.literal(`confidential`),i.literal(`public`),i.literal(`browser`)]).optional().describe(`OAuth2 client type`),accessTokenLifetimeSeconds:i.number().int().min(60,`Minimum access token lifetime is 60 seconds`).max(86400,`Maximum access token lifetime is 1 day (86400 seconds)`).optional().describe(`Access token lifetime in seconds (60-86400)`).transform(e=>e?{seconds:BigInt(e),nanos:0}:void 0),refreshTokenLifetimeSeconds:i.number().int().min(60,`Minimum refresh token lifetime is 60 seconds`).max(604800,`Maximum refresh token lifetime is 7 days (604800 seconds)`).optional().describe(`Refresh token lifetime in seconds (60-604800)`).transform(e=>e?{seconds:BigInt(e),nanos:0}:void 0),requireDpop:i.boolean().optional().describe(`Require DPoP (Demonstrating Proof-of-Possession) for token requests`)}).refine(e=>e.clientType!==`browser`||e.requireDpop!==!0,{message:`requireDpop cannot be set to true for browser clients as they don't support DPoP`,path:[`requireDpop`]}),U=i.strictObject({type:i.union([i.literal(`oauth2`),i.literal(`bearer`)]).describe(`SCIM authorization type`),bearerSecret:F.optional().describe(`Bearer token secret (required for bearer type)`)}),W=i.union([i.literal(`string`),i.literal(`number`),i.literal(`boolean`),i.literal(`datetime`),i.literal(`complex`)]).describe(`SCIM attribute data type`),G=i.strictObject({type:W.describe(`Attribute data type`),name:i.string().describe(`Attribute name`),description:i.string().optional().describe(`Attribute description`),mutability:i.union([i.literal(`readOnly`),i.literal(`readWrite`),i.literal(`writeOnly`)]).optional().describe(`Attribute mutability`),required:i.boolean().optional().describe(`Whether the attribute is required`),multiValued:i.boolean().optional().describe(`Whether the attribute can have multiple values`),uniqueness:i.union([i.literal(`none`),i.literal(`server`),i.literal(`global`)]).optional().describe(`Uniqueness constraint`),canonicalValues:i.array(i.string()).nullable().optional().describe(`List of canonical values`),get subAttributes(){return i.array(G).nullable().optional()}}),K=i.strictObject({name:i.string().describe(`SCIM schema name`),attributes:i.array(G).describe(`Schema attributes`)}),q=i.strictObject({tailorDBField:i.string().describe(`TailorDB field name to map to`),scimPath:i.string().describe(`SCIM attribute path`)}),se=i.strictObject({name:i.string().describe(`SCIM resource name`),tailorDBNamespace:i.string().describe(`TailorDB namespace for the resource`),tailorDBType:i.string().describe(`TailorDB table name for the resource`),coreSchema:K.describe(`Core SCIM schema definition`),attributeMapping:i.array(q).describe(`Attribute mapping configuration`)}),ce=i.strictObject({machineUserName:i.string().describe(`Machine user name for SCIM operations`),authorization:U.describe(`SCIM authorization configuration`),resources:i.array(se).describe(`SCIM resource definitions`)}),le=i.strictObject({namespace:i.string().describe(`TailorDB namespace for the tenant table`),type:i.string().describe(`TailorDB table name for tenants`),signatureField:i.string().describe(`Field used as the tenant signature`)}),ue=i.strictObject({namespace:i.string().optional().describe(`TailorDB namespace where the user table is defined`),type:i.custom().transform(stripTailorDBTypeBuilderHelpers).pipe(T),usernameField:i.string(),attributes:i.record(i.string(),i.literal(!0)).optional(),attributeList:i.array(i.string()).optional()}),de=i.union([i.string(),i.boolean(),i.array(i.string()),i.array(i.boolean())]),fe=i.strictObject({attributes:i.record(i.string(),de.nullish()).transform(e=>Object.fromEntries(Object.entries(e).filter(e=>e[1]!=null))).optional(),attributeList:i.array(i.uuid()).optional()}),pe=i.strictObject({handler:i.function(),invoker:i.string()}),J=i.strictObject({name:i.string().describe(`Auth service name`),hooks:i.strictObject({beforeLogin:pe.optional().describe(`Before login auth hook`)}).optional().describe(`Auth hooks`),machineUsers:i.record(i.string(),fe).optional().describe(`Machine user definitions`),oauth2Clients:i.record(i.string(),H).optional().describe(`OAuth2 client definitions`),idProvider:B.optional().describe(`Identity provider configuration`),scim:ce.optional().describe(`SCIM provisioning configuration`),tenantProvider:le.optional().describe(`Multi-tenant provider configuration`),connections:i.record(i.string(),k).optional().describe(`Auth connection definitions for external OAuth2 providers`),publishSessionEvents:i.boolean().optional().describe(`Enable publishing session events`)}),me=i.xor([J.extend({userProfile:ue.optional().describe(`User profile configuration`),machineUserAttributes:i.undefined().optional()}),J.extend({userProfile:i.undefined().optional(),machineUserAttributes:i.record(i.string(),M).describe(`Machine user attribute fields`)})],{error:e=>{if(e.code===`invalid_union`&&!(e.errors.length<2)&&e.errors.every(e=>e.every(e=>e.path.length===1&&(e.path[0]===`userProfile`||e.path[0]===`machineUserAttributes`))))return"Specify either `userProfile` or `machineUserAttributes`, not both."}}),he=i.strictObject({kind:i.literal(`tailordb`).describe(`TailorDB record event trigger`),events:i.array(i.enum([`tailordb.type_record.created`,`tailordb.type_record.updated`,`tailordb.type_record.deleted`])).min(1).transform(e=>[...new Set(e)]).describe(`TailorDB event types to trigger on`),tableName:i.string().describe(`TailorDB table name to watch for events`),condition:s.optional().describe(`Condition function to filter events`)}),ge=i.strictObject({kind:i.literal(`resolverExecuted`),resolverName:i.string().describe(`Name of the resolver to trigger on`),condition:s.optional().describe(`Condition function to filter events`)}),_e=i.strictObject({kind:i.literal(`schedule`),cron:i.string().describe(`CRON expression for the schedule`),timezone:i.string().optional().default(`UTC`).describe(`Timezone for the CRON schedule (default: UTC)`)}),ve=i.strictObject({body:s.optional().describe(`Function returning the response body`),statusCode:i.number().int().optional().describe(`HTTP status code for the response`)}),ye=i.strictObject({kind:i.literal(`incomingWebhook`),response:ve.optional().describe(`Response configuration`)}),be=i.strictObject({kind:i.literal(`idpUser`).describe(`IdP user event trigger`),events:i.array(i.enum([`idp.user.created`,`idp.user.updated`,`idp.user.deleted`])).min(1).transform(e=>[...new Set(e)]).describe(`IdP user event types to trigger on`),idp:i.string().optional().describe(`IdP namespace name to subscribe to. If omitted, the project's only IdP is used; throws when multiple IdPs exist.`)}),xe=i.strictObject({kind:i.literal(`authAccessToken`).describe(`Auth access token event trigger`),events:i.array(i.enum([`auth.access_token.issued`,`auth.access_token.refreshed`,`auth.access_token.revoked`])).min(1).transform(e=>[...new Set(e)]).describe(`Auth access token event types to trigger on`)}),Y=i.string().refine(e=>e.trim().length>0,`Workflow name cannot be blank`).describe(`Workflow name to subscribe to.`),Se=i.strictObject({kind:i.literal(`workflowExecution`).describe(`Workflow execution event trigger`),events:i.array(i.enum([`workflow.workflow_execution.started`,`workflow.workflow_execution.completed`,`workflow.workflow_execution.retried`,`workflow.workflow_execution.resumed`,`workflow.workflow_execution.wait_started`,`workflow.workflow_execution.wait_resolved`])).min(1).transform(e=>[...new Set(e)]).describe(`Workflow execution event types to trigger on`),workflowName:Y,condition:s.optional().describe(`Condition function to filter events`)}),Ce=i.strictObject({kind:i.literal(`workflowJobExecution`).describe(`Workflow job execution event trigger`),events:i.array(i.enum([`workflow.workflow_execution.job_execution.started`,`workflow.workflow_execution.job_execution.completed`,`workflow.workflow_execution.job_execution.wait_started`,`workflow.workflow_execution.job_execution.wait_resolved`])).min(1).transform(e=>[...new Set(e)]).describe(`Workflow job execution event types to trigger on`),workflowName:Y,condition:s.optional().describe(`Condition function to filter events`)}),X=i.discriminatedUnion(`kind`,[he,ge,_e,ye,be,xe,Se,Ce]),we=i.strictObject({kind:i.enum([`function`,`jobFunction`]),body:s.describe(`Function implementation`),invoker:P.optional().describe(`Invoker for the function execution`)}),Te=i.strictObject({kind:i.literal(`graphql`),appName:i.string().optional().describe(`Target application name for the GraphQL query`),query:i.preprocess(e=>String(e),i.string().describe(`GraphQL query string`)),variables:s.optional().describe(`Function to compute GraphQL variables`),invoker:P.optional().describe(`Invoker for the GraphQL execution`)}),Ee=i.strictObject({kind:i.literal(`webhook`),url:s.describe(`Function returning the webhook URL`),requestBody:s.optional().describe(`Function to compute the request body`),headers:i.record(i.string(),i.union([i.string(),i.strictObject({vault:i.string(),key:i.string()})])).optional().describe(`HTTP headers for the webhook request`)}),Z=i.lazy(()=>i.union([i.string(),i.number(),i.boolean(),i.null(),i.array(Z),i.record(i.string(),Z)])),De=i.union([i.string(),i.number(),i.boolean(),i.array(Z),i.record(i.string(),Z)]),Oe=i.union([De,s]).describe(`Arguments to pass to the workflow`),Q={kind:i.literal(`workflow`),args:Oe.optional(),invoker:P.optional().describe(`Invoker for the workflow execution`)},ke=i.strictObject({...Q,workflowName:i.string().describe(`Name of the workflow to execute`),workflow:i.never().optional()}),Ae=i.strictObject({...Q,workflow:i.looseObject({name:i.string()}),workflowName:i.string().optional()}).transform(({workflow:e,...t})=>({...t,workflowName:e.name})),je=i.union([Ae,ke]),Me=i.union([we,Te,Ee,je]),$=i.strictObject({name:i.string().describe(`Executor name`),description:i.string().optional().describe(`Executor description`),disabled:i.boolean().optional().default(!1).describe(`Whether the executor is disabled`),trigger:X.describe(`Event trigger configuration`),operation:Me.describe(`Operation to execute when triggered`)});function stripExecutorTriggerArgs(t){if(!e(t,`executor`))return t;let n=t.trigger;if(typeof n!=`object`||!n||!(`__args`in n))return t;let{__args:r,...i}=n;return{...t,trigger:i}}async function loadExecutor(e){let t=(await importUserModule(e)).default,n=$.safeParse(stripExecutorTriggerArgs(t));return n.success?n.data:null}function createExecutorService(i){let{config:a,baseDir:o}=i,s={},c=[],l,loadExecutorForFile=async i=>{try{let a=await importUserModule(i),o=$.safeParse(stripExecutorTriggerArgs(a.default));if(o.success){let e=r.relative(process.cwd(),i);return t.debug(`Executor: ${n.successBright(`"${o.data.name}"`)} loaded from ${n.path(e)}`),s[i]=o.data,o.data}if(e(a.default,`executor`))throw o.error}catch(e){let a=r.relative(process.cwd(),i);throw t.error(`Failed to load executor from ${n.bold(a)}`),t.error(String(e)),e}};return{config:a,get executors(){return s},get pluginExecutors(){return c},loadExecutors:async()=>(l||=(async()=>{if(a.files.length===0)return;let e=loadFilesWithIgnores(a,o);return t.newline(),t.log(`Found ${n.highlight(e.length.toString())} executor files`),await Promise.all(e.map(e=>loadExecutorForFile(e))),assertUniqueExecutorNames(s),s})(),await l??(Object.keys(s).length>0?s:void 0)),loadPluginExecutorFiles:async e=>{if(e.length!==0){t.newline(),t.log(`Loading ${n.highlight(e.length.toString())} plugin-generated executor files`);for(let t of e){let e=await loadExecutorForFile(t);e&&c.push({executor:e,pluginId:`plugin-generated`,sourceTableName:void 0})}assertUniqueExecutorNames(s)}}}}function assertUniqueExecutorNames(e){let t=/* @__PURE__ */ new Map;for(let[n,i]of Object.entries(e)){let e=r.relative(process.cwd(),n),a=t.get(i.name);if(a)throw Error(`Duplicate executor name "${i.name}" found:\n - ${a}\n - ${e}\nEach executor must have a unique name.`);t.set(i.name,e)}}export{c as _,me as a,importUserModule as b,pickTailorDBTypeSchemaKeys as c,T as d,applyRelationMetadataToFieldConfig as f,loadFilesWithIgnores as g,validateRelationConfig as h,$ as i,stripTailorDBTypeBuilderHelpers as l,processRelationMetadata as m,loadExecutor as n,P as o,buildRelationInfo as p,stripExecutorTriggerArgs as r,M as s,createExecutorService as t,D as u,beginUserModuleRun as v,s as x,currentImportNonce as y};
|
|
7
|
+
//# sourceMappingURL=service-CL1Bp4It.mjs.map
|