@tailor-platform/sdk 1.47.1 → 1.49.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/CHANGELOG.md +95 -0
  2. package/dist/{actor-jk4-f0yp.d.mts → actor-BeIEiPYM.d.mts} +2 -2
  3. package/dist/{application-C7H7y0hS.mjs → application-CZMzt9jL.mjs} +82 -18
  4. package/dist/application-CZMzt9jL.mjs.map +1 -0
  5. package/dist/application-v_E2W-Fz.mjs +4 -0
  6. package/dist/brand-D-d15jx3.mjs.map +1 -1
  7. package/dist/cli/index.mjs +55 -31
  8. package/dist/cli/index.mjs.map +1 -1
  9. package/dist/cli/lib.d.mts +6 -6
  10. package/dist/cli/lib.mjs +6 -6
  11. package/dist/cli/lib.mjs.map +1 -1
  12. package/dist/cli/skills.mjs.map +1 -1
  13. package/dist/{client-DCqdtFte.mjs → client-CPW1N1Rs.mjs} +1 -1
  14. package/dist/{client-DbyKSN1F.mjs → client-_kHh0Pip.mjs} +2 -2
  15. package/dist/{client-DbyKSN1F.mjs.map → client-_kHh0Pip.mjs.map} +1 -1
  16. package/dist/configure/index.d.mts +4 -4
  17. package/dist/configure/index.mjs +51 -3
  18. package/dist/configure/index.mjs.map +1 -1
  19. package/dist/{crashreport-CNSw_BrJ.mjs → crashreport-CvmdFs4i.mjs} +5 -5
  20. package/dist/crashreport-CvmdFs4i.mjs.map +1 -0
  21. package/dist/{crashreport-DXGFd16F.mjs → crashreport-DHJuSmUc.mjs} +1 -1
  22. package/dist/enum-constants-C3KSpsYj.mjs.map +1 -1
  23. package/dist/{errors-wNQxQQBH.mjs → errors-pMPXghkO.mjs} +1 -1
  24. package/dist/{errors-wNQxQQBH.mjs.map → errors-pMPXghkO.mjs.map} +1 -1
  25. package/dist/field-DLSIuMTu.mjs.map +1 -1
  26. package/dist/file-utils-DjNi_3U_.mjs.map +1 -1
  27. package/dist/index-BQ4oi0AI.d.mts +48 -0
  28. package/dist/{index-BbOTbZFf.d.mts → index-BjXN1SdY.d.mts} +2 -2
  29. package/dist/{index-DB8EapT-.d.mts → index-C--7W0UO.d.mts} +5 -5
  30. package/dist/{index-BRvNi5q9.d.mts → index-VJW98BSy.d.mts} +2 -2
  31. package/dist/{index-iy-hNfGp.d.mts → index-nV4ZC_Ve.d.mts} +2 -2
  32. package/dist/{interceptor-CBsqEWDK.mjs → interceptor-DTNS0EtF.mjs} +1 -1
  33. package/dist/{interceptor-CBsqEWDK.mjs.map → interceptor-DTNS0EtF.mjs.map} +1 -1
  34. package/dist/{job-R5C2Hfcc.mjs → job-M3Avv_SV.mjs} +4 -3
  35. package/dist/{job-R5C2Hfcc.mjs.map → job-M3Avv_SV.mjs.map} +1 -1
  36. package/dist/kysely/index.mjs.map +1 -1
  37. package/dist/kysely-type-B8aRz_oC.mjs.map +1 -1
  38. package/dist/logger-DTNAMYGy.mjs.map +1 -1
  39. package/dist/{mock-BP-9O5On.mjs → mock-BfL09ULZ.mjs} +1 -1
  40. package/dist/{mock-BP-9O5On.mjs.map → mock-BfL09ULZ.mjs.map} +1 -1
  41. package/dist/multiline-e3IpANmS.mjs.map +1 -1
  42. package/dist/package-json-6Px8bDpG.mjs.map +1 -1
  43. package/dist/plugin/builtin/enum-constants/index.d.mts +1 -1
  44. package/dist/plugin/builtin/file-utils/index.d.mts +1 -1
  45. package/dist/plugin/builtin/kysely-type/index.d.mts +1 -1
  46. package/dist/plugin/builtin/seed/index.d.mts +1 -1
  47. package/dist/plugin/builtin/seed/index.mjs +1 -1
  48. package/dist/plugin/index.d.mts +2 -2
  49. package/dist/plugin/index.mjs.map +1 -1
  50. package/dist/{repl-editor-CZpLlOBj.mjs → repl-editor-jZ493eQI.mjs} +1 -1
  51. package/dist/{repl-editor-CZpLlOBj.mjs.map → repl-editor-jZ493eQI.mjs.map} +1 -1
  52. package/dist/{runtime-XjP6JMmP.mjs → runtime-oZgK353r.mjs} +484 -132
  53. package/dist/runtime-oZgK353r.mjs.map +1 -0
  54. package/dist/{tailordb-DjlNUV6u.mjs → schema-C5QjYEc-.mjs} +2 -42
  55. package/dist/schema-C5QjYEc-.mjs.map +1 -0
  56. package/dist/secret-file-BHpxGyNf.mjs +65 -0
  57. package/dist/secret-file-BHpxGyNf.mjs.map +1 -0
  58. package/dist/seed/index.mjs.map +1 -1
  59. package/dist/{seed-DrKY5yIF.mjs → seed-DjfAn0BC.mjs} +44 -19
  60. package/dist/seed-DjfAn0BC.mjs.map +1 -0
  61. package/dist/{service-obEU5gSM.mjs → service-DCgJxdg1.mjs} +2 -2
  62. package/dist/{service-obEU5gSM.mjs.map → service-DCgJxdg1.mjs.map} +1 -1
  63. package/dist/{tailor-db-field-Bn8ZC5lK.d.mts → tailor-db-field-4bMLe25-.d.mts} +5 -1
  64. package/dist/telemetry-C13VIFpT.mjs +4 -0
  65. package/dist/{telemetry-DcL8Fsm_.mjs → telemetry-C1Y56L5E.mjs} +1 -1
  66. package/dist/{telemetry-DcL8Fsm_.mjs.map → telemetry-C1Y56L5E.mjs.map} +1 -1
  67. package/dist/types-sir9UPht.mjs.map +1 -1
  68. package/dist/utils/test/index.d.mts +3 -3
  69. package/dist/utils/test/index.mjs +1 -1
  70. package/dist/utils/test/index.mjs.map +1 -1
  71. package/dist/vitest/environment.mjs +1 -1
  72. package/dist/vitest/environment.mjs.map +1 -1
  73. package/dist/vitest/index.mjs +1 -1
  74. package/dist/vitest/index.mjs.map +1 -1
  75. package/dist/vitest/setup.mjs +1 -1
  76. package/dist/vitest/setup.mjs.map +1 -1
  77. package/dist/{workflow.generated-i7PK4fg-.d.mts → workflow.generated-OYAu_6zX.d.mts} +12 -2
  78. package/docs/cli/application.md +4 -0
  79. package/docs/cli/workspace.md +20 -17
  80. package/docs/configuration.md +4 -0
  81. package/docs/generator/builtin.md +35 -4
  82. package/package.json +16 -16
  83. package/postinstall.mjs +1 -1
  84. package/dist/application-C7H7y0hS.mjs.map +0 -1
  85. package/dist/application-Csq5jxYP.mjs +0 -4
  86. package/dist/crashreport-CNSw_BrJ.mjs.map +0 -1
  87. package/dist/index-BXyS7xKC.d.mts +0 -21
  88. package/dist/runtime-XjP6JMmP.mjs.map +0 -1
  89. package/dist/seed-DrKY5yIF.mjs.map +0 -1
  90. package/dist/tailordb-DjlNUV6u.mjs.map +0 -1
  91. package/dist/telemetry-21afNV9_.mjs +0 -4
@@ -1 +1 @@
1
- {"version":3,"file":"service-obEU5gSM.mjs","names":["CLIError"],"sources":["../src/cli/commands/upgrade/version-detector.ts","../src/cli/commands/upgrade/service.ts"],"sourcesContent":["import * as path from \"pathe\";\nimport { readPackageJSON } from \"pkg-types\";\n\nconst SDK_PACKAGE_NAME = \"@tailor-platform/sdk\";\n\n/**\n * Detect the installed SDK version from the user's project.\n * Walks up from projectRoot to find the SDK package in node_modules,\n * matching Node's module resolution for workspace setups with hoisted deps.\n * @param projectRoot - The project root directory to search from\n * @returns The installed SDK version string, or null if not found\n */\nexport async function detectInstalledVersion(projectRoot: string): Promise<string | null> {\n let dir = path.resolve(projectRoot);\n while (true) {\n try {\n const sdkPath = path.join(dir, \"node_modules\", SDK_PACKAGE_NAME);\n const pkg = await readPackageJSON(sdkPath);\n if (pkg.version) return pkg.version;\n } catch {\n // Not found at this level, try parent\n }\n const parent = path.dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n return null;\n}\n","import { spawnSync } from \"node:child_process\";\nimport { CLIError } from \"@/cli/shared/errors\";\nimport { logger, styles } from \"@/cli/shared/logger\";\nimport { detectInstalledVersion } from \"./version-detector\";\nimport type { RunOutput } from \"./types\";\n\ninterface UpgradeOptions {\n from: string;\n dryRun: boolean;\n path: string;\n}\n\n/**\n * Print the upgrade summary to the terminal.\n * @param output - The parsed JSON output from sdk-codemod\n * @param dryRun - Whether this was a dry-run\n */\nfunction printUpgradeSummary(output: RunOutput, dryRun: boolean): void {\n if (dryRun) {\n logger.info(`${styles.bold(\"[Dry Run]\")} No files were modified.`);\n logger.log(\"\");\n }\n\n const total = output.codemodsApplied + output.codemodsSkipped + output.errors.length;\n logger.info(\n `Upgrade complete: ${styles.success(`${output.codemodsApplied} applied`)}, ${styles.dim(`${output.codemodsSkipped} skipped`)} (${total} total codemods)`,\n );\n\n if (output.filesModified.length > 0) {\n logger.log(\"\");\n logger.info(\n `${dryRun ? \"Files that would be modified\" : \"Modified files\"} (${output.filesModified.length}):`,\n );\n for (const file of output.filesModified) {\n logger.log(` ${styles.path(file)}`);\n }\n }\n\n if (output.warnings.length > 0) {\n logger.log(\"\");\n logger.warn(`Manual attention needed (${output.warnings.length}):`);\n for (const warning of output.warnings) {\n logger.log(` ${styles.warning(\"!\")} ${warning}`);\n }\n }\n\n if (output.errors.length > 0) {\n logger.log(\"\");\n logger.error(`Failed codemods (${output.errors.length}):`);\n for (const { codemodId, message } of output.errors) {\n logger.log(` ${styles.error(codemodId)}: ${message}`);\n }\n }\n}\n\n/**\n * Run the upgrade pipeline:\n * 1. Detect target SDK version from node_modules\n * 2. Invoke @tailor-platform/sdk-codemod CLI\n * 3. Parse JSON output and display results\n * @param options - Upgrade options\n */\nexport async function upgrade(options: UpgradeOptions): Promise<void> {\n const projectRoot = options.path;\n\n // Step 1: Detect target SDK version (the newly installed version)\n const targetVersion = await detectInstalledVersion(projectRoot);\n if (!targetVersion) {\n throw CLIError({\n message: `Could not detect installed @tailor-platform/sdk version in ${projectRoot}`,\n suggestion:\n \"Ensure @tailor-platform/sdk is installed. Run 'pnpm install' or 'npm install' first.\",\n command: \"upgrade\",\n });\n }\n\n logger.info(\n `Upgrading from ${styles.highlight(options.from)} → ${styles.highlight(targetVersion)}`,\n );\n\n if (options.dryRun) {\n logger.info(`${styles.bold(\"[Dry Run]\")} Changes will be previewed but not applied.`);\n }\n\n logger.log(\"\");\n\n // Step 2: Invoke sdk-codemod CLI\n // Use \"latest\" because sdk-codemod may not be published at the exact same\n // version as @tailor-platform/sdk. Version filtering is handled internally\n // by sdk-codemod's registry via the --from / --to arguments.\n const npxCommand = process.platform === \"win32\" ? \"npx.cmd\" : \"npx\";\n\n const result = spawnSync(\n npxCommand,\n [\n \"@tailor-platform/sdk-codemod@latest\",\n \"--from\",\n options.from,\n \"--to\",\n targetVersion,\n \"--target\",\n projectRoot,\n ...(options.dryRun ? [\"--dry-run\"] : []),\n ],\n {\n cwd: projectRoot,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n encoding: \"utf-8\",\n timeout: 300_000,\n },\n );\n\n if (result.error) {\n throw CLIError({\n message: `Failed to run @tailor-platform/sdk-codemod: ${result.error.message}`,\n suggestion: \"Ensure npx is available and the network is accessible.\",\n command: \"upgrade\",\n });\n }\n\n // Check for non-zero exit without a launch error (e.g. registry/auth/network failures)\n if (result.status !== 0 && !result.stdout?.trim()) {\n throw CLIError({\n message: `@tailor-platform/sdk-codemod exited with code ${result.status}`,\n details: result.stderr?.trim() || \"(no stderr output)\",\n suggestion:\n \"Review the error above. Common causes: invalid version arguments, network issues, or missing package registry access.\",\n command: \"upgrade\",\n });\n }\n\n // Forward captured stderr so users see dry-run diffs and progress messages\n // written by sdk-codemod. stderr is piped (not inherited) so that the error\n // path above can surface it via CLIError, but on success we still need to\n // replay it verbatim to keep the colorized unified diff output visible.\n if (result.stderr) {\n process.stderr.write(result.stderr);\n }\n\n // Step 3: Parse JSON output\n let output: RunOutput;\n try {\n output = JSON.parse(result.stdout);\n } catch {\n throw CLIError({\n message: \"Failed to parse output from @tailor-platform/sdk-codemod\",\n details: result.stdout || \"(empty stdout)\",\n suggestion: \"This is likely a bug. Please report it.\",\n command: \"upgrade\",\n });\n }\n\n // Step 4: Display results\n // Emit structured data on stdout (honors --json via logger.out) and\n // human-readable summary on stderr (via printUpgradeSummary).\n logger.out(output);\n printUpgradeSummary(output, options.dryRun);\n\n if (output.errors.length > 0) {\n throw CLIError({\n message: `Upgrade completed with ${output.errors.length} error(s)`,\n suggestion: \"Review the errors above and re-run the upgrade after fixing the issues.\",\n command: \"upgrade\",\n });\n }\n}\n"],"mappings":";;;;;;;;AAGA,MAAM,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,IAAI,OAAO,OAAO,SAAS,GACzB,MAAMA,eAAS;EACb,SAAS,0BAA0B,OAAO,OAAO,OAAO;EACxD,YAAY;EACZ,SAAS;EACV,CAAC"}
1
+ {"version":3,"file":"service-DCgJxdg1.mjs","names":["CLIError"],"sources":["../src/cli/commands/upgrade/version-detector.ts","../src/cli/commands/upgrade/service.ts"],"sourcesContent":["import * as path from \"pathe\";\nimport { readPackageJSON } from \"pkg-types\";\n\nconst SDK_PACKAGE_NAME = \"@tailor-platform/sdk\";\n\n/**\n * Detect the installed SDK version from the user's project.\n * Walks up from projectRoot to find the SDK package in node_modules,\n * matching Node's module resolution for workspace setups with hoisted deps.\n * @param projectRoot - The project root directory to search from\n * @returns The installed SDK version string, or null if not found\n */\nexport async function detectInstalledVersion(projectRoot: string): Promise<string | null> {\n let dir = path.resolve(projectRoot);\n while (true) {\n try {\n const sdkPath = path.join(dir, \"node_modules\", SDK_PACKAGE_NAME);\n const pkg = await readPackageJSON(sdkPath);\n if (pkg.version) return pkg.version;\n } catch {\n // Not found at this level, try parent\n }\n const parent = path.dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n return null;\n}\n","import { spawnSync } from \"node:child_process\";\nimport { CLIError } from \"@/cli/shared/errors\";\nimport { logger, styles } from \"@/cli/shared/logger\";\nimport { detectInstalledVersion } from \"./version-detector\";\nimport type { RunOutput } from \"./types\";\n\ninterface UpgradeOptions {\n from: string;\n dryRun: boolean;\n path: string;\n}\n\n/**\n * Print the upgrade summary to the terminal.\n * @param output - The parsed JSON output from sdk-codemod\n * @param dryRun - Whether this was a dry-run\n */\nfunction printUpgradeSummary(output: RunOutput, dryRun: boolean): void {\n if (dryRun) {\n logger.info(`${styles.bold(\"[Dry Run]\")} No files were modified.`);\n logger.log(\"\");\n }\n\n const total = output.codemodsApplied + output.codemodsSkipped + output.errors.length;\n logger.info(\n `Upgrade complete: ${styles.success(`${output.codemodsApplied} applied`)}, ${styles.dim(`${output.codemodsSkipped} skipped`)} (${total} total codemods)`,\n );\n\n if (output.filesModified.length > 0) {\n logger.log(\"\");\n logger.info(\n `${dryRun ? \"Files that would be modified\" : \"Modified files\"} (${output.filesModified.length}):`,\n );\n for (const file of output.filesModified) {\n logger.log(` ${styles.path(file)}`);\n }\n }\n\n if (output.warnings.length > 0) {\n logger.log(\"\");\n logger.warn(`Manual attention needed (${output.warnings.length}):`);\n for (const warning of output.warnings) {\n logger.log(` ${styles.warning(\"!\")} ${warning}`);\n }\n }\n\n if (output.errors.length > 0) {\n logger.log(\"\");\n logger.error(`Failed codemods (${output.errors.length}):`);\n for (const { codemodId, message } of output.errors) {\n logger.log(` ${styles.error(codemodId)}: ${message}`);\n }\n }\n}\n\n/**\n * Run the upgrade pipeline:\n * 1. Detect target SDK version from node_modules\n * 2. Invoke @tailor-platform/sdk-codemod CLI\n * 3. Parse JSON output and display results\n * @param options - Upgrade options\n */\nexport async function upgrade(options: UpgradeOptions): Promise<void> {\n const projectRoot = options.path;\n\n // Step 1: Detect target SDK version (the newly installed version)\n const targetVersion = await detectInstalledVersion(projectRoot);\n if (!targetVersion) {\n throw CLIError({\n message: `Could not detect installed @tailor-platform/sdk version in ${projectRoot}`,\n suggestion:\n \"Ensure @tailor-platform/sdk is installed. Run 'pnpm install' or 'npm install' first.\",\n command: \"upgrade\",\n });\n }\n\n logger.info(\n `Upgrading from ${styles.highlight(options.from)} → ${styles.highlight(targetVersion)}`,\n );\n\n if (options.dryRun) {\n logger.info(`${styles.bold(\"[Dry Run]\")} Changes will be previewed but not applied.`);\n }\n\n logger.log(\"\");\n\n // Step 2: Invoke sdk-codemod CLI\n // Use \"latest\" because sdk-codemod may not be published at the exact same\n // version as @tailor-platform/sdk. Version filtering is handled internally\n // by sdk-codemod's registry via the --from / --to arguments.\n const npxCommand = process.platform === \"win32\" ? \"npx.cmd\" : \"npx\";\n\n const result = spawnSync(\n npxCommand,\n [\n \"@tailor-platform/sdk-codemod@latest\",\n \"--from\",\n options.from,\n \"--to\",\n targetVersion,\n \"--target\",\n projectRoot,\n ...(options.dryRun ? [\"--dry-run\"] : []),\n ],\n {\n cwd: projectRoot,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n encoding: \"utf-8\",\n timeout: 300_000,\n },\n );\n\n if (result.error) {\n throw CLIError({\n message: `Failed to run @tailor-platform/sdk-codemod: ${result.error.message}`,\n suggestion: \"Ensure npx is available and the network is accessible.\",\n command: \"upgrade\",\n });\n }\n\n // Check for non-zero exit without a launch error (e.g. registry/auth/network failures)\n if (result.status !== 0 && !result.stdout?.trim()) {\n throw CLIError({\n message: `@tailor-platform/sdk-codemod exited with code ${result.status}`,\n details: result.stderr?.trim() || \"(no stderr output)\",\n suggestion:\n \"Review the error above. Common causes: invalid version arguments, network issues, or missing package registry access.\",\n command: \"upgrade\",\n });\n }\n\n // Forward captured stderr so users see dry-run diffs and progress messages\n // written by sdk-codemod. stderr is piped (not inherited) so that the error\n // path above can surface it via CLIError, but on success we still need to\n // replay it verbatim to keep the colorized unified diff output visible.\n if (result.stderr) {\n process.stderr.write(result.stderr);\n }\n\n // Step 3: Parse JSON output\n let output: RunOutput;\n try {\n output = JSON.parse(result.stdout);\n } catch {\n throw CLIError({\n message: \"Failed to parse output from @tailor-platform/sdk-codemod\",\n details: result.stdout || \"(empty stdout)\",\n suggestion: \"This is likely a bug. Please report it.\",\n command: \"upgrade\",\n });\n }\n\n // Step 4: Display results\n // Emit structured data on stdout (honors --json via logger.out) and\n // human-readable summary on stderr (via printUpgradeSummary).\n logger.out(output);\n printUpgradeSummary(output, options.dryRun);\n\n if (output.errors.length > 0) {\n throw CLIError({\n message: `Upgrade completed with ${output.errors.length} error(s)`,\n suggestion: \"Review the errors above and re-run the upgrade after fixing the issues.\",\n command: \"upgrade\",\n });\n }\n}\n"],"mappings":";;;;;;;;AAGA,MAAM,mBAAmB;;;;;;;;AASzB,eAAsB,uBAAuB,aAA6C;CACxF,IAAI,MAAM,KAAK,QAAQ,WAAW;CAClC,OAAO,MAAM;EACX,IAAI;GAEF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AO,OAAO;EACxD,YAAY;EACZ,SAAS;CACX,CAAC;AAEL"}
@@ -512,6 +512,10 @@ type BaseGeneratorConfig = ["@tailor-platform/kysely-type", {
512
512
  }] | ["@tailor-platform/seed", {
513
513
  distPath: string;
514
514
  machineUserName?: string | undefined;
515
+ disableIdpUserSync?: {
516
+ userToIdp?: boolean | undefined;
517
+ idpToUser?: boolean | undefined;
518
+ } | undefined;
515
519
  }] | ["@tailor-platform/enum-constants", {
516
520
  distPath: string;
517
521
  }] | ["@tailor-platform/file-utils", {
@@ -1631,4 +1635,4 @@ type TailorAnyDBType = TailorDBType<any, any>;
1631
1635
  type TailorDBInstance<Fields extends Record<string, TailorAnyDBField> = any, User extends object = InferredAttributeMap> = TailorDBType<Fields, User>;
1632
1636
  //#endregion
1633
1637
  export { ResolverInput as $, RelationType as A, FieldMetadata as At, BeforeLoginHookArgs as B, InferredAttributeMap as Bt, ResolverReadyContext as C, SCIMAuthorization as Ct, DefinedDBFieldMetadata as D, ArrayFieldOutput as Dt, DBFieldMetadata as E, TenantProvider as Et, AuthConfig as F, FieldValidateInput as Ft, UserAttributeListKey as G, JsonCompatible as Gt, OAuth2ClientGrantType as H, TailorUser as Ht, AuthConnectionTokenResult as I, Validators as It, ValueOperand as J, output as Jt, UserAttributeMap as K, JsonValue as Kt, AuthExternalConfig as L, AttributeList as Lt, TailorDBServiceInput as M, FieldOutput$1 as Mt, TailorDBType$1 as N, TailorFieldType as Nt, GqlOperationsConfig as O, DefinedFieldMetadata as Ot, TypeSourceInfoEntry as P, TailorToTs as Pt, Resolver as Q, AuthOwnConfig as R, AttributeMap as Rt, ResolverNamespaceData as S, SCIMAttributeMapping as St, TailorDBReadyContext as T, SCIMResource as Tt, SCIMAttributeType as U, unauthenticatedTailorUser as Ut, DefinedAuth as V, TailorInvoker as Vt, UserAttributeKey as W, InferFieldsOutput as Wt, AuthConnectionConfig as X, TailorField as Y, AuthConnectionOAuth2Config as Z, PluginProcessContext as _, IdProvider as _t, NamespacePluginOutput as a, FunctionOperation as at, ExecutorReadyContext as b, SAML as bt, PluginConfigs as c, IncomingWebhookTrigger as ct, PluginGeneratedExecutor as d, TailorDBTrigger as dt, GeneratorConfig as et, PluginGeneratedExecutorWithFile as f, WebhookOperation as ft, PluginOutput as g, IDToken as gt, PluginNamespaceProcessContext as h, BuiltinIdP as ht, TailorDBType as i, ExecutorInput as it, SerialConfig as j, FieldOptions as jt, IndexDef as k, EnumValue as kt, PluginExecutorContext as l, ResolverExecutedTrigger as lt, PluginGeneratedType as m, AuthInvoker as mt, TailorAnyDBType as n, AuthAccessTokenTrigger as nt, Plugin as o, GqlOperation as ot, PluginGeneratedResolver as p, WorkflowOperation as pt, UsernameFieldKey as q, Prettify as qt, TailorDBField as r, Executor as rt, PluginAttachment as s, IdpUserTrigger as st, TailorAnyDBField as t, BaseGeneratorConfig as tt, PluginExecutorContextBase as u, ScheduleTriggerInput as ut, TailorDBTypeForPlugin as v, OAuth2ClientInput as vt, TailorDBNamespaceData as w, SCIMConfig as wt, GeneratorResult as x, SCIMAttribute as xt, TypePluginOutput as y, OIDC as yt, AuthServiceInput as z, InferredAttributeList as zt };
1634
- //# sourceMappingURL=tailor-db-field-Bn8ZC5lK.d.mts.map
1638
+ //# sourceMappingURL=tailor-db-field-4bMLe25-.d.mts.map
@@ -0,0 +1,4 @@
1
+
2
+ import { n as shutdownTelemetry, r as withSpan, t as initTelemetry } from "./telemetry-C1Y56L5E.mjs";
3
+
4
+ export { initTelemetry, shutdownTelemetry };
@@ -82,4 +82,4 @@ async function withSpan(name, fn) {
82
82
 
83
83
  //#endregion
84
84
  export { shutdownTelemetry as n, withSpan as r, initTelemetry as t };
85
- //# sourceMappingURL=telemetry-DcL8Fsm_.mjs.map
85
+ //# sourceMappingURL=telemetry-C1Y56L5E.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"telemetry-DcL8Fsm_.mjs","names":[],"sources":["../src/cli/telemetry/config.ts","../src/cli/telemetry/index.ts"],"sourcesContent":["/**\n * Telemetry configuration parsed from standard OpenTelemetry environment variables.\n * Tracing is enabled when OTEL_EXPORTER_OTLP_ENDPOINT is set.\n */\nexport interface TelemetryConfig {\n readonly enabled: boolean;\n readonly endpoint: string;\n}\n\n/**\n * Parse telemetry configuration from standard OpenTelemetry environment variables.\n * Tracing is enabled when OTEL_EXPORTER_OTLP_ENDPOINT is set.\n * @returns Telemetry configuration\n */\nexport function parseTelemetryConfig(): TelemetryConfig {\n const endpoint = process.env.OTEL_EXPORTER_OTLP_ENDPOINT ?? \"\";\n const enabled = endpoint.length > 0;\n\n return {\n enabled,\n endpoint,\n };\n}\n","import { trace, SpanStatusCode, type Span } from \"@opentelemetry/api\";\nimport { parseTelemetryConfig, type TelemetryConfig } from \"./config\";\n\nlet _config: TelemetryConfig | undefined;\nlet _initialized = false;\nlet _provider: { register: () => void; shutdown: () => Promise<void> } | undefined;\n\n/**\n * Check whether telemetry is currently enabled.\n * @returns true if telemetry has been initialized and is enabled\n */\nexport function isTelemetryEnabled(): boolean {\n return _config?.enabled ?? false;\n}\n\n/**\n * Initialize telemetry if OTEL_EXPORTER_OTLP_ENDPOINT is set.\n * When disabled, this is a no-op with zero overhead beyond reading env vars.\n * @returns Promise that resolves when initialization completes\n */\nexport async function initTelemetry(): Promise<void> {\n if (_initialized) return;\n _initialized = true;\n\n _config = parseTelemetryConfig();\n if (!_config.enabled) return;\n\n // Dynamic imports - only loaded when tracing is enabled\n const [\n { NodeTracerProvider, BatchSpanProcessor },\n { OTLPTraceExporter },\n { resourceFromAttributes },\n { ATTR_SERVICE_NAME, ATTR_SERVICE_VERSION },\n { readPackageJson },\n ] = await Promise.all([\n import(\"@opentelemetry/sdk-trace-node\"),\n import(\"@opentelemetry/exporter-trace-otlp-proto\"),\n import(\"@opentelemetry/resources\"),\n import(\"@opentelemetry/semantic-conventions\"),\n import(\"@/cli/shared/package-json\"),\n ]);\n\n const packageJson = await readPackageJson();\n const version = packageJson.version ?? \"unknown\";\n\n const resource = resourceFromAttributes({\n [ATTR_SERVICE_NAME]: \"tailor-sdk\",\n [ATTR_SERVICE_VERSION]: version,\n });\n\n const exporter = new OTLPTraceExporter({\n url: `${_config.endpoint}/v1/traces`,\n });\n\n _provider = new NodeTracerProvider({\n resource,\n spanProcessors: [new BatchSpanProcessor(exporter)],\n });\n\n _provider.register();\n}\n\n/**\n * Shutdown the telemetry provider, flushing all pending spans.\n * Must be called before process exit to ensure traces are exported.\n * @returns Promise that resolves when shutdown completes\n */\nexport async function shutdownTelemetry(): Promise<void> {\n if (!_provider) return;\n await _provider.shutdown();\n}\n\n/**\n * Execute a function within a new span. Records exceptions and sets span status.\n * When no TracerProvider is registered, the OTel API automatically provides\n * noop spans with zero overhead.\n * @param name - Span name\n * @param fn - Function to execute within the span\n * @returns Result of fn\n */\nexport async function withSpan<T>(name: string, fn: (span: Span) => Promise<T>): Promise<T> {\n const tracer = trace.getTracer(\"tailor-sdk\");\n\n return tracer.startActiveSpan(name, async (span) => {\n try {\n const result = await fn(span);\n span.setStatus({ code: SpanStatusCode.OK });\n return result;\n } catch (error) {\n span.setStatus({ code: SpanStatusCode.ERROR });\n if (error instanceof Error) {\n span.recordException(error);\n }\n throw error;\n } finally {\n span.end();\n }\n });\n}\n"],"mappings":";;;;;;;;;AAcA,SAAgB,uBAAwC;CACtD,MAAM,WAAW,QAAQ,IAAI,+BAA+B;CAG5D,OAAO;EACL,SAHc,SAAS,SAAS;EAIhC;EACD;;;;;AClBH,IAAI;AACJ,IAAI,eAAe;AACnB,IAAI;;;;;;AAeJ,eAAsB,gBAA+B;CACnD,IAAI,cAAc;CAClB,eAAe;CAEf,UAAU,sBAAsB;CAChC,IAAI,CAAC,QAAQ,SAAS;CAGtB,MAAM,CACJ,EAAE,oBAAoB,sBACtB,EAAE,qBACF,EAAE,0BACF,EAAE,mBAAmB,wBACrB,EAAE,qBACA,MAAM,QAAQ,IAAI;EACpB,OAAO;EACP,OAAO;EACP,OAAO;EACP,OAAO;EACP,OAAO;EACR,CAAC;CAGF,MAAM,WAAU,MADU,iBAAiB,EACf,WAAW;CAWvC,YAAY,IAAI,mBAAmB;EACjC,UAVe,uBAAuB;IACrC,oBAAoB;IACpB,uBAAuB;GACzB,CAOS;EACR,gBAAgB,CAAC,IAAI,mBAAmB,IANrB,kBAAkB,EACrC,KAAK,GAAG,QAAQ,SAAS,aAC1B,CAIiD,CAAC,CAAC;EACnD,CAAC;CAEF,UAAU,UAAU;;;;;;;AAQtB,eAAsB,oBAAmC;CACvD,IAAI,CAAC,WAAW;CAChB,MAAM,UAAU,UAAU;;;;;;;;;;AAW5B,eAAsB,SAAY,MAAc,IAA4C;CAG1F,OAFe,MAAM,UAAU,aAElB,CAAC,gBAAgB,MAAM,OAAO,SAAS;EAClD,IAAI;GACF,MAAM,SAAS,MAAM,GAAG,KAAK;GAC7B,KAAK,UAAU,EAAE,MAAM,eAAe,IAAI,CAAC;GAC3C,OAAO;WACA,OAAO;GACd,KAAK,UAAU,EAAE,MAAM,eAAe,OAAO,CAAC;GAC9C,IAAI,iBAAiB,OACnB,KAAK,gBAAgB,MAAM;GAE7B,MAAM;YACE;GACR,KAAK,KAAK;;GAEZ"}
1
+ {"version":3,"file":"telemetry-C1Y56L5E.mjs","names":[],"sources":["../src/cli/telemetry/config.ts","../src/cli/telemetry/index.ts"],"sourcesContent":["/**\n * Telemetry configuration parsed from standard OpenTelemetry environment variables.\n * Tracing is enabled when OTEL_EXPORTER_OTLP_ENDPOINT is set.\n */\nexport interface TelemetryConfig {\n readonly enabled: boolean;\n readonly endpoint: string;\n}\n\n/**\n * Parse telemetry configuration from standard OpenTelemetry environment variables.\n * Tracing is enabled when OTEL_EXPORTER_OTLP_ENDPOINT is set.\n * @returns Telemetry configuration\n */\nexport function parseTelemetryConfig(): TelemetryConfig {\n const endpoint = process.env.OTEL_EXPORTER_OTLP_ENDPOINT ?? \"\";\n const enabled = endpoint.length > 0;\n\n return {\n enabled,\n endpoint,\n };\n}\n","import { trace, SpanStatusCode, type Span } from \"@opentelemetry/api\";\nimport { parseTelemetryConfig, type TelemetryConfig } from \"./config\";\n\nlet _config: TelemetryConfig | undefined;\nlet _initialized = false;\nlet _provider: { register: () => void; shutdown: () => Promise<void> } | undefined;\n\n/**\n * Check whether telemetry is currently enabled.\n * @returns true if telemetry has been initialized and is enabled\n */\nexport function isTelemetryEnabled(): boolean {\n return _config?.enabled ?? false;\n}\n\n/**\n * Initialize telemetry if OTEL_EXPORTER_OTLP_ENDPOINT is set.\n * When disabled, this is a no-op with zero overhead beyond reading env vars.\n * @returns Promise that resolves when initialization completes\n */\nexport async function initTelemetry(): Promise<void> {\n if (_initialized) return;\n _initialized = true;\n\n _config = parseTelemetryConfig();\n if (!_config.enabled) return;\n\n // Dynamic imports - only loaded when tracing is enabled\n const [\n { NodeTracerProvider, BatchSpanProcessor },\n { OTLPTraceExporter },\n { resourceFromAttributes },\n { ATTR_SERVICE_NAME, ATTR_SERVICE_VERSION },\n { readPackageJson },\n ] = await Promise.all([\n import(\"@opentelemetry/sdk-trace-node\"),\n import(\"@opentelemetry/exporter-trace-otlp-proto\"),\n import(\"@opentelemetry/resources\"),\n import(\"@opentelemetry/semantic-conventions\"),\n import(\"@/cli/shared/package-json\"),\n ]);\n\n const packageJson = await readPackageJson();\n const version = packageJson.version ?? \"unknown\";\n\n const resource = resourceFromAttributes({\n [ATTR_SERVICE_NAME]: \"tailor-sdk\",\n [ATTR_SERVICE_VERSION]: version,\n });\n\n const exporter = new OTLPTraceExporter({\n url: `${_config.endpoint}/v1/traces`,\n });\n\n _provider = new NodeTracerProvider({\n resource,\n spanProcessors: [new BatchSpanProcessor(exporter)],\n });\n\n _provider.register();\n}\n\n/**\n * Shutdown the telemetry provider, flushing all pending spans.\n * Must be called before process exit to ensure traces are exported.\n * @returns Promise that resolves when shutdown completes\n */\nexport async function shutdownTelemetry(): Promise<void> {\n if (!_provider) return;\n await _provider.shutdown();\n}\n\n/**\n * Execute a function within a new span. Records exceptions and sets span status.\n * When no TracerProvider is registered, the OTel API automatically provides\n * noop spans with zero overhead.\n * @param name - Span name\n * @param fn - Function to execute within the span\n * @returns Result of fn\n */\nexport async function withSpan<T>(name: string, fn: (span: Span) => Promise<T>): Promise<T> {\n const tracer = trace.getTracer(\"tailor-sdk\");\n\n return tracer.startActiveSpan(name, async (span) => {\n try {\n const result = await fn(span);\n span.setStatus({ code: SpanStatusCode.OK });\n return result;\n } catch (error) {\n span.setStatus({ code: SpanStatusCode.ERROR });\n if (error instanceof Error) {\n span.recordException(error);\n }\n throw error;\n } finally {\n span.end();\n }\n });\n}\n"],"mappings":";;;;;;;;;AAcA,SAAgB,uBAAwC;CACtD,MAAM,WAAW,QAAQ,IAAI,+BAA+B;CAG5D,OAAO;EACL,SAHc,SAAS,SAAS;EAIhC;CACF;AACF;;;;ACnBA,IAAI;AACJ,IAAI,eAAe;AACnB,IAAI;;;;;;AAeJ,eAAsB,gBAA+B;CACnD,IAAI,cAAc;CAClB,eAAe;CAEf,UAAU,qBAAqB;CAC/B,IAAI,CAAC,QAAQ,SAAS;CAGtB,MAAM,CACJ,EAAE,oBAAoB,sBACtB,EAAE,qBACF,EAAE,0BACF,EAAE,mBAAmB,wBACrB,EAAE,qBACA,MAAM,QAAQ,IAAI;EACpB,OAAO;EACP,OAAO;EACP,OAAO;EACP,OAAO;EACP,OAAO;CACT,CAAC;CAGD,MAAM,WAAU,MADU,gBAAgB,GACd,WAAW;CAWvC,YAAY,IAAI,mBAAmB;EACjC,UAVe,uBAAuB;IACrC,oBAAoB;IACpB,uBAAuB;EAC1B,CAOS;EACP,gBAAgB,CAAC,IAAI,mBAAmB,IANrB,kBAAkB,EACrC,KAAK,GAAG,QAAQ,SAAS,YAC3B,CAIiD,CAAC,CAAC;CACnD,CAAC;CAED,UAAU,SAAS;AACrB;;;;;;AAOA,eAAsB,oBAAmC;CACvD,IAAI,CAAC,WAAW;CAChB,MAAM,UAAU,SAAS;AAC3B;;;;;;;;;AAUA,eAAsB,SAAY,MAAc,IAA4C;CAG1F,OAFe,MAAM,UAAU,YAEnB,EAAE,gBAAgB,MAAM,OAAO,SAAS;EAClD,IAAI;GACF,MAAM,SAAS,MAAM,GAAG,IAAI;GAC5B,KAAK,UAAU,EAAE,MAAM,eAAe,GAAG,CAAC;GAC1C,OAAO;EACT,SAAS,OAAO;GACd,KAAK,UAAU,EAAE,MAAM,eAAe,MAAM,CAAC;GAC7C,IAAI,iBAAiB,OACnB,KAAK,gBAAgB,KAAK;GAE5B,MAAM;EACR,UAAU;GACR,KAAK,IAAI;EACX;CACF,CAAC;AACH"}
@@ -1 +1 @@
1
- {"version":3,"file":"types-sir9UPht.mjs","names":[],"sources":["../src/configure/types/type.ts"],"sourcesContent":["import { type AllowedValues, type AllowedValuesOutput, mapAllowedValues } from \"./field\";\nimport type {\n DefinedFieldMetadata,\n TailorFieldType,\n TailorToTs,\n FieldMetadata,\n FieldOptions,\n FieldOutput,\n} from \"@/types/field-types\";\nimport type { InferFieldsOutput, Prettify } from \"@/types/helpers\";\nimport type { TailorField as TailorFieldBase } from \"@/types/tailor-field\";\nimport type { TailorUser } from \"@/types/user\";\nimport type { FieldValidateInput } from \"@/types/validation\";\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\n\n// This helper type intentionally uses `any` as a placeholder for unknown field output.\n// oxlint-disable-next-line no-explicit-any\nexport type TailorAnyField = TailorField<any>;\n\n/**\n * Full TailorField interface with builder methods.\n * Extends the minimal structural interface from types/ with fluent API methods.\n */\nexport interface TailorField<\n Defined extends DefinedFieldMetadata = DefinedFieldMetadata,\n // Generic default output type (kept loose on purpose for library ergonomics).\n // oxlint-disable-next-line no-explicit-any\n Output = any,\n M extends FieldMetadata = FieldMetadata,\n T extends TailorFieldType = TailorFieldType,\n> extends TailorFieldBase<Defined, Output, M, T> {\n readonly fields: Record<string, TailorAnyField>;\n _metadata: M;\n\n /**\n * Set a description for the field\n * @param description - The description text\n * @returns The field with updated metadata\n */\n description<CurrentDefined extends Defined>(\n this: CurrentDefined extends { description: unknown }\n ? never\n : TailorField<CurrentDefined, Output>,\n description: string,\n ): TailorField<Prettify<CurrentDefined & { description: true }>, Output>;\n\n /**\n * Set a custom type name for enum or nested types\n * @param typeName - The custom type name\n * @returns The field with updated metadata\n */\n typeName<CurrentDefined extends Defined>(\n this: CurrentDefined extends { typeName: unknown }\n ? never\n : CurrentDefined extends { type: \"enum\" | \"nested\" }\n ? TailorField<CurrentDefined, Output>\n : never,\n typeName: string,\n ): TailorField<Prettify<CurrentDefined & { typeName: true }>, Output>;\n\n /**\n * Add validation functions to the field\n * @param validate - One or more validation functions\n * @returns The field with updated metadata\n */\n validate<CurrentDefined extends Defined>(\n this: CurrentDefined extends { validate: unknown }\n ? never\n : TailorField<CurrentDefined, Output>,\n ...validate: FieldValidateInput<Output>[]\n ): TailorField<Prettify<CurrentDefined & { validate: true }>, Output>;\n\n /**\n * Parse and validate a value against this field's validation rules\n * Returns StandardSchema Result type with success or failure\n * @param args - Value, context data, and user\n * @returns Validation result\n */\n parse(args: FieldParseArgs): StandardSchemaV1.Result<Output>;\n\n /**\n * Internal parse method that tracks field path for nested validation\n * @private\n * @param args - Parse arguments\n * @returns Validation result\n */\n _parseInternal(args: FieldParseInternalArgs): StandardSchemaV1.Result<Output>;\n}\n\nconst regex = {\n uuid: /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,\n date: /^(?<year>\\d{4})-(?<month>\\d{2})-(?<day>\\d{2})$/,\n time: /^(?<hour>\\d{2}):(?<minute>\\d{2})$/,\n datetime:\n /^(?<year>\\d{4})-(?<month>\\d{2})-(?<day>\\d{2})T(?<hour>\\d{2}):(?<minute>\\d{2}):(?<second>\\d{2})(.(?<millisec>\\d{3}))?Z$/,\n decimal: /^-?(\\d+\\.?\\d*|\\.\\d+)([eE][+-]?\\d+)?$/,\n} as const;\n\ntype FieldParseArgs = {\n value: unknown;\n data: unknown;\n user: TailorUser;\n};\n\ntype FieldValidateValueArgs<T extends TailorFieldType> = {\n value: TailorToTs[T];\n data: unknown;\n user: TailorUser;\n pathArray: string[];\n};\n\ntype FieldParseInternalArgs = {\n // Runtime input is unknown/untyped; we validate and narrow it inside the parser.\n // oxlint-disable-next-line no-explicit-any\n value: any;\n data: unknown;\n user: TailorUser;\n pathArray: string[];\n};\n\n/**\n * Creates a new TailorField instance.\n * @param type - Field type\n * @param options - Field options\n * @param fields - Nested fields for object-like types\n * @param values - Allowed values for enum-like fields\n * @returns A new TailorField\n */\nfunction createTailorField<\n const T extends TailorFieldType,\n const TOptions extends FieldOptions,\n const OutputBase = TailorToTs[T],\n>(\n type: T,\n options?: TOptions,\n fields?: Record<string, TailorAnyField>,\n values?: AllowedValues,\n): TailorField<\n { type: T; array: TOptions extends { array: true } ? true : false },\n FieldOutput<OutputBase, TOptions>\n> {\n const _metadata: FieldMetadata = { required: true };\n\n if (options) {\n if (options.optional === true) {\n _metadata.required = false;\n }\n if (options.array === true) {\n _metadata.array = true;\n }\n }\n if (values) {\n _metadata.allowedValues = mapAllowedValues(values);\n }\n\n /**\n * Validate a single value (not an array element)\n * Used internally for array element validation\n * @param args - Value, context data, and user\n * @returns Array of validation issues\n */\n function validateValue(args: FieldValidateValueArgs<T>): StandardSchemaV1.Issue[] {\n const { value, data, user, pathArray } = args;\n const issues: StandardSchemaV1.Issue[] = [];\n\n // Type-specific validation\n switch (type) {\n case \"string\":\n if (typeof value !== \"string\") {\n issues.push({\n message: `Expected a string: received ${String(value)}`,\n path: pathArray.length > 0 ? pathArray : undefined,\n });\n }\n break;\n\n case \"integer\":\n if (typeof value !== \"number\" || !Number.isInteger(value)) {\n issues.push({\n message: `Expected an integer: received ${String(value)}`,\n path: pathArray.length > 0 ? pathArray : undefined,\n });\n }\n break;\n\n case \"float\":\n if (typeof value !== \"number\" || !Number.isFinite(value)) {\n issues.push({\n message: `Expected a number: received ${String(value)}`,\n path: pathArray.length > 0 ? pathArray : undefined,\n });\n }\n break;\n\n case \"boolean\":\n if (typeof value !== \"boolean\") {\n issues.push({\n message: `Expected a boolean: received ${String(value)}`,\n path: pathArray.length > 0 ? pathArray : undefined,\n });\n }\n break;\n\n case \"uuid\":\n if (typeof value !== \"string\" || !regex.uuid.test(value)) {\n issues.push({\n message: `Expected a valid UUID: received ${String(value)}`,\n path: pathArray.length > 0 ? pathArray : undefined,\n });\n }\n break;\n case \"date\":\n if (typeof value !== \"string\" || !regex.date.test(value)) {\n issues.push({\n message: `Expected to match \"yyyy-MM-dd\" format: received ${String(value)}`,\n path: pathArray.length > 0 ? pathArray : undefined,\n });\n }\n break;\n case \"datetime\":\n if (typeof value !== \"string\" || !regex.datetime.test(value)) {\n issues.push({\n message: `Expected to match ISO format: received ${String(value)}`,\n path: pathArray.length > 0 ? pathArray : undefined,\n });\n }\n break;\n case \"time\":\n if (typeof value !== \"string\" || !regex.time.test(value)) {\n issues.push({\n message: `Expected to match \"HH:mm\" format: received ${String(value)}`,\n path: pathArray.length > 0 ? pathArray : undefined,\n });\n }\n break;\n case \"decimal\":\n if (typeof value !== \"string\" || !regex.decimal.test(value)) {\n issues.push({\n message: `Expected a decimal string: received ${String(value)}`,\n path: pathArray.length > 0 ? pathArray : undefined,\n });\n }\n break;\n\n case \"enum\":\n if (field._metadata.allowedValues) {\n const allowedValues = field._metadata.allowedValues.map((v) => v.value);\n if (typeof value !== \"string\" || !allowedValues.includes(value)) {\n issues.push({\n message: `Must be one of [${allowedValues.join(\", \")}]: received ${String(value)}`,\n path: pathArray.length > 0 ? pathArray : undefined,\n });\n }\n }\n break;\n\n case \"nested\":\n // Validate nested object fields\n if (\n typeof value !== \"object\" ||\n value === null ||\n Array.isArray(value) ||\n value instanceof Date\n ) {\n issues.push({\n message: `Expected an object: received ${String(value)}`,\n path: pathArray.length > 0 ? pathArray : undefined,\n });\n } else if (field.fields && Object.keys(field.fields).length > 0) {\n for (const [fieldName, nestedField] of Object.entries(field.fields)) {\n const fieldValue = value?.[fieldName];\n const result = nestedField._parseInternal({\n value: fieldValue,\n data,\n user,\n pathArray: pathArray.concat(fieldName),\n });\n if (result.issues) {\n issues.push(...result.issues);\n }\n }\n }\n break;\n }\n\n // Custom validation functions\n const validateFns = field._metadata.validate;\n if (validateFns && validateFns.length > 0) {\n for (const validateInput of validateFns) {\n const { fn, message } =\n typeof validateInput === \"function\"\n ? { fn: validateInput, message: \"Validation failed\" }\n : { fn: validateInput[0], message: validateInput[1] };\n\n if (!fn({ value, data, user })) {\n issues.push({\n message,\n path: pathArray.length > 0 ? pathArray : undefined,\n });\n }\n }\n }\n\n return issues;\n }\n\n /**\n * Internal parse method that tracks field path for nested validation\n * @param args - Parse arguments\n * @returns Parse result with value or issues\n */\n function parseInternal(\n args: FieldParseInternalArgs,\n ): StandardSchemaV1.Result<FieldOutput<OutputBase, TOptions>> {\n const { value, data, user, pathArray } = args;\n const issues: StandardSchemaV1.Issue[] = [];\n\n // 1. Check required/optional\n const isNullOrUndefined = value === null || value === undefined;\n if (field._metadata.required && isNullOrUndefined) {\n issues.push({\n message: \"Required field is missing\",\n path: pathArray.length > 0 ? pathArray : undefined,\n });\n return { issues };\n }\n\n // If optional and null/undefined, skip further validation and normalize to null\n if (!field._metadata.required && isNullOrUndefined) {\n return { value: value ?? null };\n }\n\n // 2. Check array type\n if (field._metadata.array) {\n if (!Array.isArray(value)) {\n issues.push({\n message: \"Expected an array\",\n path: pathArray.length > 0 ? pathArray : undefined,\n });\n return { issues };\n }\n\n // Validate each array element (without array flag)\n for (let i = 0; i < value.length; i++) {\n const elementValue = value[i];\n const elementPath = pathArray.concat(`[${i}]`);\n\n // Validate element with same type but without array flag\n const elementIssues = validateValue({\n value: elementValue,\n data,\n user,\n pathArray: elementPath,\n });\n if (elementIssues.length > 0) {\n issues.push(...elementIssues);\n }\n }\n\n if (issues.length > 0) {\n return { issues };\n }\n return { value: value as FieldOutput<OutputBase, TOptions> };\n }\n\n // 3. Type-specific validation and custom validation\n const valueIssues = validateValue({ value, data, user, pathArray });\n issues.push(...valueIssues);\n\n if (issues.length > 0) {\n return { issues };\n }\n\n return { value };\n }\n\n const field: TailorField<\n { type: T; array: TOptions extends { array: true } ? true : false },\n FieldOutput<OutputBase, TOptions>\n > = {\n type,\n fields: fields ?? {},\n _defined: undefined as unknown as {\n type: T;\n array: TOptions extends { array: true } ? true : false;\n },\n _output: undefined as FieldOutput<OutputBase, TOptions>,\n _metadata,\n\n get metadata() {\n return { ...this._metadata };\n },\n\n description(description: string) {\n this._metadata.description = description;\n // Fluent API returns this with updated type\n // oxlint-disable-next-line no-explicit-any\n return this as any;\n },\n\n typeName(typeName: string) {\n this._metadata.typeName = typeName;\n // Fluent API returns this with updated type\n // oxlint-disable-next-line no-explicit-any\n return this as any;\n },\n\n validate(...validateInputs: FieldValidateInput<FieldOutput<OutputBase, TOptions>>[]) {\n this._metadata.validate = validateInputs;\n // Fluent API returns this with updated type\n // oxlint-disable-next-line no-explicit-any\n return this as any;\n },\n\n parse(args: FieldParseArgs): StandardSchemaV1.Result<FieldOutput<OutputBase, TOptions>> {\n return parseInternal({\n value: args.value,\n data: args.data,\n user: args.user,\n pathArray: [],\n });\n },\n\n _parseInternal: parseInternal,\n };\n\n return field;\n}\n\n/**\n * Create a UUID field for resolver input/output.\n * @param options - Field configuration options\n * @returns A UUID field\n * @example t.uuid()\n */\nfunction uuid<const Opt extends FieldOptions>(options?: Opt) {\n return createTailorField(\"uuid\", options);\n}\n\n/**\n * Create a string field for resolver input/output.\n * @param options - Field configuration options\n * @returns A string field\n * @example t.string()\n * @example t.string({ optional: true })\n * @example t.string({ array: true })\n */\nfunction string<const Opt extends FieldOptions>(options?: Opt) {\n return createTailorField(\"string\", options);\n}\n\n/**\n * Create a boolean field for resolver input/output.\n * @param options - Field configuration options\n * @returns A boolean field\n * @example t.bool()\n */\nfunction bool<const Opt extends FieldOptions>(options?: Opt) {\n return createTailorField(\"boolean\", options);\n}\n\n/**\n * Create an integer field for resolver input/output.\n * @param options - Field configuration options\n * @returns An integer field\n * @example t.int()\n */\nfunction int<const Opt extends FieldOptions>(options?: Opt) {\n return createTailorField(\"integer\", options);\n}\n\n/**\n * Create a float field for resolver input/output.\n * @param options - Field configuration options\n * @returns A float field\n * @example t.float()\n */\nfunction float<const Opt extends FieldOptions>(options?: Opt) {\n return createTailorField(\"float\", options);\n}\n\n/**\n * Create a decimal field for resolver input/output (stored as string for precision).\n * @param options - Field configuration options\n * @returns A decimal field\n * @example t.decimal()\n * @example t.decimal({ optional: true })\n */\nfunction decimal<const Opt extends FieldOptions>(options?: Opt) {\n return createTailorField(\"decimal\", options);\n}\n\n/**\n * Create a date field for resolver input/output.\n * @param options - Field configuration options\n * @returns A date field\n * @example t.date()\n */\nfunction date<const Opt extends FieldOptions>(options?: Opt) {\n return createTailorField(\"date\", options);\n}\n\n/**\n * Create a datetime field for resolver input/output.\n * @param options - Field configuration options\n * @returns A datetime field\n * @example t.datetime()\n */\nfunction datetime<const Opt extends FieldOptions>(options?: Opt) {\n return createTailorField(\"datetime\", options);\n}\n\n/**\n * Create a time field for resolver input/output.\n * @param options - Field configuration options\n * @returns A time field\n * @example t.time()\n */\nfunction time<const Opt extends FieldOptions>(options?: Opt) {\n return createTailorField(\"time\", options);\n}\n\n/**\n * Create an enum field for resolver input/output.\n * @param values - Array of allowed string values\n * @param options - Field configuration options\n * @returns An enum field\n * @example t.enum([\"active\", \"inactive\"])\n */\nfunction _enum<const V extends AllowedValues, const Opt extends FieldOptions>(\n values: V,\n options?: Opt,\n): TailorField<\n { type: \"enum\"; array: Opt extends { array: true } ? true : false },\n FieldOutput<AllowedValuesOutput<V>, Opt>\n> {\n return createTailorField<\"enum\", Opt, AllowedValuesOutput<V>>(\"enum\", options, undefined, values);\n}\n\n/**\n * Create a nested object field for resolver input/output.\n * @param fields - Record of field definitions\n * @param options - Field options (optional, array)\n * @returns A nested object field\n * @example\n * // Single object:\n * output: t.object({ name: t.string(), email: t.string() })\n * @example\n * // Array of objects:\n * items: t.object({ name: t.string() }, { array: true })\n */\nfunction object<const F extends Record<string, TailorAnyField>, const Opt extends FieldOptions>(\n fields: F,\n options?: Opt,\n) {\n const objectField = createTailorField(\"nested\", options, fields) as TailorField<\n { type: \"nested\"; array: Opt extends { array: true } ? true : false },\n FieldOutput<InferFieldsOutput<F>, Opt>\n >;\n return objectField;\n}\n\nexport const t = {\n uuid,\n string,\n bool,\n int,\n float,\n decimal,\n date,\n datetime,\n time,\n enum: _enum,\n object,\n};\n"],"mappings":";;;;AAyFA,MAAM,QAAQ;CACZ,MAAM;CACN,MAAM;CACN,MAAM;CACN,UACE;CACF,SAAS;CACV;;;;;;;;;AAgCD,SAAS,kBAKP,MACA,SACA,QACA,QAIA;CACA,MAAM,YAA2B,EAAE,UAAU,MAAM;CAEnD,IAAI,SAAS;EACX,IAAI,QAAQ,aAAa,MACvB,UAAU,WAAW;EAEvB,IAAI,QAAQ,UAAU,MACpB,UAAU,QAAQ;;CAGtB,IAAI,QACF,UAAU,gBAAgB,iBAAiB,OAAO;;;;;;;CASpD,SAAS,cAAc,MAA2D;EAChF,MAAM,EAAE,OAAO,MAAM,MAAM,cAAc;EACzC,MAAM,SAAmC,EAAE;EAG3C,QAAQ,MAAR;GACE,KAAK;IACH,IAAI,OAAO,UAAU,UACnB,OAAO,KAAK;KACV,SAAS,+BAA+B,OAAO,MAAM;KACrD,MAAM,UAAU,SAAS,IAAI,YAAY;KAC1C,CAAC;IAEJ;GAEF,KAAK;IACH,IAAI,OAAO,UAAU,YAAY,CAAC,OAAO,UAAU,MAAM,EACvD,OAAO,KAAK;KACV,SAAS,iCAAiC,OAAO,MAAM;KACvD,MAAM,UAAU,SAAS,IAAI,YAAY;KAC1C,CAAC;IAEJ;GAEF,KAAK;IACH,IAAI,OAAO,UAAU,YAAY,CAAC,OAAO,SAAS,MAAM,EACtD,OAAO,KAAK;KACV,SAAS,+BAA+B,OAAO,MAAM;KACrD,MAAM,UAAU,SAAS,IAAI,YAAY;KAC1C,CAAC;IAEJ;GAEF,KAAK;IACH,IAAI,OAAO,UAAU,WACnB,OAAO,KAAK;KACV,S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AuC,SAAe;CAC7D,OAAO,kBAAkB,UAAU,QAAQ;;;;;;;;AAS7C,SAAS,KAAqC,SAAe;CAC3D,OAAO,kBAAkB,WAAW,QAAQ;;;;;;;;AAS9C,SAAS,IAAoC,SAAe;CAC1D,OAAO,kBAAkB,WAAW,QAAQ;;;;;;;;AAS9C,SAAS,MAAsC,SAAe;CAC5D,OAAO,kBAAkB,SAAS,QAAQ;;;;;;;;;AAU5C,SAAS,QAAwC,SAAe;CAC9D,OAAO,kBAAkB,WAAW,QAAQ;;;;;;;;AAS9C,SAAS,KAAqC,SAAe;CAC3D,OAAO,kBAAkB,QAAQ,QAAQ;;;;;;;;AAS3C,SAAS,SAAyC,SAAe;CAC/D,OAAO,kBAAkB,YAAY,QAAQ;;;;;;;;AAS/C,SAAS,KAAqC,SAAe;CAC3D,OAAO,kBAAkB,QAAQ,QAAQ;;;;;;;;;AAU3C,SAAS,MACP,QACA,SAIA;CACA,OAAO,kBAAuD,QAAQ,SAAS,QAAW,OAAO;;;;;;;;;;;;;;AAenG,SAAS,OACP,QACA,SACA;CAKA,OAJoB,kBAAkB,UAAU,SAAS,OAIvC;;AAGpB,MAAa,IAAI;CACf;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA,MAAM;CACN;CACD"}
1
+ {"version":3,"file":"types-sir9UPht.mjs","names":[],"sources":["../src/configure/types/type.ts"],"sourcesContent":["import { type AllowedValues, type AllowedValuesOutput, mapAllowedValues } from \"./field\";\nimport type {\n DefinedFieldMetadata,\n TailorFieldType,\n TailorToTs,\n FieldMetadata,\n FieldOptions,\n FieldOutput,\n} from \"@/types/field-types\";\nimport type { InferFieldsOutput, Prettify } from \"@/types/helpers\";\nimport type { TailorField as TailorFieldBase } from \"@/types/tailor-field\";\nimport type { TailorUser } from \"@/types/user\";\nimport type { FieldValidateInput } from \"@/types/validation\";\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\n\n// This helper type intentionally uses `any` as a placeholder for unknown field output.\n// oxlint-disable-next-line no-explicit-any\nexport type TailorAnyField = TailorField<any>;\n\n/**\n * Full TailorField interface with builder methods.\n * Extends the minimal structural interface from types/ with fluent API methods.\n */\nexport interface TailorField<\n Defined extends DefinedFieldMetadata = DefinedFieldMetadata,\n // Generic default output type (kept loose on purpose for library ergonomics).\n // oxlint-disable-next-line no-explicit-any\n Output = any,\n M extends FieldMetadata = FieldMetadata,\n T extends TailorFieldType = TailorFieldType,\n> extends TailorFieldBase<Defined, Output, M, T> {\n readonly fields: Record<string, TailorAnyField>;\n _metadata: M;\n\n /**\n * Set a description for the field\n * @param description - The description text\n * @returns The field with updated metadata\n */\n description<CurrentDefined extends Defined>(\n this: CurrentDefined extends { description: unknown }\n ? never\n : TailorField<CurrentDefined, Output>,\n description: string,\n ): TailorField<Prettify<CurrentDefined & { description: true }>, Output>;\n\n /**\n * Set a custom type name for enum or nested types\n * @param typeName - The custom type name\n * @returns The field with updated metadata\n */\n typeName<CurrentDefined extends Defined>(\n this: CurrentDefined extends { typeName: unknown }\n ? never\n : CurrentDefined extends { type: \"enum\" | \"nested\" }\n ? TailorField<CurrentDefined, Output>\n : never,\n typeName: string,\n ): TailorField<Prettify<CurrentDefined & { typeName: true }>, Output>;\n\n /**\n * Add validation functions to the field\n * @param validate - One or more validation functions\n * @returns The field with updated metadata\n */\n validate<CurrentDefined extends Defined>(\n this: CurrentDefined extends { validate: unknown }\n ? never\n : TailorField<CurrentDefined, Output>,\n ...validate: FieldValidateInput<Output>[]\n ): TailorField<Prettify<CurrentDefined & { validate: true }>, Output>;\n\n /**\n * Parse and validate a value against this field's validation rules\n * Returns StandardSchema Result type with success or failure\n * @param args - Value, context data, and user\n * @returns Validation result\n */\n parse(args: FieldParseArgs): StandardSchemaV1.Result<Output>;\n\n /**\n * Internal parse method that tracks field path for nested validation\n * @private\n * @param args - Parse arguments\n * @returns Validation result\n */\n _parseInternal(args: FieldParseInternalArgs): StandardSchemaV1.Result<Output>;\n}\n\nconst regex = {\n uuid: /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,\n date: /^(?<year>\\d{4})-(?<month>\\d{2})-(?<day>\\d{2})$/,\n time: /^(?<hour>\\d{2}):(?<minute>\\d{2})$/,\n datetime:\n /^(?<year>\\d{4})-(?<month>\\d{2})-(?<day>\\d{2})T(?<hour>\\d{2}):(?<minute>\\d{2}):(?<second>\\d{2})(.(?<millisec>\\d{3}))?Z$/,\n decimal: /^-?(\\d+\\.?\\d*|\\.\\d+)([eE][+-]?\\d+)?$/,\n} as const;\n\ntype FieldParseArgs = {\n value: unknown;\n data: unknown;\n user: TailorUser;\n};\n\ntype FieldValidateValueArgs<T extends TailorFieldType> = {\n value: TailorToTs[T];\n data: unknown;\n user: TailorUser;\n pathArray: string[];\n};\n\ntype FieldParseInternalArgs = {\n // Runtime input is unknown/untyped; we validate and narrow it inside the parser.\n // oxlint-disable-next-line no-explicit-any\n value: any;\n data: unknown;\n user: TailorUser;\n pathArray: string[];\n};\n\n/**\n * Creates a new TailorField instance.\n * @param type - Field type\n * @param options - Field options\n * @param fields - Nested fields for object-like types\n * @param values - Allowed values for enum-like fields\n * @returns A new TailorField\n */\nfunction createTailorField<\n const T extends TailorFieldType,\n const TOptions extends FieldOptions,\n const OutputBase = TailorToTs[T],\n>(\n type: T,\n options?: TOptions,\n fields?: Record<string, TailorAnyField>,\n values?: AllowedValues,\n): TailorField<\n { type: T; array: TOptions extends { array: true } ? true : false },\n FieldOutput<OutputBase, TOptions>\n> {\n const _metadata: FieldMetadata = { required: true };\n\n if (options) {\n if (options.optional === true) {\n _metadata.required = false;\n }\n if (options.array === true) {\n _metadata.array = true;\n }\n }\n if (values) {\n _metadata.allowedValues = mapAllowedValues(values);\n }\n\n /**\n * Validate a single value (not an array element)\n * Used internally for array element validation\n * @param args - Value, context data, and user\n * @returns Array of validation issues\n */\n function validateValue(args: FieldValidateValueArgs<T>): StandardSchemaV1.Issue[] {\n const { value, data, user, pathArray } = args;\n const issues: StandardSchemaV1.Issue[] = [];\n\n // Type-specific validation\n switch (type) {\n case \"string\":\n if (typeof value !== \"string\") {\n issues.push({\n message: `Expected a string: received ${String(value)}`,\n path: pathArray.length > 0 ? pathArray : undefined,\n });\n }\n break;\n\n case \"integer\":\n if (typeof value !== \"number\" || !Number.isInteger(value)) {\n issues.push({\n message: `Expected an integer: received ${String(value)}`,\n path: pathArray.length > 0 ? pathArray : undefined,\n });\n }\n break;\n\n case \"float\":\n if (typeof value !== \"number\" || !Number.isFinite(value)) {\n issues.push({\n message: `Expected a number: received ${String(value)}`,\n path: pathArray.length > 0 ? pathArray : undefined,\n });\n }\n break;\n\n case \"boolean\":\n if (typeof value !== \"boolean\") {\n issues.push({\n message: `Expected a boolean: received ${String(value)}`,\n path: pathArray.length > 0 ? pathArray : undefined,\n });\n }\n break;\n\n case \"uuid\":\n if (typeof value !== \"string\" || !regex.uuid.test(value)) {\n issues.push({\n message: `Expected a valid UUID: received ${String(value)}`,\n path: pathArray.length > 0 ? pathArray : undefined,\n });\n }\n break;\n case \"date\":\n if (typeof value !== \"string\" || !regex.date.test(value)) {\n issues.push({\n message: `Expected to match \"yyyy-MM-dd\" format: received ${String(value)}`,\n path: pathArray.length > 0 ? pathArray : undefined,\n });\n }\n break;\n case \"datetime\":\n if (typeof value !== \"string\" || !regex.datetime.test(value)) {\n issues.push({\n message: `Expected to match ISO format: received ${String(value)}`,\n path: pathArray.length > 0 ? pathArray : undefined,\n });\n }\n break;\n case \"time\":\n if (typeof value !== \"string\" || !regex.time.test(value)) {\n issues.push({\n message: `Expected to match \"HH:mm\" format: received ${String(value)}`,\n path: pathArray.length > 0 ? pathArray : undefined,\n });\n }\n break;\n case \"decimal\":\n if (typeof value !== \"string\" || !regex.decimal.test(value)) {\n issues.push({\n message: `Expected a decimal string: received ${String(value)}`,\n path: pathArray.length > 0 ? pathArray : undefined,\n });\n }\n break;\n\n case \"enum\":\n if (field._metadata.allowedValues) {\n const allowedValues = field._metadata.allowedValues.map((v) => v.value);\n if (typeof value !== \"string\" || !allowedValues.includes(value)) {\n issues.push({\n message: `Must be one of [${allowedValues.join(\", \")}]: received ${String(value)}`,\n path: pathArray.length > 0 ? pathArray : undefined,\n });\n }\n }\n break;\n\n case \"nested\":\n // Validate nested object fields\n if (\n typeof value !== \"object\" ||\n value === null ||\n Array.isArray(value) ||\n value instanceof Date\n ) {\n issues.push({\n message: `Expected an object: received ${String(value)}`,\n path: pathArray.length > 0 ? pathArray : undefined,\n });\n } else if (field.fields && Object.keys(field.fields).length > 0) {\n for (const [fieldName, nestedField] of Object.entries(field.fields)) {\n const fieldValue = value?.[fieldName];\n const result = nestedField._parseInternal({\n value: fieldValue,\n data,\n user,\n pathArray: pathArray.concat(fieldName),\n });\n if (result.issues) {\n issues.push(...result.issues);\n }\n }\n }\n break;\n }\n\n // Custom validation functions\n const validateFns = field._metadata.validate;\n if (validateFns && validateFns.length > 0) {\n for (const validateInput of validateFns) {\n const { fn, message } =\n typeof validateInput === \"function\"\n ? { fn: validateInput, message: \"Validation failed\" }\n : { fn: validateInput[0], message: validateInput[1] };\n\n if (!fn({ value, data, user })) {\n issues.push({\n message,\n path: pathArray.length > 0 ? pathArray : undefined,\n });\n }\n }\n }\n\n return issues;\n }\n\n /**\n * Internal parse method that tracks field path for nested validation\n * @param args - Parse arguments\n * @returns Parse result with value or issues\n */\n function parseInternal(\n args: FieldParseInternalArgs,\n ): StandardSchemaV1.Result<FieldOutput<OutputBase, TOptions>> {\n const { value, data, user, pathArray } = args;\n const issues: StandardSchemaV1.Issue[] = [];\n\n // 1. Check required/optional\n const isNullOrUndefined = value === null || value === undefined;\n if (field._metadata.required && isNullOrUndefined) {\n issues.push({\n message: \"Required field is missing\",\n path: pathArray.length > 0 ? pathArray : undefined,\n });\n return { issues };\n }\n\n // If optional and null/undefined, skip further validation and normalize to null\n if (!field._metadata.required && isNullOrUndefined) {\n return { value: value ?? null };\n }\n\n // 2. Check array type\n if (field._metadata.array) {\n if (!Array.isArray(value)) {\n issues.push({\n message: \"Expected an array\",\n path: pathArray.length > 0 ? pathArray : undefined,\n });\n return { issues };\n }\n\n // Validate each array element (without array flag)\n for (let i = 0; i < value.length; i++) {\n const elementValue = value[i];\n const elementPath = pathArray.concat(`[${i}]`);\n\n // Validate element with same type but without array flag\n const elementIssues = validateValue({\n value: elementValue,\n data,\n user,\n pathArray: elementPath,\n });\n if (elementIssues.length > 0) {\n issues.push(...elementIssues);\n }\n }\n\n if (issues.length > 0) {\n return { issues };\n }\n return { value: value as FieldOutput<OutputBase, TOptions> };\n }\n\n // 3. Type-specific validation and custom validation\n const valueIssues = validateValue({ value, data, user, pathArray });\n issues.push(...valueIssues);\n\n if (issues.length > 0) {\n return { issues };\n }\n\n return { value };\n }\n\n const field: TailorField<\n { type: T; array: TOptions extends { array: true } ? true : false },\n FieldOutput<OutputBase, TOptions>\n > = {\n type,\n fields: fields ?? {},\n _defined: undefined as unknown as {\n type: T;\n array: TOptions extends { array: true } ? true : false;\n },\n _output: undefined as FieldOutput<OutputBase, TOptions>,\n _metadata,\n\n get metadata() {\n return { ...this._metadata };\n },\n\n description(description: string) {\n this._metadata.description = description;\n // Fluent API returns this with updated type\n // oxlint-disable-next-line no-explicit-any\n return this as any;\n },\n\n typeName(typeName: string) {\n this._metadata.typeName = typeName;\n // Fluent API returns this with updated type\n // oxlint-disable-next-line no-explicit-any\n return this as any;\n },\n\n validate(...validateInputs: FieldValidateInput<FieldOutput<OutputBase, TOptions>>[]) {\n this._metadata.validate = validateInputs;\n // Fluent API returns this with updated type\n // oxlint-disable-next-line no-explicit-any\n return this as any;\n },\n\n parse(args: FieldParseArgs): StandardSchemaV1.Result<FieldOutput<OutputBase, TOptions>> {\n return parseInternal({\n value: args.value,\n data: args.data,\n user: args.user,\n pathArray: [],\n });\n },\n\n _parseInternal: parseInternal,\n };\n\n return field;\n}\n\n/**\n * Create a UUID field for resolver input/output.\n * @param options - Field configuration options\n * @returns A UUID field\n * @example t.uuid()\n */\nfunction uuid<const Opt extends FieldOptions>(options?: Opt) {\n return createTailorField(\"uuid\", options);\n}\n\n/**\n * Create a string field for resolver input/output.\n * @param options - Field configuration options\n * @returns A string field\n * @example t.string()\n * @example t.string({ optional: true })\n * @example t.string({ array: true })\n */\nfunction string<const Opt extends FieldOptions>(options?: Opt) {\n return createTailorField(\"string\", options);\n}\n\n/**\n * Create a boolean field for resolver input/output.\n * @param options - Field configuration options\n * @returns A boolean field\n * @example t.bool()\n */\nfunction bool<const Opt extends FieldOptions>(options?: Opt) {\n return createTailorField(\"boolean\", options);\n}\n\n/**\n * Create an integer field for resolver input/output.\n * @param options - Field configuration options\n * @returns An integer field\n * @example t.int()\n */\nfunction int<const Opt extends FieldOptions>(options?: Opt) {\n return createTailorField(\"integer\", options);\n}\n\n/**\n * Create a float field for resolver input/output.\n * @param options - Field configuration options\n * @returns A float field\n * @example t.float()\n */\nfunction float<const Opt extends FieldOptions>(options?: Opt) {\n return createTailorField(\"float\", options);\n}\n\n/**\n * Create a decimal field for resolver input/output (stored as string for precision).\n * @param options - Field configuration options\n * @returns A decimal field\n * @example t.decimal()\n * @example t.decimal({ optional: true })\n */\nfunction decimal<const Opt extends FieldOptions>(options?: Opt) {\n return createTailorField(\"decimal\", options);\n}\n\n/**\n * Create a date field for resolver input/output.\n * @param options - Field configuration options\n * @returns A date field\n * @example t.date()\n */\nfunction date<const Opt extends FieldOptions>(options?: Opt) {\n return createTailorField(\"date\", options);\n}\n\n/**\n * Create a datetime field for resolver input/output.\n * @param options - Field configuration options\n * @returns A datetime field\n * @example t.datetime()\n */\nfunction datetime<const Opt extends FieldOptions>(options?: Opt) {\n return createTailorField(\"datetime\", options);\n}\n\n/**\n * Create a time field for resolver input/output.\n * @param options - Field configuration options\n * @returns A time field\n * @example t.time()\n */\nfunction time<const Opt extends FieldOptions>(options?: Opt) {\n return createTailorField(\"time\", options);\n}\n\n/**\n * Create an enum field for resolver input/output.\n * @param values - Array of allowed string values\n * @param options - Field configuration options\n * @returns An enum field\n * @example t.enum([\"active\", \"inactive\"])\n */\nfunction _enum<const V extends AllowedValues, const Opt extends FieldOptions>(\n values: V,\n options?: Opt,\n): TailorField<\n { type: \"enum\"; array: Opt extends { array: true } ? true : false },\n FieldOutput<AllowedValuesOutput<V>, Opt>\n> {\n return createTailorField<\"enum\", Opt, AllowedValuesOutput<V>>(\"enum\", options, undefined, values);\n}\n\n/**\n * Create a nested object field for resolver input/output.\n * @param fields - Record of field definitions\n * @param options - Field options (optional, array)\n * @returns A nested object field\n * @example\n * // Single object:\n * output: t.object({ name: t.string(), email: t.string() })\n * @example\n * // Array of objects:\n * items: t.object({ name: t.string() }, { array: true })\n */\nfunction object<const F extends Record<string, TailorAnyField>, const Opt extends FieldOptions>(\n fields: F,\n options?: Opt,\n) {\n const objectField = createTailorField(\"nested\", options, fields) as TailorField<\n { type: \"nested\"; array: Opt extends { array: true } ? true : false },\n FieldOutput<InferFieldsOutput<F>, Opt>\n >;\n return objectField;\n}\n\nexport const t = {\n uuid,\n string,\n bool,\n int,\n float,\n decimal,\n date,\n datetime,\n time,\n enum: _enum,\n object,\n};\n"],"mappings":";;;;AAyFA,MAAM,QAAQ;CACZ,MAAM;CACN,MAAM;CACN,MAAM;CACN,UACE;CACF,SAAS;AACX;;;;;;;;;AAgCA,SAAS,kBAKP,MACA,SACA,QACA,QAIA;CACA,MAAM,YAA2B,EAAE,UAAU,KAAK;CAElD,IAAI,SAAS;EACX,IAAI,QAAQ,aAAa,MACvB,UAAU,WAAW;EAEvB,IAAI,QAAQ,UAAU,MACpB,UAAU,QAAQ;CAEtB;CACA,IAAI,QACF,UAAU,gBAAgB,iBAAiB,MAAM;;;;;;;CASnD,SAAS,cAAc,MAA2D;EAChF,MAAM,EAAE,OAAO,MAAM,MAAM,cAAc;EACzC,MAAM,SAAmC,CAAC;EAG1C,QAAQ,MAAR;GACE,KAAK;IACH,IAAI,OAAO,UAAU,UACnB,OAAO,KAAK;KACV,SAAS,+BAA+B,OAAO,KAAK;KACpD,MAAM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IxC;AACnB;AAEA,MAAa,IAAI;CACf;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA,MAAM;CACN;AACF"}
@@ -1,7 +1,7 @@
1
1
  /// <reference types="@tailor-platform/function-types" />
2
- import { Vt as TailorInvoker } from "../../tailor-db-field-Bn8ZC5lK.mjs";
3
- import { O as TailorDBType } from "../../workflow.generated-i7PK4fg-.mjs";
4
- import { dt as WORKFLOW_TEST_ENV_KEY, n as output, xt as TailorField } from "../../index-DB8EapT-.mjs";
2
+ import { Vt as TailorInvoker } from "../../tailor-db-field-4bMLe25-.mjs";
3
+ import { O as TailorDBType } from "../../workflow.generated-OYAu_6zX.mjs";
4
+ import { dt as WORKFLOW_TEST_ENV_KEY, n as output, xt as TailorField } from "../../index-C--7W0UO.mjs";
5
5
  import { StandardSchemaV1 } from "@standard-schema/spec";
6
6
 
7
7
  //#region src/utils/test/mock.d.ts
@@ -1,5 +1,5 @@
1
1
 
2
- import { t as WORKFLOW_TEST_ENV_KEY } from "../../job-R5C2Hfcc.mjs";
2
+ import { t as WORKFLOW_TEST_ENV_KEY } from "../../job-M3Avv_SV.mjs";
3
3
  import { pathToFileURL } from "node:url";
4
4
  import * as path from "node:path";
5
5
 
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../../../src/utils/test/mock.ts","../../../src/utils/test/index.ts"],"sourcesContent":["import * as path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport type { TailorInvoker } from \"@/types/user\";\n\ntype MainFunction = (args: Record<string, unknown>) => unknown | Promise<unknown>;\ntype QueryResolver = (query: string, params: unknown[]) => unknown[];\ntype JobHandler = (jobName: string, args: unknown) => unknown;\ntype WaitHandler = (key: string, payload: unknown) => unknown;\ntype ResolveHandler = (\n executionId: string,\n key: string,\n callback: (payload: unknown) => unknown,\n) => Promise<void> | void;\n\ninterface TailordbGlobal {\n tailordb?: {\n Client: new (config: { namespace?: string }) => {\n connect(): Promise<void> | void;\n end(): Promise<void> | void;\n queryObject(\n query: string,\n params?: unknown[],\n ): Promise<{ rows: unknown[] }> | { rows: unknown[] };\n };\n };\n tailor?: {\n workflow: {\n triggerJobFunction: (jobName: string, args: unknown) => unknown;\n wait?: (key: string, payload?: unknown) => unknown;\n resolve?: (\n executionId: string,\n key: string,\n callback: (payload: unknown) => unknown,\n ) => Promise<void>;\n };\n context: {\n getInvoker: () => tailor.context.Invoker | null;\n };\n };\n}\n\ninterface TailorErrorItem {\n message: string;\n path: (string | number)[];\n}\n\ninterface TailorErrorsGlobal {\n TailorErrors?: new (errors: TailorErrorItem[]) => Error;\n}\n\nconst GlobalThis = globalThis as TailordbGlobal & TailorErrorsGlobal;\n\n/**\n * Sets up a mock for `globalThis.tailordb.Client` used in bundled resolver/executor tests.\n * @deprecated Use `tailordbMock` from `@tailor-platform/sdk/vitest` with the `tailor-runtime` environment instead.\n * @param resolver - Optional function to resolve query results. Defaults to returning empty arrays.\n * @returns Object containing arrays of executed queries and created clients for assertions.\n */\nexport function setupTailordbMock(resolver: QueryResolver = () => []): {\n executedQueries: { query: string; params: unknown[] }[];\n createdClients: { namespace?: string; ended: boolean }[];\n} {\n const executedQueries: { query: string; params: unknown[] }[] = [];\n const createdClients: { namespace?: string; ended: boolean }[] = [];\n\n class MockTailordbClient {\n private record: { namespace?: string; ended: boolean };\n\n constructor({ namespace }: { namespace?: string }) {\n this.record = { namespace, ended: false };\n createdClients.push(this.record);\n }\n\n async connect(): Promise<void> {\n /* noop */\n }\n\n async end(): Promise<void> {\n this.record.ended = true;\n }\n\n async queryObject(query: string, params: unknown[] = []): Promise<{ rows: unknown[] }> {\n executedQueries.push({ query, params });\n return { rows: resolver(query, params) ?? [] };\n }\n }\n\n GlobalThis.tailordb = {\n Client: MockTailordbClient,\n } as typeof GlobalThis.tailordb;\n\n return { executedQueries, createdClients };\n}\n\n/**\n * Sets up a mock for `globalThis.tailor.workflow.triggerJobFunction` used in bundled workflow tests.\n * `wait`/`resolve` are stubbed to throw a helpful error directing to `workflowMock`,\n * so mistakenly calling wait without wait-point mocks produces a clear message instead of a TypeError.\n * @deprecated Use `workflowMock` from `@tailor-platform/sdk/vitest` with the `tailor-runtime` environment instead.\n * @param handler - Function that handles triggered job calls and returns results.\n * @returns Object containing an array of triggered jobs for assertions.\n */\nexport function setupWorkflowMock(handler: JobHandler): {\n triggeredJobs: { jobName: string; args: unknown }[];\n} {\n const triggeredJobs: { jobName: string; args: unknown }[] = [];\n\n GlobalThis.tailor = {\n ...GlobalThis.tailor,\n workflow: {\n wait: () => {\n throw new Error(\n \"tailor.workflow.wait is not mocked. Use workflowMock from @tailor-platform/sdk/vitest in tests.\",\n );\n },\n resolve: async () => {\n throw new Error(\n \"tailor.workflow.resolve is not mocked. Use workflowMock from @tailor-platform/sdk/vitest in tests.\",\n );\n },\n ...GlobalThis.tailor?.workflow,\n triggerJobFunction: (jobName: string, args: unknown) => {\n triggeredJobs.push({ jobName, args });\n return handler(jobName, args);\n },\n },\n } as typeof GlobalThis.tailor;\n\n return { triggeredJobs };\n}\n\n/**\n * Sets up a mock for `globalThis.tailor.context.getInvoker` used in bundled\n * resolver/executor/workflow tests.\n * @deprecated With the `tailor-runtime` environment from `@tailor-platform/sdk/vitest`, drive the invoker via `vi.spyOn(globalThis.tailor.context, \"getInvoker\").mockReturnValue(...)` for bundled tests, or pass `invoker` directly to `.body()` when unit-testing resolvers/executors/workflow jobs against the TypeScript source.\n * @param invoker - The `TailorInvoker` value to return, or `null` for anonymous.\n */\nexport function setupInvokerMock(invoker: TailorInvoker): void {\n const raw: tailor.context.Invoker | null = invoker\n ? {\n id: invoker.id,\n type: invoker.type,\n workspaceId: invoker.workspaceId,\n attributes: invoker.attributeList as string[],\n attributeMap: invoker.attributes as Record<string, unknown>,\n }\n : null;\n\n GlobalThis.tailor = {\n ...GlobalThis.tailor,\n context: {\n getInvoker: () => raw,\n },\n } as typeof GlobalThis.tailor;\n}\n\n/**\n * Sets up a mock for `globalThis.TailorErrors` used in bundled resolver tests.\n * Mimics the PF runtime's TailorErrors class that serializes errors with the `TailorErrors: ` prefix.\n * @deprecated Use the `tailor-runtime` environment from `@tailor-platform/sdk/vitest` which auto-injects TailorErrors.\n */\nexport function setupTailorErrorsMock(): void {\n GlobalThis.TailorErrors = class TailorErrors extends Error {\n errors: TailorErrorItem[];\n\n constructor(errors: TailorErrorItem[]) {\n super(`TailorErrors: ${JSON.stringify({ errors })}`);\n this.name = \"TailorErrors\";\n this.errors = errors;\n }\n };\n}\n\n/**\n * Sets up mocks for `globalThis.tailor.workflow.wait` and `.resolve` used in bundled workflow tests.\n * `triggerJobFunction` is stubbed to throw a helpful error directing to `setupWorkflowMock()`,\n * so mistakenly triggering a job without job mocks produces a clear message instead of silently returning undefined.\n * @deprecated Use `workflowMock` from `@tailor-platform/sdk/vitest` with the `tailor-runtime` environment instead.\n * `setWaitHandler` / `setResolveHandler` cover wait/resolve, and `waitCalls` / `resolveCalls` give the same assertion shape.\n * @param config - Optional handlers for wait and resolve calls.\n * @param config.onWait - Handler called when wait is invoked.\n * @param config.onResolve - Handler called when resolve is invoked.\n * @returns Object containing arrays of wait and resolve calls for assertions.\n */\nexport function setupWaitPointMock(config?: { onWait?: WaitHandler; onResolve?: ResolveHandler }): {\n waitCalls: { key: string; payload: unknown }[];\n resolveCalls: { executionId: string; key: string }[];\n} {\n const waitCalls: { key: string; payload: unknown }[] = [];\n const resolveCalls: { executionId: string; key: string }[] = [];\n\n GlobalThis.tailor = {\n ...GlobalThis.tailor,\n workflow: {\n triggerJobFunction: () => {\n throw new Error(\n \"tailor.workflow.triggerJobFunction is not mocked. Use setupWorkflowMock() in tests.\",\n );\n },\n ...GlobalThis.tailor?.workflow,\n wait: (key: string, payload?: unknown) => {\n waitCalls.push({ key, payload });\n return config?.onWait?.(key, payload);\n },\n resolve: async (\n executionId: string,\n key: string,\n callback: (payload: unknown) => unknown,\n ) => {\n resolveCalls.push({ executionId, key });\n await config?.onResolve?.(executionId, key, callback);\n },\n },\n } as typeof GlobalThis.tailor;\n\n return { waitCalls, resolveCalls };\n}\n\n/**\n * Creates a function that imports a bundled JS file and returns its `main` export.\n * Used to test bundled output from `apply --buildOnly`.\n * @param baseDir - Base directory where bundled files are located.\n * @returns An async function that takes a relative path and returns the `main` function.\n * @deprecated This is an SDK-internal testing helper. Bundling integrity is the SDK's responsibility,\n * not the application's — verify your code through unit tests against the TypeScript source and\n * E2E tests against a deployed application instead. This export will be removed in a future release.\n */\nexport function createImportMain(baseDir: string): (relativePath: string) => Promise<MainFunction> {\n return async (relativePath: string): Promise<MainFunction> => {\n const fileUrl = pathToFileURL(path.join(baseDir, relativePath));\n fileUrl.searchParams.set(\"v\", `${Date.now()}-${Math.random()}`);\n const module = await import(fileUrl.href);\n const main = module.main;\n if (typeof main !== \"function\") {\n throw new Error(`Expected \"main\" to be a function in ${relativePath}, got ${typeof main}`);\n }\n return main;\n };\n}\n","import type { output, TailorUser } from \"@/configure\";\nimport type { TailorDBType } from \"@/configure/services/tailordb/schema\";\nimport type { TailorField } from \"@/configure/types/type\";\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\n\nexport { WORKFLOW_TEST_ENV_KEY } from \"@/configure/services/workflow/job\";\nexport {\n setupTailordbMock,\n setupTailorErrorsMock,\n setupWorkflowMock,\n setupInvokerMock,\n setupWaitPointMock,\n createImportMain,\n} from \"./mock\";\n\n/** Represents an unauthenticated user in the Tailor platform. */\nexport const unauthenticatedTailorUser = {\n id: \"00000000-0000-0000-0000-000000000000\",\n type: \"\",\n workspaceId: \"00000000-0000-0000-0000-000000000000\",\n attributes: null,\n attributeList: [],\n} as const satisfies TailorUser;\n\n/**\n * Creates a hook function that processes TailorDB type fields\n * - Uses existing id from data if provided, otherwise generates UUID for id fields\n * - Recursively processes nested types\n * - Executes hooks.create for fields with create hooks\n * @template T - The output type of the hook function\n * @param type - TailorDB type definition\n * @returns A function that transforms input data according to field hooks\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function createTailorDBHook<T extends TailorDBType<any, any>>(type: T) {\n return (data: unknown) => {\n return Object.entries(type.fields).reduce(\n (hooked, [key, value]) => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const field = value as TailorField<any, any, any>;\n if (key === \"id\") {\n // Use existing id from data if provided, otherwise generate new UUID\n const existingId =\n data && typeof data === \"object\" ? (data as Record<string, unknown>)[key] : undefined;\n hooked[key] = existingId ?? crypto.randomUUID();\n } else if (field.type === \"nested\") {\n const nestedValue =\n data && typeof data === \"object\" ? (data as Record<string, unknown>)[key] : undefined;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const nestedHook = createTailorDBHook({ fields: field.fields } as any);\n if (field.metadata.array) {\n // For nested array fields, recurse per element and pass through non-array values\n // (e.g. null/undefined for optional fields) so validation sees the original value.\n hooked[key] = Array.isArray(nestedValue)\n ? nestedValue.map((item) => nestedHook(item))\n : nestedValue;\n } else {\n hooked[key] = nestedHook(nestedValue);\n }\n } else if (field.metadata.hooks?.create) {\n hooked[key] = field.metadata.hooks.create({\n value: (data as Record<string, unknown>)[key],\n data: data,\n user: unauthenticatedTailorUser,\n });\n if (hooked[key] instanceof Date) {\n hooked[key] = hooked[key].toISOString();\n }\n } else if (data && typeof data === \"object\") {\n hooked[key] = (data as Record<string, unknown>)[key];\n }\n return hooked;\n },\n {} as Record<string, unknown>,\n ) as Partial<output<T>>;\n };\n}\n\n/**\n * Creates the standard schema definition for lines-db\n * This returns the first argument for defineSchema with the ~standard section\n * @template T - The output type after validation\n * @param schemaType - TailorDB field schema for validation\n * @param hook - Hook function to transform data before validation\n * @returns Schema object with ~standard section for defineSchema\n */\nexport function createStandardSchema<T = Record<string, unknown>>(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n schemaType: TailorField<any, T>,\n hook: (data: unknown) => Partial<T>,\n) {\n return {\n \"~standard\": {\n version: 1,\n vendor: \"@tailor-platform/sdk\",\n validate: (value: unknown) => {\n const hooked = hook(value);\n const result = schemaType.parse({\n value: hooked,\n data: hooked,\n user: unauthenticatedTailorUser,\n });\n if (result.issues) {\n return result;\n }\n return { value: hooked as T };\n },\n },\n } as const satisfies StandardSchemaV1<T>;\n}\n"],"mappings":";;;;;;AAkDA,MAAM,aAAa;;;;;;;AAQnB,SAAgB,kBAAkB,iBAAgC,EAAE,EAGlE;CACA,MAAM,kBAA0D,EAAE;CAClE,MAAM,iBAA2D,EAAE;CAEnE,MAAM,mBAAmB;EACvB,AAAQ;EAER,YAAY,EAAE,aAAqC;GACjD,KAAK,SAAS;IAAE;IAAW,OAAO;IAAO;GACzC,eAAe,KAAK,KAAK,OAAO;;EAGlC,MAAM,UAAyB;EAI/B,MAAM,MAAqB;GACzB,KAAK,OAAO,QAAQ;;EAGtB,MAAM,YAAY,OAAe,SAAoB,EAAE,EAAgC;GACrF,gBAAgB,KAAK;IAAE;IAAO;IAAQ,CAAC;GACvC,OAAO,EAAE,MAAM,SAAS,OAAO,OAAO,IAAI,EAAE,EAAE;;;CAIlD,WAAW,WAAW,EACpB,QAAQ,oBACT;CAED,OAAO;EAAE;EAAiB;EAAgB;;;;;;;;;;AAW5C,SAAgB,kBAAkB,SAEhC;CACA,MAAM,gBAAsD,EAAE;CAE9D,WAAW,SAAS;EAClB,GAAG,WAAW;EACd,UAAU;GACR,YAAY;IACV,MAAM,IAAI,MACR,kGACD;;GAEH,SAAS,YAAY;IACnB,MAAM,IAAI,MACR,qGACD;;GAEH,GAAG,WAAW,QAAQ;GACtB,qBAAqB,SAAiB,SAAkB;IACtD,cAAc,KAAK;KAAE;KAAS;KAAM,CAAC;IACrC,OAAO,QAAQ,SAAS,KAAK;;GAEhC;EACF;CAED,OAAO,EAAE,eAAe;;;;;;;;AAS1B,SAAgB,iBAAiB,SAA8B;CAC7D,MAAM,MAAqC,UACvC;EACE,IAAI,QAAQ;EACZ,MAAM,QAAQ;EACd,aAAa,QAAQ;EACrB,YAAY,QAAQ;EACpB,cAAc,QAAQ;EACvB,GACD;CAEJ,WAAW,SAAS;EAClB,GAAG,WAAW;EACd,SAAS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,CAAC,QAChC,QAAQ,CAAC,KAAK,WAAW;GAExB,MAAM,QAAQ;GACd,IAAI,QAAQ,MAIV,OAAO,QADL,QAAQ,OAAO,SAAS,WAAY,KAAiC,OAAO,WAClD,OAAO,YAAY;QAC1C,IAAI,MAAM,SAAS,UAAU;IAClC,MAAM,cACJ,QAAQ,OAAO,SAAS,WAAY,KAAiC,OAAO;IAE9E,MAAM,aAAa,mBAAmB,EAAE,QAAQ,MAAM,QAAQ,CAAQ;IACtE,IAAI,MAAM,SAAS,OAGjB,OAAO,OAAO,MAAM,QAAQ,YAAY,GACpC,YAAY,KAAK,SAAS,WAAW,KAAK,CAAC,GAC3C;SAEJ,OAAO,OAAO,WAAW,YAAY;UAElC,IAAI,MAAM,SAAS,OAAO,QAAQ;IACvC,OAAO,OAAO,MAAM,SAAS,MAAM,OAAO;KACxC,OAAQ,KAAiC;KACnC;KACN,MAAM;KACP,CAAC;IACF,IAAI,OAAO,gBAAgB,MACzB,OAAO,OAAO,OAAO,KAAK,aAAa;UAEpC,IAAI,QAAQ,OAAO,SAAS,UACjC,OAAO,OAAQ,KAAiC;GAElD,OAAO;KAET,EAAE,CACH;;;;;;;;;;;AAYL,SAAgB,qBAEd,YACA,MACA;CACA,OAAO,EACL,aAAa;EACX,SAAS;EACT,QAAQ;EACR,WAAW,UAAmB;GAC5B,MAAM,SAAS,KAAK,MAAM;GAC1B,MAAM,SAAS,WAAW,MAAM;IAC9B,OAAO;IACP,MAAM;IACN,MAAM;IACP,CAAC;GACF,IAAI,OAAO,QACT,OAAO;GAET,OAAO,EAAE,OAAO,QAAa;;EAEhC,EACF"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../../../src/utils/test/mock.ts","../../../src/utils/test/index.ts"],"sourcesContent":["import * as path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport type { TailorInvoker } from \"@/types/user\";\n\ntype MainFunction = (args: Record<string, unknown>) => unknown | Promise<unknown>;\ntype QueryResolver = (query: string, params: unknown[]) => unknown[];\ntype JobHandler = (jobName: string, args: unknown) => unknown;\ntype WaitHandler = (key: string, payload: unknown) => unknown;\ntype ResolveHandler = (\n executionId: string,\n key: string,\n callback: (payload: unknown) => unknown,\n) => Promise<void> | void;\n\ninterface TailordbGlobal {\n tailordb?: {\n Client: new (config: { namespace?: string }) => {\n connect(): Promise<void> | void;\n end(): Promise<void> | void;\n queryObject(\n query: string,\n params?: unknown[],\n ): Promise<{ rows: unknown[] }> | { rows: unknown[] };\n };\n };\n tailor?: {\n workflow: {\n triggerJobFunction: (jobName: string, args: unknown) => unknown;\n wait?: (key: string, payload?: unknown) => unknown;\n resolve?: (\n executionId: string,\n key: string,\n callback: (payload: unknown) => unknown,\n ) => Promise<void>;\n };\n context: {\n getInvoker: () => tailor.context.Invoker | null;\n };\n };\n}\n\ninterface TailorErrorItem {\n message: string;\n path: (string | number)[];\n}\n\ninterface TailorErrorsGlobal {\n TailorErrors?: new (errors: TailorErrorItem[]) => Error;\n}\n\nconst GlobalThis = globalThis as TailordbGlobal & TailorErrorsGlobal;\n\n/**\n * Sets up a mock for `globalThis.tailordb.Client` used in bundled resolver/executor tests.\n * @deprecated Use `tailordbMock` from `@tailor-platform/sdk/vitest` with the `tailor-runtime` environment instead.\n * @param resolver - Optional function to resolve query results. Defaults to returning empty arrays.\n * @returns Object containing arrays of executed queries and created clients for assertions.\n */\nexport function setupTailordbMock(resolver: QueryResolver = () => []): {\n executedQueries: { query: string; params: unknown[] }[];\n createdClients: { namespace?: string; ended: boolean }[];\n} {\n const executedQueries: { query: string; params: unknown[] }[] = [];\n const createdClients: { namespace?: string; ended: boolean }[] = [];\n\n class MockTailordbClient {\n private record: { namespace?: string; ended: boolean };\n\n constructor({ namespace }: { namespace?: string }) {\n this.record = { namespace, ended: false };\n createdClients.push(this.record);\n }\n\n async connect(): Promise<void> {\n /* noop */\n }\n\n async end(): Promise<void> {\n this.record.ended = true;\n }\n\n async queryObject(query: string, params: unknown[] = []): Promise<{ rows: unknown[] }> {\n executedQueries.push({ query, params });\n return { rows: resolver(query, params) ?? [] };\n }\n }\n\n GlobalThis.tailordb = {\n Client: MockTailordbClient,\n } as typeof GlobalThis.tailordb;\n\n return { executedQueries, createdClients };\n}\n\n/**\n * Sets up a mock for `globalThis.tailor.workflow.triggerJobFunction` used in bundled workflow tests.\n * `wait`/`resolve` are stubbed to throw a helpful error directing to `workflowMock`,\n * so mistakenly calling wait without wait-point mocks produces a clear message instead of a TypeError.\n * @deprecated Use `workflowMock` from `@tailor-platform/sdk/vitest` with the `tailor-runtime` environment instead.\n * @param handler - Function that handles triggered job calls and returns results.\n * @returns Object containing an array of triggered jobs for assertions.\n */\nexport function setupWorkflowMock(handler: JobHandler): {\n triggeredJobs: { jobName: string; args: unknown }[];\n} {\n const triggeredJobs: { jobName: string; args: unknown }[] = [];\n\n GlobalThis.tailor = {\n ...GlobalThis.tailor,\n workflow: {\n wait: () => {\n throw new Error(\n \"tailor.workflow.wait is not mocked. Use workflowMock from @tailor-platform/sdk/vitest in tests.\",\n );\n },\n resolve: async () => {\n throw new Error(\n \"tailor.workflow.resolve is not mocked. Use workflowMock from @tailor-platform/sdk/vitest in tests.\",\n );\n },\n ...GlobalThis.tailor?.workflow,\n triggerJobFunction: (jobName: string, args: unknown) => {\n triggeredJobs.push({ jobName, args });\n return handler(jobName, args);\n },\n },\n } as typeof GlobalThis.tailor;\n\n return { triggeredJobs };\n}\n\n/**\n * Sets up a mock for `globalThis.tailor.context.getInvoker` used in bundled\n * resolver/executor/workflow tests.\n * @deprecated With the `tailor-runtime` environment from `@tailor-platform/sdk/vitest`, drive the invoker via `vi.spyOn(globalThis.tailor.context, \"getInvoker\").mockReturnValue(...)` for bundled tests, or pass `invoker` directly to `.body()` when unit-testing resolvers/executors/workflow jobs against the TypeScript source.\n * @param invoker - The `TailorInvoker` value to return, or `null` for anonymous.\n */\nexport function setupInvokerMock(invoker: TailorInvoker): void {\n const raw: tailor.context.Invoker | null = invoker\n ? {\n id: invoker.id,\n type: invoker.type,\n workspaceId: invoker.workspaceId,\n attributes: invoker.attributeList as string[],\n attributeMap: invoker.attributes as Record<string, unknown>,\n }\n : null;\n\n GlobalThis.tailor = {\n ...GlobalThis.tailor,\n context: {\n getInvoker: () => raw,\n },\n } as typeof GlobalThis.tailor;\n}\n\n/**\n * Sets up a mock for `globalThis.TailorErrors` used in bundled resolver tests.\n * Mimics the PF runtime's TailorErrors class that serializes errors with the `TailorErrors: ` prefix.\n * @deprecated Use the `tailor-runtime` environment from `@tailor-platform/sdk/vitest` which auto-injects TailorErrors.\n */\nexport function setupTailorErrorsMock(): void {\n GlobalThis.TailorErrors = class TailorErrors extends Error {\n errors: TailorErrorItem[];\n\n constructor(errors: TailorErrorItem[]) {\n super(`TailorErrors: ${JSON.stringify({ errors })}`);\n this.name = \"TailorErrors\";\n this.errors = errors;\n }\n };\n}\n\n/**\n * Sets up mocks for `globalThis.tailor.workflow.wait` and `.resolve` used in bundled workflow tests.\n * `triggerJobFunction` is stubbed to throw a helpful error directing to `setupWorkflowMock()`,\n * so mistakenly triggering a job without job mocks produces a clear message instead of silently returning undefined.\n * @deprecated Use `workflowMock` from `@tailor-platform/sdk/vitest` with the `tailor-runtime` environment instead.\n * `setWaitHandler` / `setResolveHandler` cover wait/resolve, and `waitCalls` / `resolveCalls` give the same assertion shape.\n * @param config - Optional handlers for wait and resolve calls.\n * @param config.onWait - Handler called when wait is invoked.\n * @param config.onResolve - Handler called when resolve is invoked.\n * @returns Object containing arrays of wait and resolve calls for assertions.\n */\nexport function setupWaitPointMock(config?: { onWait?: WaitHandler; onResolve?: ResolveHandler }): {\n waitCalls: { key: string; payload: unknown }[];\n resolveCalls: { executionId: string; key: string }[];\n} {\n const waitCalls: { key: string; payload: unknown }[] = [];\n const resolveCalls: { executionId: string; key: string }[] = [];\n\n GlobalThis.tailor = {\n ...GlobalThis.tailor,\n workflow: {\n triggerJobFunction: () => {\n throw new Error(\n \"tailor.workflow.triggerJobFunction is not mocked. Use setupWorkflowMock() in tests.\",\n );\n },\n ...GlobalThis.tailor?.workflow,\n wait: (key: string, payload?: unknown) => {\n waitCalls.push({ key, payload });\n return config?.onWait?.(key, payload);\n },\n resolve: async (\n executionId: string,\n key: string,\n callback: (payload: unknown) => unknown,\n ) => {\n resolveCalls.push({ executionId, key });\n await config?.onResolve?.(executionId, key, callback);\n },\n },\n } as typeof GlobalThis.tailor;\n\n return { waitCalls, resolveCalls };\n}\n\n/**\n * Creates a function that imports a bundled JS file and returns its `main` export.\n * Used to test bundled output from `apply --buildOnly`.\n * @param baseDir - Base directory where bundled files are located.\n * @returns An async function that takes a relative path and returns the `main` function.\n * @deprecated This is an SDK-internal testing helper. Bundling integrity is the SDK's responsibility,\n * not the application's — verify your code through unit tests against the TypeScript source and\n * E2E tests against a deployed application instead. This export will be removed in a future release.\n */\nexport function createImportMain(baseDir: string): (relativePath: string) => Promise<MainFunction> {\n return async (relativePath: string): Promise<MainFunction> => {\n const fileUrl = pathToFileURL(path.join(baseDir, relativePath));\n fileUrl.searchParams.set(\"v\", `${Date.now()}-${Math.random()}`);\n const module = await import(fileUrl.href);\n const main = module.main;\n if (typeof main !== \"function\") {\n throw new Error(`Expected \"main\" to be a function in ${relativePath}, got ${typeof main}`);\n }\n return main;\n };\n}\n","import type { output, TailorUser } from \"@/configure\";\nimport type { TailorDBType } from \"@/configure/services/tailordb/schema\";\nimport type { TailorField } from \"@/configure/types/type\";\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\n\nexport { WORKFLOW_TEST_ENV_KEY } from \"@/configure/services/workflow/job\";\nexport {\n setupTailordbMock,\n setupTailorErrorsMock,\n setupWorkflowMock,\n setupInvokerMock,\n setupWaitPointMock,\n createImportMain,\n} from \"./mock\";\n\n/** Represents an unauthenticated user in the Tailor platform. */\nexport const unauthenticatedTailorUser = {\n id: \"00000000-0000-0000-0000-000000000000\",\n type: \"\",\n workspaceId: \"00000000-0000-0000-0000-000000000000\",\n attributes: null,\n attributeList: [],\n} as const satisfies TailorUser;\n\n/**\n * Creates a hook function that processes TailorDB type fields\n * - Uses existing id from data if provided, otherwise generates UUID for id fields\n * - Recursively processes nested types\n * - Executes hooks.create for fields with create hooks\n * @template T - The output type of the hook function\n * @param type - TailorDB type definition\n * @returns A function that transforms input data according to field hooks\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function createTailorDBHook<T extends TailorDBType<any, any>>(type: T) {\n return (data: unknown) => {\n return Object.entries(type.fields).reduce(\n (hooked, [key, value]) => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const field = value as TailorField<any, any, any>;\n if (key === \"id\") {\n // Use existing id from data if provided, otherwise generate new UUID\n const existingId =\n data && typeof data === \"object\" ? (data as Record<string, unknown>)[key] : undefined;\n hooked[key] = existingId ?? crypto.randomUUID();\n } else if (field.type === \"nested\") {\n const nestedValue =\n data && typeof data === \"object\" ? (data as Record<string, unknown>)[key] : undefined;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const nestedHook = createTailorDBHook({ fields: field.fields } as any);\n if (field.metadata.array) {\n // For nested array fields, recurse per element and pass through non-array values\n // (e.g. null/undefined for optional fields) so validation sees the original value.\n hooked[key] = Array.isArray(nestedValue)\n ? nestedValue.map((item) => nestedHook(item))\n : nestedValue;\n } else {\n hooked[key] = nestedHook(nestedValue);\n }\n } else if (field.metadata.hooks?.create) {\n hooked[key] = field.metadata.hooks.create({\n value: (data as Record<string, unknown>)[key],\n data: data,\n user: unauthenticatedTailorUser,\n });\n if (hooked[key] instanceof Date) {\n hooked[key] = hooked[key].toISOString();\n }\n } else if (data && typeof data === \"object\") {\n hooked[key] = (data as Record<string, unknown>)[key];\n }\n return hooked;\n },\n {} as Record<string, unknown>,\n ) as Partial<output<T>>;\n };\n}\n\n/**\n * Creates the standard schema definition for lines-db\n * This returns the first argument for defineSchema with the ~standard section\n * @template T - The output type after validation\n * @param schemaType - TailorDB field schema for validation\n * @param hook - Hook function to transform data before validation\n * @returns Schema object with ~standard section for defineSchema\n */\nexport function createStandardSchema<T = Record<string, unknown>>(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n schemaType: TailorField<any, T>,\n hook: (data: unknown) => Partial<T>,\n) {\n return {\n \"~standard\": {\n version: 1,\n vendor: \"@tailor-platform/sdk\",\n validate: (value: unknown) => {\n const hooked = hook(value);\n const result = schemaType.parse({\n value: hooked,\n data: hooked,\n user: unauthenticatedTailorUser,\n });\n if (result.issues) {\n return result;\n }\n return { value: hooked as T };\n },\n },\n } as const satisfies StandardSchemaV1<T>;\n}\n"],"mappings":";;;;;;AAkDA,MAAM,aAAa;;;;;;;AAQnB,SAAgB,kBAAkB,iBAAgC,CAAC,GAGjE;CACA,MAAM,kBAA0D,CAAC;CACjE,MAAM,iBAA2D,CAAC;CAElE,MAAM,mBAAmB;EACvB,AAAQ;EAER,YAAY,EAAE,aAAqC;GACjD,KAAK,SAAS;IAAE;IAAW,OAAO;GAAM;GACxC,eAAe,KAAK,KAAK,MAAM;EACjC;EAEA,MAAM,UAAyB,CAE/B;EAEA,MAAM,MAAqB;GACzB,KAAK,OAAO,QAAQ;EACtB;EAEA,MAAM,YAAY,OAAe,SAAoB,CAAC,GAAiC;GACrF,gBAAgB,KAAK;IAAE;IAAO;GAAO,CAAC;GACtC,OAAO,EAAE,MAAM,SAAS,OAAO,MAAM,KAAK,CAAC,EAAE;EAC/C;CACF;CAEA,WAAW,WAAW,EACpB,QAAQ,mBACV;CAEA,OAAO;EAAE;EAAiB;CAAe;AAC3C;;;;;;;;;AAUA,SAAgB,kBAAkB,SAEhC;CACA,MAAM,gBAAsD,CAAC;CAE7D,WAAW,SAAS;EAClB,GAAG,WAAW;EACd,UAAU;GACR,YAAY;IACV,MAAM,IAAI,MACR,iGACF;GACF;GACA,SAAS,YAAY;IACnB,MAAM,IAAI,MACR,oGACF;GACF;GACA,GAAG,WAAW,QAAQ;GACtB,qBAAqB,SAAiB,SAAkB;IACtD,cAAc,KAAK;KAAE;KAAS;IAAK,CAAC;IACpC,OAAO,QAAQ,SAA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IACN,MAAM;GACR,CAAC;GACD,IAAI,OAAO,QACT,OAAO;GAET,OAAO,EAAE,OAAO,OAAY;EAC9B;CACF,EACF;AACF"}
@@ -1,5 +1,5 @@
1
1
 
2
- import { c as injectMocks, i as cleanupMocks, n as STATE_KEY, t as RUNTIME_FLAG_KEY } from "../mock-BP-9O5On.mjs";
2
+ import { c as injectMocks, i as cleanupMocks, n as STATE_KEY, t as RUNTIME_FLAG_KEY } from "../mock-BfL09ULZ.mjs";
3
3
  import * as globals from "globals";
4
4
 
5
5
  //#region src/vitest/environment.ts
@@ -1 +1 @@
1
- {"version":3,"file":"environment.mjs","names":[],"sources":["../../src/vitest/environment.ts"],"sourcesContent":["import * as globals from \"globals\";\nimport { STATE_KEY, RUNTIME_FLAG_KEY, injectMocks, cleanupMocks } from \"./mock\";\n\n// Normalize the `globals` module shape across CJS/ESM interop so the\n// whitelist build doesn't crash if the default export is unavailable or\n// the keyed sets are missing. Mirrors src/cli/services/tailordb/es-builtins.ts.\ntype GlobalsShape = {\n builtin?: Record<string, boolean>;\n \"shared-node-browser\"?: Record<string, boolean>;\n};\nconst globalsMap: GlobalsShape =\n (globals as unknown as { default?: GlobalsShape }).default ??\n (globals as unknown as GlobalsShape);\n\n// Globals allowed in the Tailor Platform runtime.\n// Mirrors ES_BUILTINS in src/cli/services/tailordb/es-builtins.ts so the\n// emulated runtime exposes exactly the same identifiers as the production\n// platform's free-variable allowlist (ECMAScript builtins + shared\n// Node/browser runtime globals like console, fetch, setTimeout).\n// Platform API mocks (tailor, tailordb, etc.) are not listed here — they are\n// injected by injectMocks() after the whitelist cleanup, so they are never removed.\nconst ALLOWED_GLOBALS = new Set([\n ...Object.keys(globalsMap.builtin ?? {}),\n ...Object.keys(globalsMap[\"shared-node-browser\"] ?? {}),\n\n // Mock state key (lazily populated by mock helpers) and the\n // environment-active flag (set in injectMocks, used by setup.ts to detect\n // the tailor-runtime environment).\n STATE_KEY,\n RUNTIME_FLAG_KEY,\n\n // Used by Vitest internally — not in the platform runtime, but removing breaks the test runner\n \"process\",\n \"require\",\n \"module\",\n \"exports\",\n \"__vitest_worker__\",\n \"__vitest_mocker__\",\n \"VITEST_POOL_ID\",\n]);\n\nexport default {\n name: \"tailor-runtime\",\n viteEnvironment: \"ssr\",\n\n async setup(global: typeof globalThis) {\n const g = global as Record<string, unknown>;\n\n // Save and remove all non-whitelisted globals\n const saved: Record<string, PropertyDescriptor> = {};\n for (const key of Object.getOwnPropertyNames(g)) {\n if (!ALLOWED_GLOBALS.has(key)) {\n const descriptor = Object.getOwnPropertyDescriptor(g, key);\n if (descriptor?.configurable) {\n saved[key] = descriptor;\n delete g[key];\n }\n }\n }\n\n // Inject platform API mocks after whitelist cleanup\n injectMocks(global);\n\n return {\n teardown(global: typeof globalThis) {\n cleanupMocks(global);\n\n // Restore removed globals\n const g = global as Record<string, unknown>;\n for (const [key, descriptor] of Object.entries(saved)) {\n Object.defineProperty(g, key, descriptor);\n }\n },\n };\n },\n};\n"],"mappings":";;;;;AAUA,MAAM,aACH,QAAkD,WAClD;AASH,MAAM,kBAAkB,IAAI,IAAI;CAC9B,GAAG,OAAO,KAAK,WAAW,WAAW,EAAE,CAAC;CACxC,GAAG,OAAO,KAAK,WAAW,0BAA0B,EAAE,CAAC;CAKvD;CACA;CAGA;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC;AAEF,0BAAe;CACb,MAAM;CACN,iBAAiB;CAEjB,MAAM,MAAM,QAA2B;EACrC,MAAM,IAAI;EAGV,MAAM,QAA4C,EAAE;EACpD,KAAK,MAAM,OAAO,OAAO,oBAAoB,EAAE,EAC7C,IAAI,CAAC,gBAAgB,IAAI,IAAI,EAAE;GAC7B,MAAM,aAAa,OAAO,yBAAyB,GAAG,IAAI;GAC1D,IAAI,YAAY,cAAc;IAC5B,MAAM,OAAO;IACb,OAAO,EAAE;;;EAMf,YAAY,OAAO;EAEnB,OAAO,EACL,SAAS,QAA2B;GAClC,aAAa,OAAO;GAGpB,MAAM,IAAI;GACV,KAAK,MAAM,CAAC,KAAK,eAAe,OAAO,QAAQ,MAAM,EACnD,OAAO,eAAe,GAAG,KAAK,WAAW;KAG9C;;CAEJ"}
1
+ {"version":3,"file":"environment.mjs","names":[],"sources":["../../src/vitest/environment.ts"],"sourcesContent":["import * as globals from \"globals\";\nimport { STATE_KEY, RUNTIME_FLAG_KEY, injectMocks, cleanupMocks } from \"./mock\";\n\n// Normalize the `globals` module shape across CJS/ESM interop so the\n// whitelist build doesn't crash if the default export is unavailable or\n// the keyed sets are missing. Mirrors src/cli/services/tailordb/es-builtins.ts.\ntype GlobalsShape = {\n builtin?: Record<string, boolean>;\n \"shared-node-browser\"?: Record<string, boolean>;\n};\nconst globalsMap: GlobalsShape =\n (globals as unknown as { default?: GlobalsShape }).default ??\n (globals as unknown as GlobalsShape);\n\n// Globals allowed in the Tailor Platform runtime.\n// Mirrors ES_BUILTINS in src/cli/services/tailordb/es-builtins.ts so the\n// emulated runtime exposes exactly the same identifiers as the production\n// platform's free-variable allowlist (ECMAScript builtins + shared\n// Node/browser runtime globals like console, fetch, setTimeout).\n// Platform API mocks (tailor, tailordb, etc.) are not listed here — they are\n// injected by injectMocks() after the whitelist cleanup, so they are never removed.\nconst ALLOWED_GLOBALS = new Set([\n ...Object.keys(globalsMap.builtin ?? {}),\n ...Object.keys(globalsMap[\"shared-node-browser\"] ?? {}),\n\n // Mock state key (lazily populated by mock helpers) and the\n // environment-active flag (set in injectMocks, used by setup.ts to detect\n // the tailor-runtime environment).\n STATE_KEY,\n RUNTIME_FLAG_KEY,\n\n // Used by Vitest internally — not in the platform runtime, but removing breaks the test runner\n \"process\",\n \"require\",\n \"module\",\n \"exports\",\n \"__vitest_worker__\",\n \"__vitest_mocker__\",\n \"VITEST_POOL_ID\",\n]);\n\nexport default {\n name: \"tailor-runtime\",\n viteEnvironment: \"ssr\",\n\n async setup(global: typeof globalThis) {\n const g = global as Record<string, unknown>;\n\n // Save and remove all non-whitelisted globals\n const saved: Record<string, PropertyDescriptor> = {};\n for (const key of Object.getOwnPropertyNames(g)) {\n if (!ALLOWED_GLOBALS.has(key)) {\n const descriptor = Object.getOwnPropertyDescriptor(g, key);\n if (descriptor?.configurable) {\n saved[key] = descriptor;\n delete g[key];\n }\n }\n }\n\n // Inject platform API mocks after whitelist cleanup\n injectMocks(global);\n\n return {\n teardown(global: typeof globalThis) {\n cleanupMocks(global);\n\n // Restore removed globals\n const g = global as Record<string, unknown>;\n for (const [key, descriptor] of Object.entries(saved)) {\n Object.defineProperty(g, key, descriptor);\n }\n },\n };\n },\n};\n"],"mappings":";;;;;AAUA,MAAM,aACH,QAAkD,WAClD;AASH,MAAM,kBAAkB,IAAI,IAAI;CAC9B,GAAG,OAAO,KAAK,WAAW,WAAW,CAAC,CAAC;CACvC,GAAG,OAAO,KAAK,WAAW,0BAA0B,CAAC,CAAC;CAKtD;CACA;CAGA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,0BAAe;CACb,MAAM;CACN,iBAAiB;CAEjB,MAAM,MAAM,QAA2B;EACrC,MAAM,IAAI;EAGV,MAAM,QAA4C,CAAC;EACnD,KAAK,MAAM,OAAO,OAAO,oBAAoB,CAAC,GAC5C,IAAI,CAAC,gBAAgB,IAAI,GAAG,GAAG;GAC7B,MAAM,aAAa,OAAO,yBAAyB,GAAG,GAAG;GACzD,IAAI,YAAY,cAAc;IAC5B,MAAM,OAAO;IACb,OAAO,EAAE;GACX;EACF;EAIF,YAAY,MAAM;EAElB,OAAO,EACL,SAAS,QAA2B;GAClC,aAAa,MAAM;GAGnB,MAAM,IAAI;GACV,KAAK,MAAM,CAAC,KAAK,eAAe,OAAO,QAAQ,KAAK,GAClD,OAAO,eAAe,GAAG,KAAK,UAAU;EAE5C,EACF;CACF;AACF"}
@@ -1,5 +1,5 @@
1
1
 
2
- import { a as fileMock, d as workflowMock, l as secretmanagerMock, o as iconvMock, r as authconnectionMock, s as idpMock, u as tailordbMock } from "../mock-BP-9O5On.mjs";
2
+ import { a as fileMock, d as workflowMock, l as secretmanagerMock, o as iconvMock, r as authconnectionMock, s as idpMock, u as tailordbMock } from "../mock-BfL09ULZ.mjs";
3
3
  import { builtinModules } from "node:module";
4
4
  import { fileURLToPath } from "node:url";
5
5
  import { dirname, isAbsolute, matchesGlob, relative, resolve } from "node:path";
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../../src/vitest/blocked-modules.ts","../../src/vitest/plugin.ts","../../src/vitest/index.ts"],"sourcesContent":["/**\n * Blocked Node.js built-in modules and their Web Standard API alternatives.\n *\n * The Tailor Platform runtime only provides Web Standard APIs.\n * These Node.js modules are not available and should be replaced with\n * the suggested alternatives.\n */\nimport { builtinModules } from \"node:module\";\n\n// Suggestions keyed by bare specifier. Lookup also checks with \"node:\" prefix stripped.\nconst SUGGESTIONS: Record<string, string> = {\n crypto: \"Use the Web Crypto API (globalThis.crypto) instead.\",\n buffer: \"Use Uint8Array or ArrayBuffer instead.\",\n fs: \"File system access is not available in the Tailor Platform runtime.\",\n \"fs/promises\": \"File system access is not available in the Tailor Platform runtime.\",\n path: \"Use URL or URLPattern for path manipulation.\",\n http: \"Use the Fetch API (globalThis.fetch) for HTTP requests instead.\",\n https: \"Use the Fetch API (globalThis.fetch) for HTTPS requests instead.\",\n url: \"Use the URL and URLSearchParams Web APIs instead.\",\n util: \"Use Web Standard APIs instead.\",\n stream: \"Use Web Streams API (ReadableStream, WritableStream, TransformStream) instead.\",\n \"stream/web\": \"Use Web Streams API (ReadableStream, WritableStream, TransformStream) instead.\",\n events: \"Use EventTarget instead.\",\n zlib: \"Use CompressionStream and DecompressionStream Web APIs instead.\",\n querystring: \"Use URLSearchParams instead.\",\n string_decoder: \"Use TextDecoder instead.\",\n};\n\nconst BLOCKED_MODULES = new Set<string>();\nfor (const mod of builtinModules) {\n BLOCKED_MODULES.add(mod);\n BLOCKED_MODULES.add(`node:${mod}`);\n}\n\n/**\n * Check if a module specifier is a blocked Node.js built-in.\n * @param specifier - Module specifier to check (e.g. \"node:crypto\", \"fs\")\n * @returns Whether the specifier is blocked\n */\nexport function isBlockedModule(specifier: string): boolean {\n return BLOCKED_MODULES.has(specifier);\n}\n\n/**\n * Get the error message for a blocked module import.\n * @param specifier - Module specifier that was blocked\n * @returns Error message with optional suggestion for the Web Standard API alternative\n */\nexport function getBlockedMessage(specifier: string): string {\n const bare = specifier.startsWith(\"node:\") ? specifier.slice(5) : specifier;\n const suggestion = SUGGESTIONS[bare];\n const base = `\"${specifier}\" is not available in the Tailor Platform runtime.`;\n return suggestion ? `${base} ${suggestion}` : base;\n}\n","import { dirname, isAbsolute, matchesGlob, relative, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { isBlockedModule, getBlockedMessage } from \"./blocked-modules\";\nimport type { Plugin } from \"vitest/config\";\n\nconst DEFAULT_TEST_INCLUDE = [\"**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}\"];\n\ninterface ExportSpecifierNode {\n type?: string;\n exported?: { name?: unknown } | null;\n}\n\ninterface ImportLikeNode {\n type: string;\n start: number;\n end: number;\n source?: { value?: unknown } | null;\n specifiers?: ExportSpecifierNode[] | null;\n exported?: { name?: unknown } | null;\n}\n\nconst IMPORT_LIKE_TYPES = new Set([\n \"ImportDeclaration\",\n \"ExportNamedDeclaration\",\n \"ExportAllDeclaration\",\n]);\n\n// Re-export specifiers (`export { x as Y } from \"...\"`) accept any\n// `IdentifierName` for `Y` — including reserved words like `delete`. But\n// `export const Y = ...` requires a `BindingIdentifier`, which forbids\n// reserved words and the strict-mode-banned `arguments` / `eval`. Synthesizing\n// `export const delete = ...` would yield a syntax error, so we fall back to\n// plain `throw` for unsafe names.\nconst UNSAFE_BINDING_NAMES = new Set([\n // ReservedWord (ES2022+)\n \"break\",\n \"case\",\n \"catch\",\n \"class\",\n \"const\",\n \"continue\",\n \"debugger\",\n \"default\",\n \"delete\",\n \"do\",\n \"else\",\n \"enum\",\n \"export\",\n \"extends\",\n \"false\",\n \"finally\",\n \"for\",\n \"function\",\n \"if\",\n \"import\",\n \"in\",\n \"instanceof\",\n \"new\",\n \"null\",\n \"return\",\n \"super\",\n \"switch\",\n \"this\",\n \"throw\",\n \"true\",\n \"try\",\n \"typeof\",\n \"var\",\n \"void\",\n \"while\",\n \"with\",\n \"yield\",\n // Strict-mode reserved (ESM is always strict)\n \"let\",\n \"static\",\n \"implements\",\n \"interface\",\n \"package\",\n \"private\",\n \"protected\",\n \"public\",\n // Module-specific reserved\n \"await\",\n // Banned as binding names in strict mode\n \"arguments\",\n \"eval\",\n]);\n\nconst ID_START = /^[A-Za-z_$]/;\nconst ID_CONT = /^[A-Za-z0-9_$]*$/;\n\nfunction isSafeBindingName(name: string): boolean {\n if (UNSAFE_BINDING_NAMES.has(name)) return false;\n if (name.length === 0) return false;\n // Restrict to ASCII identifiers — Unicode bindings are valid JS but rare\n // for re-exports of node:* modules, and a regex over the full\n // ID_Start/ID_Continue sets adds substantial weight for marginal gain.\n return ID_START.test(name[0] ?? \"\") && ID_CONT.test(name.slice(1));\n}\n\nfunction buildBlockedReplacement(node: ImportLikeNode, message: string): string {\n // JSON.stringify yields a fully-escaped string literal (including the\n // surrounding quotes), so we don't need to manually handle backslashes,\n // newlines, or other control characters that may appear in the message.\n const literal = JSON.stringify(message);\n const throwStmt = `throw new Error(${literal});`;\n const throwExpr = `(() => { throw new Error(${literal}); })()`;\n\n if (node.type === \"ExportNamedDeclaration\") {\n const specs = node.specifiers ?? [];\n const stubs: string[] = [];\n for (const spec of specs) {\n const exportedName = spec.exported?.name;\n if (typeof exportedName !== \"string\") continue;\n if (exportedName === \"default\") {\n stubs.push(`export default ${throwExpr};`);\n continue;\n }\n // Reserved words can be re-export names but not binding names.\n // Bail to a plain throw rather than emit invalid syntax.\n if (!isSafeBindingName(exportedName)) return throwStmt;\n stubs.push(`export const ${exportedName} = ${throwExpr};`);\n }\n return stubs.length > 0 ? stubs.join(\" \") : throwStmt;\n }\n\n if (node.type === \"ExportAllDeclaration\") {\n const exportedName = node.exported?.name;\n if (typeof exportedName === \"string\" && isSafeBindingName(exportedName)) {\n return `export const ${exportedName} = ${throwExpr};`;\n }\n return throwStmt;\n }\n\n return throwStmt;\n}\n\n/**\n * Vite plugin that blocks Node.js built-in module imports from production code.\n *\n * Uses the `transform` hook to walk the Rollup-provided AST of non-test source\n * files for static `node:*` imports and re-exports.\n * `ImportDeclaration` and bare `export * from \"...\"` are replaced with a\n * `throw new Error(...)` statement so the failure surfaces at evaluation time.\n * `ExportNamedDeclaration` (`export { x, y as z } from \"...\"`) and namespaced\n * `export * as ns from \"...\"` are rewritten to per-binding stub exports\n * (`export const x = (() => { throw new Error(...) })();`). The IIFE throws\n * eagerly during module evaluation (same timing as a top-level `throw`), but\n * preserving the declared export bindings ensures the surfaced error is the\n * actual \"node:* not available\" message rather than an opaque\n * \"missing export\" raised by the loader.\n * Vitest treats `node:*` as external SSR modules (skipping `resolveId`), so\n * source-level transformation is the only reliable interception point.\n * Runs in the default phase (no `enforce: \"pre\"`) so esbuild's TypeScript\n * transform strips `import type` first; only runtime imports reach this hook.\n * Node.js globals not in the platform runtime are removed by the environment (whitelist-based).\n * Test file patterns are read from the resolved Vitest config (`test.include`).\n * Vitest setup files (`test.setupFiles`) and global-setup files\n * (`test.globalSetup`) are also exempted: they run in the test runner host,\n * not in the emulated platform runtime, so they may freely use `node:*`\n * modules (e.g. `node:url` for `pathToFileURL`).\n * @returns Vite plugin\n */\nexport function createBlockPlugin(): Plugin {\n let isTestFile: (id: string) => boolean = () => false;\n let isUserSourceFile: (id: string) => boolean = () => false;\n\n return {\n name: \"tailor-runtime-block-node\",\n\n configResolved(config) {\n type HostFileTestConfig = {\n include?: string[];\n setupFiles?: string | string[];\n globalSetup?: string | string[];\n root?: string;\n };\n const testConfig = (\n config as typeof config & {\n test?: HostFileTestConfig & {\n projects?: { test?: HostFileTestConfig }[];\n };\n }\n ).test;\n const root = testConfig?.root ?? config.root;\n // Setup files and global-setup files run in the Vitest host (not the\n // emulated runtime), so they may freely import node:* modules. Collect\n // them from the top-level config AND from each `test.projects[i]` —\n // per-project setup files run in the host too and would otherwise be\n // transformed as production code, breaking node:* imports inside them.\n const toAbsolutePaths = (value: string | string[] | undefined, baseRoot: string) =>\n (Array.isArray(value) ? value : value ? [value] : []).map((f) => resolve(baseRoot, f));\n const exemptHostFiles = new Set<string>([\n ...toAbsolutePaths(testConfig?.setupFiles, root),\n ...toAbsolutePaths(testConfig?.globalSetup, root),\n ]);\n // Vitest projects can each define their own `test.include` (and root).\n // A project that uses non-default patterns (e.g. `tests/**/*.spec.ts`)\n // must also be considered when classifying test files — otherwise its\n // tests would be treated as production code and have node:* imports\n // rewritten. Build a list of (root, patterns) pairs covering top-level\n // + every project, and accept a file if any pair matches.\n const includePairs: { root: string; patterns: string[] }[] = [\n { root, patterns: testConfig?.include ?? DEFAULT_TEST_INCLUDE },\n ];\n for (const project of testConfig?.projects ?? []) {\n const projectTest = project?.test;\n if (!projectTest) continue;\n const projectRoot = projectTest.root ?? root;\n for (const f of toAbsolutePaths(projectTest.setupFiles, projectRoot)) {\n exemptHostFiles.add(f);\n }\n for (const f of toAbsolutePaths(projectTest.globalSetup, projectRoot)) {\n exemptHostFiles.add(f);\n }\n includePairs.push({\n root: projectRoot,\n patterns: projectTest.include ?? DEFAULT_TEST_INCLUDE,\n });\n }\n isTestFile = (id: string) => {\n if (exemptHostFiles.has(id)) return true;\n return includePairs.some(({ root: r, patterns }) => {\n const candidate = isAbsolute(id) ? relative(r, id) : id;\n return patterns.some((pattern) => matchesGlob(candidate, pattern));\n });\n };\n // Only transform files inside the project root. With pnpm workspaces,\n // dependencies are symlinked and Vite resolves them to absolute paths\n // outside `node_modules`, so the substring check alone is insufficient.\n // Non-absolute ids are Vite-internal: virtual modules (`\\0...`,\n // `virtual:...`), bare specifiers, etc. Those are never user source\n // files and must not be parsed/transformed.\n isUserSourceFile = (id: string) => {\n if (!isAbsolute(id)) return false;\n const rel = relative(root, id);\n return rel !== \"\" && !rel.startsWith(\"..\") && !isAbsolute(rel);\n };\n },\n\n transform(code, id) {\n // Vite can pass ids with query/hash suffixes (e.g. `file.ts?import`,\n // `file.ts?v=hash`). Strip them so exact-path lookups (Set membership,\n // glob matching, absolute-path checks) match what callers configured.\n const queryIdx = id.search(/[?#]/);\n const cleanId = queryIdx === -1 ? id : id.slice(0, queryIdx);\n\n if (isTestFile(cleanId)) return undefined;\n if (cleanId.includes(\"node_modules\")) return undefined;\n if (!isUserSourceFile(cleanId)) return undefined;\n\n let ast: { body: ImportLikeNode[] };\n try {\n ast = this.parse(code) as unknown as { body: ImportLikeNode[] };\n } catch {\n // Not parseable as ESM (e.g. JSON, asset). Let other plugins handle it.\n return undefined;\n }\n\n const replacements: { start: number; end: number; replacement: string }[] = [];\n for (const node of ast.body) {\n if (!IMPORT_LIKE_TYPES.has(node.type)) continue;\n const specifier = node.source?.value;\n if (typeof specifier !== \"string\") continue;\n if (isBlockedModule(specifier)) {\n replacements.push({\n start: node.start,\n end: node.end,\n replacement: buildBlockedReplacement(node, getBlockedMessage(specifier)),\n });\n }\n }\n\n if (replacements.length === 0) return undefined;\n\n let transformed = code;\n for (const r of replacements.sort((a, b) => b.start - a.start)) {\n transformed = transformed.slice(0, r.start) + r.replacement + transformed.slice(r.end);\n }\n\n return { code: transformed, map: null };\n },\n };\n}\n\nconst ENVIRONMENT_NAME = \"tailor-runtime\";\n\n/**\n * Vite plugin that resolves the tailor-runtime environment and injects setup files.\n *\n * Vitest resolves environments starting with \".\" or \"/\" as file paths.\n * This plugin rewrites `environment: \"tailor-runtime\"` to the absolute path\n * of the bundled environment module, both at the top-level and per-project.\n * It also injects the setup file that removes Vitest-dependent globals\n * (like `performance`) per-test via beforeEach/afterEach hooks.\n * @param options - Optional configuration\n * @param options.config - Path to tailor.config.ts to load SecretManager values into mock\n * @returns Vite plugin\n */\nexport function createEnvironmentPlugin(options?: { config?: string }): Plugin {\n const currentDir = dirname(fileURLToPath(import.meta.url));\n const environmentPath = resolve(currentDir, \"environment.mjs\");\n const setupPath = resolve(currentDir, \"setup.mjs\");\n\n return {\n name: \"tailor-runtime-environment\",\n\n config(config) {\n const testConfig = config.test as\n | (Record<string, unknown> & {\n projects?: Record<string, unknown>[];\n setupFiles?: string | string[];\n })\n | undefined;\n\n // Rewrite environment name to absolute path at top-level\n let usesTailorRuntime = false;\n if (testConfig?.environment === ENVIRONMENT_NAME) {\n testConfig.environment = environmentPath;\n usesTailorRuntime = true;\n }\n\n // Rewrite in each project config\n if (testConfig?.projects) {\n for (const project of testConfig.projects) {\n const projectTest = project.test as Record<string, unknown> | undefined;\n if (projectTest?.environment === ENVIRONMENT_NAME) {\n projectTest.environment = environmentPath;\n usesTailorRuntime = true;\n }\n }\n }\n\n // Pass config path to setup.ts via env var (cross-process compatible).\n // Always clear first, then set only when tailor-runtime is actually\n // selected. This makes the env var deterministic across Vite config\n // reloads (watch mode, programmatic re-init): a stale value from a\n // prior iteration cannot make setup.ts load secrets from an old config.\n // The leading `__` marks this as plugin-private, so deleting any\n // pre-existing value is safe.\n delete process.env.__TAILOR_RUNTIME_CONFIG;\n if (options?.config && usesTailorRuntime) {\n // Resolve against the user-provided Vite root when present (falling\n // back to cwd). Vitest projects with a non-cwd `root` would otherwise\n // resolve a relative options.config against the wrong directory.\n const configRoot = (config.root as string | undefined) ?? process.cwd();\n const configAbsPath = resolve(configRoot, options.config);\n process.env.__TAILOR_RUNTIME_CONFIG = configAbsPath;\n }\n\n // Normalize a user-provided string `setupFiles` into an array so Vite's\n // array-concat merge sees both sides as arrays (the string form would\n // otherwise be replaced rather than concatenated by some merge paths).\n // Vite then concatenates the user's array with our [setupPath].\n if (testConfig && typeof testConfig.setupFiles === \"string\") {\n testConfig.setupFiles = [testConfig.setupFiles];\n }\n\n return {\n test: {\n setupFiles: [setupPath],\n },\n };\n },\n };\n}\n","import { createBlockPlugin, createEnvironmentPlugin } from \"./plugin\";\nimport type { Plugin } from \"vitest/config\";\n\n/**\n * Creates Vitest plugins that emulate the Tailor Platform function runtime environment.\n *\n * **Beta:** This API may change in future releases.\n *\n * ## What it does\n *\n * 1. **Node.js module blocking** (transform hook) — Imports of `node:*` modules\n * (and bare builtins like `crypto`, `fs`) in non-test source files are replaced\n * with code that throws an error with a suggestion for the Web Standard API alternative.\n * Test files are exempt and can use `node:*` freely. Test file patterns are read\n * from the resolved Vitest config (`test.include`).\n *\n * 2. **Node.js globals removal** (environment + setup) — Only globals available in the\n * Tailor Platform runtime are kept (whitelist: ECMAScript standard, Web Standard APIs\n * from bootstrap.js, platform mocks). All others (`Buffer`, `global`, `setImmediate`,\n * `__dirname`, `__filename`, etc.) are removed. `performance` is removed per-test\n * via beforeEach/afterEach since Vitest needs it during initialization.\n *\n * 3. **Platform API mocks** (environment) — All platform APIs are auto-injected with\n * control objects: `tailordbMock`, `workflowMock`, `secretmanagerMock`,\n * `authconnectionMock`, `idpMock`, `fileMock`, `iconvMock`. Each provides response\n * configuration, call recording, and reset.\n *\n * 4. **Environment resolution** — Rewrites `environment: \"tailor-runtime\"` to the\n * absolute path of the bundled environment module via the config hook.\n *\n * ## Known limitations\n *\n * - **`process`** and **`require`** are NOT removed or blocked. Vitest's internal\n * runner depends on them. On the real Tailor Platform runtime, they do not exist.\n * - **Dynamic `import()`** of bundled files (via `createImportMain()`) bypasses\n * the transform hook since those files are loaded through Node.js native loader.\n * ## Options\n *\n * - **`config`** — Path to `tailor.config.ts`. Loads `defineSecretManager()` values\n * into `secretmanagerMock` so `getSecret()` returns the configured values.\n * @example\n * ```typescript\n * // vitest.config.ts\n * import { defineConfig } from \"vitest/config\";\n * import { tailorRuntime } from \"@tailor-platform/sdk/vitest\";\n *\n * export default defineConfig({\n * plugins: [tailorRuntime({ config: \"./tailor.config.ts\" })],\n * test: {\n * environment: \"tailor-runtime\",\n * },\n * });\n * ```\n * @param options - Optional configuration\n * @param options.config - Path to tailor.config.ts to load SecretManager values into mock\n * @returns Array of Vite plugins\n */\nexport function tailorRuntime(options?: { config?: string }): Plugin[] {\n return [createBlockPlugin(), createEnvironmentPlugin(options)];\n}\n\nexport {\n tailordbMock,\n workflowMock,\n secretmanagerMock,\n authconnectionMock,\n idpMock,\n fileMock,\n iconvMock,\n} from \"./mock\";\n"],"mappings":";;;;;;;;;;;;;;AAUA,MAAM,cAAsC;CAC1C,QAAQ;CACR,QAAQ;CACR,IAAI;CACJ,eAAe;CACf,MAAM;CACN,MAAM;CACN,OAAO;CACP,KAAK;CACL,MAAM;CACN,QAAQ;CACR,cAAc;CACd,QAAQ;CACR,MAAM;CACN,aAAa;CACb,gBAAgB;CACjB;AAED,MAAM,kCAAkB,IAAI,KAAa;AACzC,KAAK,MAAM,OAAO,gBAAgB;CAChC,gBAAgB,IAAI,IAAI;CACxB,gBAAgB,IAAI,QAAQ,MAAM;;;;;;;AAQpC,SAAgB,gBAAgB,WAA4B;CAC1D,OAAO,gBAAgB,IAAI,UAAU;;;;;;;AAQvC,SAAgB,kBAAkB,WAA2B;CAE3D,MAAM,aAAa,YADN,UAAU,WAAW,QAAQ,GAAG,UAAU,MAAM,EAAE,GAAG;CAElE,MAAM,OAAO,IAAI,UAAU;CAC3B,OAAO,aAAa,GAAG,KAAK,GAAG,eAAe;;;;;AC/ChD,MAAM,uBAAuB,CAAC,mDAAmD;AAgBjF,MAAM,oBAAoB,IAAI,IAAI;CAChC;CACA;CACA;CACD,CAAC;AAQF,MAAM,uBAAuB,IAAI,IAAI;CAEnC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAEA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAEA;CAEA;CACA;CACD,CAAC;AAEF,MAAM,WAAW;AACjB,MAAM,UAAU;AAEhB,SAAS,kBAAkB,MAAuB;CAChD,IAAI,qBAAqB,IAAI,KAAK,EAAE,OAAO;CAC3C,I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AO;IACzD,QAAQ,IAAI,0BAA0B;;GAOxC,IAAI,cAAc,OAAO,WAAW,eAAe,UACjD,WAAW,aAAa,CAAC,WAAW,WAAW;GAGjD,OAAO,EACL,MAAM,EACJ,YAAY,CAAC,UAAU,EACxB,EACF;;EAEJ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACnTH,SAAgB,cAAc,SAAyC;CACrE,OAAO,CAAC,mBAAmB,EAAE,wBAAwB,QAAQ,CAAC"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../../src/vitest/blocked-modules.ts","../../src/vitest/plugin.ts","../../src/vitest/index.ts"],"sourcesContent":["/**\n * Blocked Node.js built-in modules and their Web Standard API alternatives.\n *\n * The Tailor Platform runtime only provides Web Standard APIs.\n * These Node.js modules are not available and should be replaced with\n * the suggested alternatives.\n */\nimport { builtinModules } from \"node:module\";\n\n// Suggestions keyed by bare specifier. Lookup also checks with \"node:\" prefix stripped.\nconst SUGGESTIONS: Record<string, string> = {\n crypto: \"Use the Web Crypto API (globalThis.crypto) instead.\",\n buffer: \"Use Uint8Array or ArrayBuffer instead.\",\n fs: \"File system access is not available in the Tailor Platform runtime.\",\n \"fs/promises\": \"File system access is not available in the Tailor Platform runtime.\",\n path: \"Use URL or URLPattern for path manipulation.\",\n http: \"Use the Fetch API (globalThis.fetch) for HTTP requests instead.\",\n https: \"Use the Fetch API (globalThis.fetch) for HTTPS requests instead.\",\n url: \"Use the URL and URLSearchParams Web APIs instead.\",\n util: \"Use Web Standard APIs instead.\",\n stream: \"Use Web Streams API (ReadableStream, WritableStream, TransformStream) instead.\",\n \"stream/web\": \"Use Web Streams API (ReadableStream, WritableStream, TransformStream) instead.\",\n events: \"Use EventTarget instead.\",\n zlib: \"Use CompressionStream and DecompressionStream Web APIs instead.\",\n querystring: \"Use URLSearchParams instead.\",\n string_decoder: \"Use TextDecoder instead.\",\n};\n\nconst BLOCKED_MODULES = new Set<string>();\nfor (const mod of builtinModules) {\n BLOCKED_MODULES.add(mod);\n BLOCKED_MODULES.add(`node:${mod}`);\n}\n\n/**\n * Check if a module specifier is a blocked Node.js built-in.\n * @param specifier - Module specifier to check (e.g. \"node:crypto\", \"fs\")\n * @returns Whether the specifier is blocked\n */\nexport function isBlockedModule(specifier: string): boolean {\n return BLOCKED_MODULES.has(specifier);\n}\n\n/**\n * Get the error message for a blocked module import.\n * @param specifier - Module specifier that was blocked\n * @returns Error message with optional suggestion for the Web Standard API alternative\n */\nexport function getBlockedMessage(specifier: string): string {\n const bare = specifier.startsWith(\"node:\") ? specifier.slice(5) : specifier;\n const suggestion = SUGGESTIONS[bare];\n const base = `\"${specifier}\" is not available in the Tailor Platform runtime.`;\n return suggestion ? `${base} ${suggestion}` : base;\n}\n","import { dirname, isAbsolute, matchesGlob, relative, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { isBlockedModule, getBlockedMessage } from \"./blocked-modules\";\nimport type { Plugin } from \"vitest/config\";\n\nconst DEFAULT_TEST_INCLUDE = [\"**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}\"];\n\ninterface ExportSpecifierNode {\n type?: string;\n exported?: { name?: unknown } | null;\n}\n\ninterface ImportLikeNode {\n type: string;\n start: number;\n end: number;\n source?: { value?: unknown } | null;\n specifiers?: ExportSpecifierNode[] | null;\n exported?: { name?: unknown } | null;\n}\n\nconst IMPORT_LIKE_TYPES = new Set([\n \"ImportDeclaration\",\n \"ExportNamedDeclaration\",\n \"ExportAllDeclaration\",\n]);\n\n// Re-export specifiers (`export { x as Y } from \"...\"`) accept any\n// `IdentifierName` for `Y` — including reserved words like `delete`. But\n// `export const Y = ...` requires a `BindingIdentifier`, which forbids\n// reserved words and the strict-mode-banned `arguments` / `eval`. Synthesizing\n// `export const delete = ...` would yield a syntax error, so we fall back to\n// plain `throw` for unsafe names.\nconst UNSAFE_BINDING_NAMES = new Set([\n // ReservedWord (ES2022+)\n \"break\",\n \"case\",\n \"catch\",\n \"class\",\n \"const\",\n \"continue\",\n \"debugger\",\n \"default\",\n \"delete\",\n \"do\",\n \"else\",\n \"enum\",\n \"export\",\n \"extends\",\n \"false\",\n \"finally\",\n \"for\",\n \"function\",\n \"if\",\n \"import\",\n \"in\",\n \"instanceof\",\n \"new\",\n \"null\",\n \"return\",\n \"super\",\n \"switch\",\n \"this\",\n \"throw\",\n \"true\",\n \"try\",\n \"typeof\",\n \"var\",\n \"void\",\n \"while\",\n \"with\",\n \"yield\",\n // Strict-mode reserved (ESM is always strict)\n \"let\",\n \"static\",\n \"implements\",\n \"interface\",\n \"package\",\n \"private\",\n \"protected\",\n \"public\",\n // Module-specific reserved\n \"await\",\n // Banned as binding names in strict mode\n \"arguments\",\n \"eval\",\n]);\n\nconst ID_START = /^[A-Za-z_$]/;\nconst ID_CONT = /^[A-Za-z0-9_$]*$/;\n\nfunction isSafeBindingName(name: string): boolean {\n if (UNSAFE_BINDING_NAMES.has(name)) return false;\n if (name.length === 0) return false;\n // Restrict to ASCII identifiers — Unicode bindings are valid JS but rare\n // for re-exports of node:* modules, and a regex over the full\n // ID_Start/ID_Continue sets adds substantial weight for marginal gain.\n return ID_START.test(name[0] ?? \"\") && ID_CONT.test(name.slice(1));\n}\n\nfunction buildBlockedReplacement(node: ImportLikeNode, message: string): string {\n // JSON.stringify yields a fully-escaped string literal (including the\n // surrounding quotes), so we don't need to manually handle backslashes,\n // newlines, or other control characters that may appear in the message.\n const literal = JSON.stringify(message);\n const throwStmt = `throw new Error(${literal});`;\n const throwExpr = `(() => { throw new Error(${literal}); })()`;\n\n if (node.type === \"ExportNamedDeclaration\") {\n const specs = node.specifiers ?? [];\n const stubs: string[] = [];\n for (const spec of specs) {\n const exportedName = spec.exported?.name;\n if (typeof exportedName !== \"string\") continue;\n if (exportedName === \"default\") {\n stubs.push(`export default ${throwExpr};`);\n continue;\n }\n // Reserved words can be re-export names but not binding names.\n // Bail to a plain throw rather than emit invalid syntax.\n if (!isSafeBindingName(exportedName)) return throwStmt;\n stubs.push(`export const ${exportedName} = ${throwExpr};`);\n }\n return stubs.length > 0 ? stubs.join(\" \") : throwStmt;\n }\n\n if (node.type === \"ExportAllDeclaration\") {\n const exportedName = node.exported?.name;\n if (typeof exportedName === \"string\" && isSafeBindingName(exportedName)) {\n return `export const ${exportedName} = ${throwExpr};`;\n }\n return throwStmt;\n }\n\n return throwStmt;\n}\n\n/**\n * Vite plugin that blocks Node.js built-in module imports from production code.\n *\n * Uses the `transform` hook to walk the Rollup-provided AST of non-test source\n * files for static `node:*` imports and re-exports.\n * `ImportDeclaration` and bare `export * from \"...\"` are replaced with a\n * `throw new Error(...)` statement so the failure surfaces at evaluation time.\n * `ExportNamedDeclaration` (`export { x, y as z } from \"...\"`) and namespaced\n * `export * as ns from \"...\"` are rewritten to per-binding stub exports\n * (`export const x = (() => { throw new Error(...) })();`). The IIFE throws\n * eagerly during module evaluation (same timing as a top-level `throw`), but\n * preserving the declared export bindings ensures the surfaced error is the\n * actual \"node:* not available\" message rather than an opaque\n * \"missing export\" raised by the loader.\n * Vitest treats `node:*` as external SSR modules (skipping `resolveId`), so\n * source-level transformation is the only reliable interception point.\n * Runs in the default phase (no `enforce: \"pre\"`) so esbuild's TypeScript\n * transform strips `import type` first; only runtime imports reach this hook.\n * Node.js globals not in the platform runtime are removed by the environment (whitelist-based).\n * Test file patterns are read from the resolved Vitest config (`test.include`).\n * Vitest setup files (`test.setupFiles`) and global-setup files\n * (`test.globalSetup`) are also exempted: they run in the test runner host,\n * not in the emulated platform runtime, so they may freely use `node:*`\n * modules (e.g. `node:url` for `pathToFileURL`).\n * @returns Vite plugin\n */\nexport function createBlockPlugin(): Plugin {\n let isTestFile: (id: string) => boolean = () => false;\n let isUserSourceFile: (id: string) => boolean = () => false;\n\n return {\n name: \"tailor-runtime-block-node\",\n\n configResolved(config) {\n type HostFileTestConfig = {\n include?: string[];\n setupFiles?: string | string[];\n globalSetup?: string | string[];\n root?: string;\n };\n const testConfig = (\n config as typeof config & {\n test?: HostFileTestConfig & {\n projects?: { test?: HostFileTestConfig }[];\n };\n }\n ).test;\n const root = testConfig?.root ?? config.root;\n // Setup files and global-setup files run in the Vitest host (not the\n // emulated runtime), so they may freely import node:* modules. Collect\n // them from the top-level config AND from each `test.projects[i]` —\n // per-project setup files run in the host too and would otherwise be\n // transformed as production code, breaking node:* imports inside them.\n const toAbsolutePaths = (value: string | string[] | undefined, baseRoot: string) =>\n (Array.isArray(value) ? value : value ? [value] : []).map((f) => resolve(baseRoot, f));\n const exemptHostFiles = new Set<string>([\n ...toAbsolutePaths(testConfig?.setupFiles, root),\n ...toAbsolutePaths(testConfig?.globalSetup, root),\n ]);\n // Vitest projects can each define their own `test.include` (and root).\n // A project that uses non-default patterns (e.g. `tests/**/*.spec.ts`)\n // must also be considered when classifying test files — otherwise its\n // tests would be treated as production code and have node:* imports\n // rewritten. Build a list of (root, patterns) pairs covering top-level\n // + every project, and accept a file if any pair matches.\n const includePairs: { root: string; patterns: string[] }[] = [\n { root, patterns: testConfig?.include ?? DEFAULT_TEST_INCLUDE },\n ];\n for (const project of testConfig?.projects ?? []) {\n const projectTest = project?.test;\n if (!projectTest) continue;\n const projectRoot = projectTest.root ?? root;\n for (const f of toAbsolutePaths(projectTest.setupFiles, projectRoot)) {\n exemptHostFiles.add(f);\n }\n for (const f of toAbsolutePaths(projectTest.globalSetup, projectRoot)) {\n exemptHostFiles.add(f);\n }\n includePairs.push({\n root: projectRoot,\n patterns: projectTest.include ?? DEFAULT_TEST_INCLUDE,\n });\n }\n isTestFile = (id: string) => {\n if (exemptHostFiles.has(id)) return true;\n return includePairs.some(({ root: r, patterns }) => {\n const candidate = isAbsolute(id) ? relative(r, id) : id;\n return patterns.some((pattern) => matchesGlob(candidate, pattern));\n });\n };\n // Only transform files inside the project root. With pnpm workspaces,\n // dependencies are symlinked and Vite resolves them to absolute paths\n // outside `node_modules`, so the substring check alone is insufficient.\n // Non-absolute ids are Vite-internal: virtual modules (`\\0...`,\n // `virtual:...`), bare specifiers, etc. Those are never user source\n // files and must not be parsed/transformed.\n isUserSourceFile = (id: string) => {\n if (!isAbsolute(id)) return false;\n const rel = relative(root, id);\n return rel !== \"\" && !rel.startsWith(\"..\") && !isAbsolute(rel);\n };\n },\n\n transform(code, id) {\n // Vite can pass ids with query/hash suffixes (e.g. `file.ts?import`,\n // `file.ts?v=hash`). Strip them so exact-path lookups (Set membership,\n // glob matching, absolute-path checks) match what callers configured.\n const queryIdx = id.search(/[?#]/);\n const cleanId = queryIdx === -1 ? id : id.slice(0, queryIdx);\n\n if (isTestFile(cleanId)) return undefined;\n if (cleanId.includes(\"node_modules\")) return undefined;\n if (!isUserSourceFile(cleanId)) return undefined;\n\n let ast: { body: ImportLikeNode[] };\n try {\n ast = this.parse(code) as unknown as { body: ImportLikeNode[] };\n } catch {\n // Not parseable as ESM (e.g. JSON, asset). Let other plugins handle it.\n return undefined;\n }\n\n const replacements: { start: number; end: number; replacement: string }[] = [];\n for (const node of ast.body) {\n if (!IMPORT_LIKE_TYPES.has(node.type)) continue;\n const specifier = node.source?.value;\n if (typeof specifier !== \"string\") continue;\n if (isBlockedModule(specifier)) {\n replacements.push({\n start: node.start,\n end: node.end,\n replacement: buildBlockedReplacement(node, getBlockedMessage(specifier)),\n });\n }\n }\n\n if (replacements.length === 0) return undefined;\n\n let transformed = code;\n for (const r of replacements.sort((a, b) => b.start - a.start)) {\n transformed = transformed.slice(0, r.start) + r.replacement + transformed.slice(r.end);\n }\n\n return { code: transformed, map: null };\n },\n };\n}\n\nconst ENVIRONMENT_NAME = \"tailor-runtime\";\n\n/**\n * Vite plugin that resolves the tailor-runtime environment and injects setup files.\n *\n * Vitest resolves environments starting with \".\" or \"/\" as file paths.\n * This plugin rewrites `environment: \"tailor-runtime\"` to the absolute path\n * of the bundled environment module, both at the top-level and per-project.\n * It also injects the setup file that removes Vitest-dependent globals\n * (like `performance`) per-test via beforeEach/afterEach hooks.\n * @param options - Optional configuration\n * @param options.config - Path to tailor.config.ts to load SecretManager values into mock\n * @returns Vite plugin\n */\nexport function createEnvironmentPlugin(options?: { config?: string }): Plugin {\n const currentDir = dirname(fileURLToPath(import.meta.url));\n const environmentPath = resolve(currentDir, \"environment.mjs\");\n const setupPath = resolve(currentDir, \"setup.mjs\");\n\n return {\n name: \"tailor-runtime-environment\",\n\n config(config) {\n const testConfig = config.test as\n | (Record<string, unknown> & {\n projects?: Record<string, unknown>[];\n setupFiles?: string | string[];\n })\n | undefined;\n\n // Rewrite environment name to absolute path at top-level\n let usesTailorRuntime = false;\n if (testConfig?.environment === ENVIRONMENT_NAME) {\n testConfig.environment = environmentPath;\n usesTailorRuntime = true;\n }\n\n // Rewrite in each project config\n if (testConfig?.projects) {\n for (const project of testConfig.projects) {\n const projectTest = project.test as Record<string, unknown> | undefined;\n if (projectTest?.environment === ENVIRONMENT_NAME) {\n projectTest.environment = environmentPath;\n usesTailorRuntime = true;\n }\n }\n }\n\n // Pass config path to setup.ts via env var (cross-process compatible).\n // Always clear first, then set only when tailor-runtime is actually\n // selected. This makes the env var deterministic across Vite config\n // reloads (watch mode, programmatic re-init): a stale value from a\n // prior iteration cannot make setup.ts load secrets from an old config.\n // The leading `__` marks this as plugin-private, so deleting any\n // pre-existing value is safe.\n delete process.env.__TAILOR_RUNTIME_CONFIG;\n if (options?.config && usesTailorRuntime) {\n // Resolve against the user-provided Vite root when present (falling\n // back to cwd). Vitest projects with a non-cwd `root` would otherwise\n // resolve a relative options.config against the wrong directory.\n const configRoot = (config.root as string | undefined) ?? process.cwd();\n const configAbsPath = resolve(configRoot, options.config);\n process.env.__TAILOR_RUNTIME_CONFIG = configAbsPath;\n }\n\n // Normalize a user-provided string `setupFiles` into an array so Vite's\n // array-concat merge sees both sides as arrays (the string form would\n // otherwise be replaced rather than concatenated by some merge paths).\n // Vite then concatenates the user's array with our [setupPath].\n if (testConfig && typeof testConfig.setupFiles === \"string\") {\n testConfig.setupFiles = [testConfig.setupFiles];\n }\n\n return {\n test: {\n setupFiles: [setupPath],\n },\n };\n },\n };\n}\n","import { createBlockPlugin, createEnvironmentPlugin } from \"./plugin\";\nimport type { Plugin } from \"vitest/config\";\n\n/**\n * Creates Vitest plugins that emulate the Tailor Platform function runtime environment.\n *\n * **Beta:** This API may change in future releases.\n *\n * ## What it does\n *\n * 1. **Node.js module blocking** (transform hook) — Imports of `node:*` modules\n * (and bare builtins like `crypto`, `fs`) in non-test source files are replaced\n * with code that throws an error with a suggestion for the Web Standard API alternative.\n * Test files are exempt and can use `node:*` freely. Test file patterns are read\n * from the resolved Vitest config (`test.include`).\n *\n * 2. **Node.js globals removal** (environment + setup) — Only globals available in the\n * Tailor Platform runtime are kept (whitelist: ECMAScript standard, Web Standard APIs\n * from bootstrap.js, platform mocks). All others (`Buffer`, `global`, `setImmediate`,\n * `__dirname`, `__filename`, etc.) are removed. `performance` is removed per-test\n * via beforeEach/afterEach since Vitest needs it during initialization.\n *\n * 3. **Platform API mocks** (environment) — All platform APIs are auto-injected with\n * control objects: `tailordbMock`, `workflowMock`, `secretmanagerMock`,\n * `authconnectionMock`, `idpMock`, `fileMock`, `iconvMock`. Each provides response\n * configuration, call recording, and reset.\n *\n * 4. **Environment resolution** — Rewrites `environment: \"tailor-runtime\"` to the\n * absolute path of the bundled environment module via the config hook.\n *\n * ## Known limitations\n *\n * - **`process`** and **`require`** are NOT removed or blocked. Vitest's internal\n * runner depends on them. On the real Tailor Platform runtime, they do not exist.\n * - **Dynamic `import()`** of bundled files (via `createImportMain()`) bypasses\n * the transform hook since those files are loaded through Node.js native loader.\n * ## Options\n *\n * - **`config`** — Path to `tailor.config.ts`. Loads `defineSecretManager()` values\n * into `secretmanagerMock` so `getSecret()` returns the configured values.\n * @example\n * ```typescript\n * // vitest.config.ts\n * import { defineConfig } from \"vitest/config\";\n * import { tailorRuntime } from \"@tailor-platform/sdk/vitest\";\n *\n * export default defineConfig({\n * plugins: [tailorRuntime({ config: \"./tailor.config.ts\" })],\n * test: {\n * environment: \"tailor-runtime\",\n * },\n * });\n * ```\n * @param options - Optional configuration\n * @param options.config - Path to tailor.config.ts to load SecretManager values into mock\n * @returns Array of Vite plugins\n */\nexport function tailorRuntime(options?: { config?: string }): Plugin[] {\n return [createBlockPlugin(), createEnvironmentPlugin(options)];\n}\n\nexport {\n tailordbMock,\n workflowMock,\n secretmanagerMock,\n authconnectionMock,\n idpMock,\n fileMock,\n iconvMock,\n} from \"./mock\";\n"],"mappings":";;;;;;;;;;;;;;AAUA,MAAM,cAAsC;CAC1C,QAAQ;CACR,QAAQ;CACR,IAAI;CACJ,eAAe;CACf,MAAM;CACN,MAAM;CACN,OAAO;CACP,KAAK;CACL,MAAM;CACN,QAAQ;CACR,cAAc;CACd,QAAQ;CACR,MAAM;CACN,aAAa;CACb,gBAAgB;AAClB;AAEA,MAAM,kCAAkB,IAAI,IAAY;AACxC,KAAK,MAAM,OAAO,gBAAgB;CAChC,gBAAgB,IAAI,GAAG;CACvB,gBAAgB,IAAI,QAAQ,KAAK;AACnC;;;;;;AAOA,SAAgB,gBAAgB,WAA4B;CAC1D,OAAO,gBAAgB,IAAI,SAAS;AACtC;;;;;;AAOA,SAAgB,kBAAkB,WAA2B;CAE3D,MAAM,aAAa,YADN,UAAU,WAAW,OAAO,IAAI,UAAU,MAAM,CAAC,IAAI;CAElE,MAAM,OAAO,IAAI,UAAU;CAC3B,OAAO,aAAa,GAAG,KAAK,GAAG,eAAe;AAChD;;;;AChDA,MAAM,uBAAuB,CAAC,kDAAkD;AAgBhF,MAAM,oBAAoB,IAAI,IAAI;CAChC;CACA;CACA;AACF,CAAC;AAQD,MAAM,uBAAuB,IAAI,IAAI;CAEnC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAEA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAEA;CAEA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C5B,IAAI,aAAa,gBAAgB,kBAAkB;KACjD,YAAY,cAAc;KAC1B,oBAAoB;IACtB;GACF;GAUF,OAAO,QAAQ,IAAI;GACnB,IAAI,SAAS,UAAU,mBAAmB;IAKxC,MAAM,gBAAgB,QADF,OAAO,QAA+B,QAAQ,IAAI,GAC5B,QAAQ,MAAM;IACxD,QAAQ,IAAI,0BAA0B;GACxC;GAMA,IAAI,cAAc,OAAO,WAAW,eAAe,UACjD,WAAW,aAAa,CAAC,WAAW,UAAU;GAGhD,OAAO,EACL,MAAM,EACJ,YAAY,CAAC,SAAS,EACxB,EACF;EACF;CACF;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACpTA,SAAgB,cAAc,SAAyC;CACrE,OAAO,CAAC,kBAAkB,GAAG,wBAAwB,OAAO,CAAC;AAC/D"}
@@ -1,5 +1,5 @@
1
1
 
2
- import { l as secretmanagerMock, t as RUNTIME_FLAG_KEY } from "../mock-BP-9O5On.mjs";
2
+ import { l as secretmanagerMock, t as RUNTIME_FLAG_KEY } from "../mock-BfL09ULZ.mjs";
3
3
  import { pathToFileURL } from "node:url";
4
4
  import { afterEach, beforeAll, beforeEach } from "vitest";
5
5
 
@@ -1 +1 @@
1
- {"version":3,"file":"setup.mjs","names":[],"sources":["../../src/vitest/setup.ts"],"sourcesContent":["/**\n * Vitest setup file that removes Node.js globals which Vitest depends on\n * but are not available in the Tailor Platform runtime.\n *\n * These globals cannot be removed in the environment's setup() because\n * Vitest's runner needs them during initialization. By using beforeEach/afterEach,\n * they are only removed during user test code execution.\n *\n * This file is auto-injected by tailorRuntime() but only activates when\n * the tailor-runtime environment is active (detected via __tailorRuntimeActive,\n * a flag set by injectMocks() during environment setup).\n */\nimport { pathToFileURL } from \"node:url\";\nimport { afterEach, beforeAll, beforeEach } from \"vitest\";\nimport { RUNTIME_FLAG_KEY, secretmanagerMock } from \"./mock\";\n\n// Globals that Vitest internals depend on but don't exist in the platform runtime.\n// Removed before each test, restored after.\nconst BLOCKED_GLOBALS = [\"performance\"] as const;\n\ntype SavedGlobals = Record<string, PropertyDescriptor | undefined>;\n\n/**\n * Reference-counted lifecycle for blocked globals.\n *\n * Concurrent tests in the same Vitest worker (`test.concurrent`) interleave\n * their beforeEach/afterEach hooks: a naive `let saved` shared across hooks\n * would let one test's `afterEach` restore `performance` mid-execution of\n * another test. Reference counting keeps the globals removed for the union\n * of all overlapping test scopes — the property is removed on first entry\n * and restored only when the last test exits.\n * @returns Lifecycle hooks\n */\nexport function createBlockedGlobalsLifecycle(): {\n enter: (globalObj: Record<string, unknown>, keys: readonly string[]) => void;\n exit: (globalObj: Record<string, unknown>) => void;\n readonly active: number;\n} {\n let active = 0;\n let saved: SavedGlobals = {};\n return {\n get active() {\n return active;\n },\n enter(globalObj, keys) {\n if (active === 0) saved = removeBlockedGlobals(globalObj, keys);\n active++;\n },\n exit(globalObj) {\n // Defensive guard — in practice every `enter` is paired with `exit`,\n // but a hook crash could desync the counter.\n if (active === 0) return;\n active--;\n if (active === 0) {\n restoreBlockedGlobals(globalObj, saved);\n saved = {};\n }\n },\n };\n}\n\nconst lifecycle = createBlockedGlobalsLifecycle();\n\nfunction isTailorRuntime(): boolean {\n return RUNTIME_FLAG_KEY in globalThis;\n}\n\n/**\n * Extract a vault store from a secrets-shaped value.\n *\n * `defineSecretManager()` returns `{ vaults, options, get, getAll }` (get/getAll\n * are non-enumerable). When that shape is present, the actual vaults live\n * under `.vaults`. Otherwise fall back to treating the object itself as the\n * vault map (for plain object configs).\n * @param secrets - Value from `appConfig.secrets` or `config.secrets`\n * @returns Vault store, or null if the value is unusable\n */\nexport function extractVaultStore(secrets: unknown): Record<string, Record<string, string>> | null {\n if (!secrets || typeof secrets !== \"object\") return null;\n\n const source =\n \"vaults\" in secrets &&\n typeof (secrets as { vaults?: unknown }).vaults === \"object\" &&\n (secrets as { vaults?: unknown }).vaults !== null\n ? ((secrets as { vaults: Record<string, unknown> }).vaults as Record<string, unknown>)\n : (secrets as Record<string, unknown>);\n\n const store: Record<string, Record<string, string>> = {};\n for (const [vaultName, vaultData] of Object.entries(source)) {\n if (typeof vaultData === \"object\" && vaultData !== null) {\n store[vaultName] = { ...(vaultData as Record<string, string>) };\n }\n }\n return Object.keys(store).length > 0 ? store : null;\n}\n\n/**\n * Load and parse secrets from a tailor.config.ts file.\n *\n * Returns a vault store on success, or `null` on any failure (missing config,\n * import failure, missing/invalid secrets shape). Errors are swallowed so a\n * misconfigured project still boots — the user can set secrets manually via\n * `secretmanagerMock.setSecrets()`.\n * @param configPath - Absolute path to tailor.config.ts\n * @returns Vault store keyed by vault name, or null if unavailable\n */\nexport async function loadSecretsFromConfig(\n configPath: string,\n): Promise<Record<string, Record<string, string>> | null> {\n try {\n // Convert to file URL so absolute Windows paths (e.g. \"C:\\...\") parse as\n // valid ESM specifiers.\n const config = await import(pathToFileURL(configPath).href);\n const appConfig = config.default;\n const secrets = appConfig?.secrets ?? config.secrets;\n return extractVaultStore(secrets);\n } catch {\n return null;\n }\n}\n\n// Load secrets from tailor.config.ts if config path is provided via env var\nbeforeAll(async () => {\n if (!isTailorRuntime()) return;\n const configPath = process.env.__TAILOR_RUNTIME_CONFIG;\n if (!configPath) return;\n\n const store = await loadSecretsFromConfig(configPath);\n if (store) {\n secretmanagerMock.setSecrets(store);\n }\n});\n\n/**\n * Remove the given globals from `globalObj`, returning the descriptors that\n * were actually deleted so `restoreBlockedGlobals` can put them back.\n *\n * Mirrors environment.ts: non-configurable properties are skipped instead of\n * deleted, so `delete` never throws in strict-mode runtimes that lock them\n * down. Only properties whose deletion actually happened are returned, so the\n * caller restores nothing for the skipped case.\n * @param globalObj - Target object (typically `globalThis`)\n * @param keys - Property names to remove\n * @returns Map of removed descriptors keyed by property name\n */\nexport function removeBlockedGlobals(\n globalObj: Record<string, unknown>,\n keys: readonly string[],\n): SavedGlobals {\n const removed: SavedGlobals = {};\n for (const key of keys) {\n const descriptor = Object.getOwnPropertyDescriptor(globalObj, key);\n if (descriptor?.configurable) {\n removed[key] = descriptor;\n delete globalObj[key];\n }\n }\n return removed;\n}\n\n/**\n * Restore previously-removed globals onto `globalObj` from a `SavedGlobals`\n * map produced by `removeBlockedGlobals`.\n * @param globalObj - Target object (typically `globalThis`)\n * @param saved - Descriptors to re-define\n */\nexport function restoreBlockedGlobals(\n globalObj: Record<string, unknown>,\n saved: SavedGlobals,\n): void {\n for (const [key, descriptor] of Object.entries(saved)) {\n if (descriptor) {\n Object.defineProperty(globalObj, key, descriptor);\n }\n }\n}\n\nbeforeEach(() => {\n if (!isTailorRuntime()) return;\n lifecycle.enter(globalThis as Record<string, unknown>, BLOCKED_GLOBALS);\n});\n\nafterEach(() => {\n if (!isTailorRuntime()) return;\n lifecycle.exit(globalThis as Record<string, unknown>);\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;AAkBA,MAAM,kBAAkB,CAAC,cAAc;;;;;;;;;;;;AAevC,SAAgB,gCAId;CACA,IAAI,SAAS;CACb,IAAI,QAAsB,EAAE;CAC5B,OAAO;EACL,IAAI,SAAS;GACX,OAAO;;EAET,MAAM,WAAW,MAAM;GACrB,IAAI,WAAW,GAAG,QAAQ,qBAAqB,WAAW,KAAK;GAC/D;;EAEF,KAAK,WAAW;GAGd,IAAI,WAAW,GAAG;GAClB;GACA,IAAI,WAAW,GAAG;IAChB,sBAAsB,WAAW,MAAM;IACvC,QAAQ,EAAE;;;EAGf;;AAGH,MAAM,YAAY,+BAA+B;AAEjD,SAAS,kBAA2B;CAClC,OAAO,oBAAoB;;;;;;;;;;;;AAa7B,SAAgB,kBAAkB,SAAiE;CACjG,IAAI,CAAC,WAAW,OAAO,YAAY,UAAU,OAAO;CAEpD,MAAM,SACJ,YAAY,WACZ,OAAQ,QAAiC,WAAW,YACnD,QAAiC,WAAW,OACvC,QAAgD,SACjD;CAEP,MAAM,QAAgD,EAAE;CACxD,KAAK,MAAM,CAAC,WAAW,cAAc,OAAO,QAAQ,OAAO,EACzD,IAAI,OAAO,cAAc,YAAY,cAAc,MACjD,MAAM,aAAa,EAAE,GAAI,WAAsC;CAGnE,OAAO,OAAO,KAAK,MAAM,CAAC,SAAS,IAAI,QAAQ;;;;;;;;;;;;AAajD,eAAsB,sBACpB,YACwD;CACxD,IAAI;EAGF,MAAM,SAAS,MAAM,OAAO,cAAc,WAAW,CAAC;EAGtD,OAAO,kBAFW,OAAO,SACE,WAAW,OAAO,QACZ;SAC3B;EACN,OAAO;;;AAKX,UAAU,YAAY;CACpB,IAAI,CAAC,iBAAiB,EAAE;CACxB,MAAM,aAAa,QAAQ,IAAI;CAC/B,IAAI,CAAC,YAAY;CAEjB,MAAM,QAAQ,MAAM,sBAAsB,WAAW;CACrD,IAAI,OACF,kBAAkB,WAAW,MAAM;EAErC;;;;;;;;;;;;;AAcF,SAAgB,qBACd,WACA,MACc;CACd,MAAM,UAAwB,EAAE;CAChC,KAAK,MAAM,OAAO,MAAM;EACtB,MAAM,aAAa,OAAO,yBAAyB,WAAW,IAAI;EAClE,IAAI,YAAY,cAAc;GAC5B,QAAQ,OAAO;GACf,OAAO,UAAU;;;CAGrB,OAAO;;;;;;;;AAST,SAAgB,sBACd,WACA,OACM;CACN,KAAK,MAAM,CAAC,KAAK,eAAe,OAAO,QAAQ,MAAM,EACnD,IAAI,YACF,OAAO,eAAe,WAAW,KAAK,WAAW;;AAKvD,iBAAiB;CACf,IAAI,CAAC,iBAAiB,EAAE;CACxB,UAAU,MAAM,YAAuC,gBAAgB;EACvE;AAEF,gBAAgB;CACd,IAAI,CAAC,iBAAiB,EAAE;CACxB,UAAU,KAAK,WAAsC;EACrD"}
1
+ {"version":3,"file":"setup.mjs","names":[],"sources":["../../src/vitest/setup.ts"],"sourcesContent":["/**\n * Vitest setup file that removes Node.js globals which Vitest depends on\n * but are not available in the Tailor Platform runtime.\n *\n * These globals cannot be removed in the environment's setup() because\n * Vitest's runner needs them during initialization. By using beforeEach/afterEach,\n * they are only removed during user test code execution.\n *\n * This file is auto-injected by tailorRuntime() but only activates when\n * the tailor-runtime environment is active (detected via __tailorRuntimeActive,\n * a flag set by injectMocks() during environment setup).\n */\nimport { pathToFileURL } from \"node:url\";\nimport { afterEach, beforeAll, beforeEach } from \"vitest\";\nimport { RUNTIME_FLAG_KEY, secretmanagerMock } from \"./mock\";\n\n// Globals that Vitest internals depend on but don't exist in the platform runtime.\n// Removed before each test, restored after.\nconst BLOCKED_GLOBALS = [\"performance\"] as const;\n\ntype SavedGlobals = Record<string, PropertyDescriptor | undefined>;\n\n/**\n * Reference-counted lifecycle for blocked globals.\n *\n * Concurrent tests in the same Vitest worker (`test.concurrent`) interleave\n * their beforeEach/afterEach hooks: a naive `let saved` shared across hooks\n * would let one test's `afterEach` restore `performance` mid-execution of\n * another test. Reference counting keeps the globals removed for the union\n * of all overlapping test scopes — the property is removed on first entry\n * and restored only when the last test exits.\n * @returns Lifecycle hooks\n */\nexport function createBlockedGlobalsLifecycle(): {\n enter: (globalObj: Record<string, unknown>, keys: readonly string[]) => void;\n exit: (globalObj: Record<string, unknown>) => void;\n readonly active: number;\n} {\n let active = 0;\n let saved: SavedGlobals = {};\n return {\n get active() {\n return active;\n },\n enter(globalObj, keys) {\n if (active === 0) saved = removeBlockedGlobals(globalObj, keys);\n active++;\n },\n exit(globalObj) {\n // Defensive guard — in practice every `enter` is paired with `exit`,\n // but a hook crash could desync the counter.\n if (active === 0) return;\n active--;\n if (active === 0) {\n restoreBlockedGlobals(globalObj, saved);\n saved = {};\n }\n },\n };\n}\n\nconst lifecycle = createBlockedGlobalsLifecycle();\n\nfunction isTailorRuntime(): boolean {\n return RUNTIME_FLAG_KEY in globalThis;\n}\n\n/**\n * Extract a vault store from a secrets-shaped value.\n *\n * `defineSecretManager()` returns `{ vaults, options, get, getAll }` (get/getAll\n * are non-enumerable). When that shape is present, the actual vaults live\n * under `.vaults`. Otherwise fall back to treating the object itself as the\n * vault map (for plain object configs).\n * @param secrets - Value from `appConfig.secrets` or `config.secrets`\n * @returns Vault store, or null if the value is unusable\n */\nexport function extractVaultStore(secrets: unknown): Record<string, Record<string, string>> | null {\n if (!secrets || typeof secrets !== \"object\") return null;\n\n const source =\n \"vaults\" in secrets &&\n typeof (secrets as { vaults?: unknown }).vaults === \"object\" &&\n (secrets as { vaults?: unknown }).vaults !== null\n ? ((secrets as { vaults: Record<string, unknown> }).vaults as Record<string, unknown>)\n : (secrets as Record<string, unknown>);\n\n const store: Record<string, Record<string, string>> = {};\n for (const [vaultName, vaultData] of Object.entries(source)) {\n if (typeof vaultData === \"object\" && vaultData !== null) {\n store[vaultName] = { ...(vaultData as Record<string, string>) };\n }\n }\n return Object.keys(store).length > 0 ? store : null;\n}\n\n/**\n * Load and parse secrets from a tailor.config.ts file.\n *\n * Returns a vault store on success, or `null` on any failure (missing config,\n * import failure, missing/invalid secrets shape). Errors are swallowed so a\n * misconfigured project still boots — the user can set secrets manually via\n * `secretmanagerMock.setSecrets()`.\n * @param configPath - Absolute path to tailor.config.ts\n * @returns Vault store keyed by vault name, or null if unavailable\n */\nexport async function loadSecretsFromConfig(\n configPath: string,\n): Promise<Record<string, Record<string, string>> | null> {\n try {\n // Convert to file URL so absolute Windows paths (e.g. \"C:\\...\") parse as\n // valid ESM specifiers.\n const config = await import(pathToFileURL(configPath).href);\n const appConfig = config.default;\n const secrets = appConfig?.secrets ?? config.secrets;\n return extractVaultStore(secrets);\n } catch {\n return null;\n }\n}\n\n// Load secrets from tailor.config.ts if config path is provided via env var\nbeforeAll(async () => {\n if (!isTailorRuntime()) return;\n const configPath = process.env.__TAILOR_RUNTIME_CONFIG;\n if (!configPath) return;\n\n const store = await loadSecretsFromConfig(configPath);\n if (store) {\n secretmanagerMock.setSecrets(store);\n }\n});\n\n/**\n * Remove the given globals from `globalObj`, returning the descriptors that\n * were actually deleted so `restoreBlockedGlobals` can put them back.\n *\n * Mirrors environment.ts: non-configurable properties are skipped instead of\n * deleted, so `delete` never throws in strict-mode runtimes that lock them\n * down. Only properties whose deletion actually happened are returned, so the\n * caller restores nothing for the skipped case.\n * @param globalObj - Target object (typically `globalThis`)\n * @param keys - Property names to remove\n * @returns Map of removed descriptors keyed by property name\n */\nexport function removeBlockedGlobals(\n globalObj: Record<string, unknown>,\n keys: readonly string[],\n): SavedGlobals {\n const removed: SavedGlobals = {};\n for (const key of keys) {\n const descriptor = Object.getOwnPropertyDescriptor(globalObj, key);\n if (descriptor?.configurable) {\n removed[key] = descriptor;\n delete globalObj[key];\n }\n }\n return removed;\n}\n\n/**\n * Restore previously-removed globals onto `globalObj` from a `SavedGlobals`\n * map produced by `removeBlockedGlobals`.\n * @param globalObj - Target object (typically `globalThis`)\n * @param saved - Descriptors to re-define\n */\nexport function restoreBlockedGlobals(\n globalObj: Record<string, unknown>,\n saved: SavedGlobals,\n): void {\n for (const [key, descriptor] of Object.entries(saved)) {\n if (descriptor) {\n Object.defineProperty(globalObj, key, descriptor);\n }\n }\n}\n\nbeforeEach(() => {\n if (!isTailorRuntime()) return;\n lifecycle.enter(globalThis as Record<string, unknown>, BLOCKED_GLOBALS);\n});\n\nafterEach(() => {\n if (!isTailorRuntime()) return;\n lifecycle.exit(globalThis as Record<string, unknown>);\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;AAkBA,MAAM,kBAAkB,CAAC,aAAa;;;;;;;;;;;;AAetC,SAAgB,gCAId;CACA,IAAI,SAAS;CACb,IAAI,QAAsB,CAAC;CAC3B,OAAO;EACL,IAAI,SAAS;GACX,OAAO;EACT;EACA,MAAM,WAAW,MAAM;GACrB,IAAI,WAAW,GAAG,QAAQ,qBAAqB,WAAW,IAAI;GAC9D;EACF;EACA,KAAK,WAAW;GAGd,IAAI,WAAW,GAAG;GAClB;GACA,IAAI,WAAW,GAAG;IAChB,sBAAsB,WAAW,KAAK;IACtC,QAAQ,CAAC;GACX;EACF;CACF;AACF;AAEA,MAAM,YAAY,8BAA8B;AAEhD,SAAS,kBAA2B;CAClC,OAAO,oBAAoB;AAC7B;;;;;;;;;;;AAYA,SAAgB,kBAAkB,SAAiE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