@tailor-platform/sdk 2.20.0 → 2.22.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 (116) hide show
  1. package/CHANGELOG.md +69 -0
  2. package/agent-skills/tailor/SKILL.md +3 -1
  3. package/dist/application-BE4vehXW.mjs +1 -0
  4. package/dist/application-BzO9ywXQ.mjs +199 -0
  5. package/dist/application-BzO9ywXQ.mjs.map +1 -0
  6. package/dist/cli/commands/deploy/app-id-lock.d.mts +31 -0
  7. package/dist/cli/lib.d.mts +2 -2
  8. package/dist/cli/lib.mjs +1 -1
  9. package/dist/cli/lib.mjs.map +1 -1
  10. package/dist/cli/main.d.mts +1 -0
  11. package/dist/cli/main.mjs +42 -42
  12. package/dist/cli/main.mjs.map +1 -1
  13. package/dist/cli/shared/logger.d.mts +9 -0
  14. package/dist/cli/shared/tailordb-namespaces.d.mts +1 -1
  15. package/dist/completion/zsh-worker.zsh +654 -131
  16. package/dist/configure/config/index.d.mts +2 -0
  17. package/dist/configure/index.d.mts +2 -1
  18. package/dist/configure/index.mjs +12 -1
  19. package/dist/configure/index.mjs.map +1 -1
  20. package/dist/configure/services/secrets/index.d.mts +14 -0
  21. package/dist/configure/services/tailordb/schema.d.mts +3 -2
  22. package/dist/configure/types/secret-vault-name.d.mts +32 -0
  23. package/dist/crashreport-CBaRJl5h.mjs +1 -0
  24. package/dist/{crashreport-Cyuz1qiu.mjs → crashreport-DFpRn-LS.mjs} +4 -4
  25. package/dist/{crashreport-Cyuz1qiu.mjs.map → crashreport-DFpRn-LS.mjs.map} +1 -1
  26. package/dist/{date-B7-oyTGE.mjs → date-Dri6Yas-.mjs} +2 -2
  27. package/dist/date-Dri6Yas-.mjs.map +1 -0
  28. package/dist/{errors-BjJnpXkK.mjs → errors-C9zGf4nz.mjs} +2 -2
  29. package/dist/{errors-BjJnpXkK.mjs.map → errors-C9zGf4nz.mjs.map} +1 -1
  30. package/dist/es-builtins-SfvXRVoG.mjs +2 -0
  31. package/dist/{es-builtins-BHCXINQp.mjs.map → es-builtins-SfvXRVoG.mjs.map} +1 -1
  32. package/dist/field-parse-DhnFs9WG.mjs +2 -0
  33. package/dist/field-parse-DhnFs9WG.mjs.map +1 -0
  34. package/dist/{globals-CMHSnj4w.mjs → globals-BCmGX05J.mjs} +2 -2
  35. package/dist/{globals-CMHSnj4w.mjs.map → globals-BCmGX05J.mjs.map} +1 -1
  36. package/dist/guards-yDXyKC9F.mjs +2 -0
  37. package/dist/{guards-ForsrxnH.mjs.map → guards-yDXyKC9F.mjs.map} +1 -1
  38. package/dist/{kysely-type-B_oA8D1k.mjs → kysely-type-C-iyFFH7.mjs} +2 -2
  39. package/dist/{kysely-type-B_oA8D1k.mjs.map → kysely-type-C-iyFFH7.mjs.map} +1 -1
  40. package/dist/logger-Db-YRTwK.mjs +9 -0
  41. package/dist/logger-Db-YRTwK.mjs.map +1 -0
  42. package/dist/manager-8-JOvuLl.mjs +2 -0
  43. package/dist/{manager-qfbUL7ru.mjs.map → manager-8-JOvuLl.mjs.map} +1 -1
  44. package/dist/plugin/builtin/enum-constants/index.mjs +1 -1
  45. package/dist/plugin/builtin/enum-constants/index.mjs.map +1 -1
  46. package/dist/plugin/builtin/file-utils/index.mjs +1 -1
  47. package/dist/plugin/builtin/file-utils/index.mjs.map +1 -1
  48. package/dist/plugin/builtin/kysely-type/index.mjs +1 -1
  49. package/dist/plugin/index.mjs +1 -1
  50. package/dist/plugin/index.mjs.map +1 -1
  51. package/dist/register-ts-hook-z7ggXQy4.mjs +922 -0
  52. package/dist/register-ts-hook-z7ggXQy4.mjs.map +1 -0
  53. package/dist/registry-BijIDRVA.mjs +2 -0
  54. package/dist/{registry-HlEaGvl5.mjs.map → registry-BijIDRVA.mjs.map} +1 -1
  55. package/dist/repl-editor-DGJBfIt1.mjs +2 -0
  56. package/dist/{repl-editor-BG1aDOfH.mjs.map → repl-editor-DGJBfIt1.mjs.map} +1 -1
  57. package/dist/runtime/field-parse.d.mts +17 -1
  58. package/dist/runtime/index.d.mts +2 -1
  59. package/dist/runtime/index.mjs +1 -1
  60. package/dist/runtime/secretmanager.d.mts +8 -20
  61. package/dist/schema-CRtAmDcl.mjs +2 -0
  62. package/dist/{schema-BKvcWdVf.mjs.map → schema-CRtAmDcl.mjs.map} +1 -1
  63. package/dist/secretmanager-vHQoXdQz.mjs.map +1 -1
  64. package/dist/seed/index.mjs +7 -6
  65. package/dist/seed/index.mjs.map +1 -1
  66. package/dist/service-Bx-7Lz06.mjs +1 -0
  67. package/dist/{service-CuqkHP1r.mjs → service-CL1Bp4It.mjs} +3 -3
  68. package/dist/{service-CuqkHP1r.mjs.map → service-CL1Bp4It.mjs.map} +1 -1
  69. package/dist/{service-B4Gh_bbL.mjs → service-DHVuH7-X.mjs} +2 -2
  70. package/dist/{service-B4Gh_bbL.mjs.map → service-DHVuH7-X.mjs.map} +1 -1
  71. package/dist/service_pb-DNskuJQC.mjs +1 -0
  72. package/dist/service_pb-y2GYIgfs.mjs +2 -0
  73. package/dist/{service_pb-DprmLNsq.mjs.map → service_pb-y2GYIgfs.mjs.map} +1 -1
  74. package/dist/tailordb-ddl-DqInYupv.mjs +7 -0
  75. package/dist/{tailordb-ddl-Fgm2cNvT.mjs.map → tailordb-ddl-DqInYupv.mjs.map} +1 -1
  76. package/dist/utils/test/index.mjs +1 -1
  77. package/dist/utils/test/index.mjs.map +1 -1
  78. package/dist/vitest/environment.mjs +1 -1
  79. package/dist/vitest/environment.mjs.map +1 -1
  80. package/dist/vitest/index.mjs +1 -1
  81. package/dist/vitest/index.mjs.map +1 -1
  82. package/dist/vitest/mocks/file.d.mts +1 -1
  83. package/dist/vitest/setup.mjs +1 -1
  84. package/dist/workspace_resource_pb-D2njwgsE.mjs +2 -0
  85. package/dist/{workspace_resource_pb-BOoRts_z.mjs.map → workspace_resource_pb-D2njwgsE.mjs.map} +1 -1
  86. package/docs/cli-reference.md +22 -12
  87. package/docs/configuration.md +1 -1
  88. package/docs/github-actions.md +90 -24
  89. package/docs/migration/v2.md +70 -5
  90. package/docs/migration/v3.md +64 -0
  91. package/docs/plugin/index.md +1 -1
  92. package/docs/services/resolver.md +21 -0
  93. package/docs/services/secret.md +20 -15
  94. package/package.json +19 -19
  95. package/dist/application-B6NYnrhv.mjs +0 -199
  96. package/dist/application-B6NYnrhv.mjs.map +0 -1
  97. package/dist/application-BlbyGJsd.mjs +0 -1
  98. package/dist/crashreport-CgymxQDu.mjs +0 -1
  99. package/dist/date-B7-oyTGE.mjs.map +0 -1
  100. package/dist/es-builtins-BHCXINQp.mjs +0 -2
  101. package/dist/field-parse-BbNyotv5.mjs +0 -2
  102. package/dist/field-parse-BbNyotv5.mjs.map +0 -1
  103. package/dist/guards-ForsrxnH.mjs +0 -2
  104. package/dist/logger-72hM4JWZ.mjs +0 -9
  105. package/dist/logger-72hM4JWZ.mjs.map +0 -1
  106. package/dist/manager-qfbUL7ru.mjs +0 -2
  107. package/dist/register-ts-hook-FsCX38LQ.mjs +0 -917
  108. package/dist/register-ts-hook-FsCX38LQ.mjs.map +0 -1
  109. package/dist/registry-HlEaGvl5.mjs +0 -2
  110. package/dist/repl-editor-BG1aDOfH.mjs +0 -2
  111. package/dist/schema-BKvcWdVf.mjs +0 -2
  112. package/dist/service-BgrEteZ2.mjs +0 -1
  113. package/dist/service_pb-DKrsO1_u.mjs +0 -1
  114. package/dist/service_pb-DprmLNsq.mjs +0 -2
  115. package/dist/tailordb-ddl-Fgm2cNvT.mjs +0 -7
  116. package/dist/workspace_resource_pb-BOoRts_z.mjs +0 -2
@@ -10,7 +10,21 @@ type SecretsOptions = {
10
10
  type DefinedSecrets<T extends SecretsInputNullish> = {
11
11
  readonly vaults: T;
12
12
  readonly options: SecretsOptions;
13
+ /**
14
+ * Retrieve a single secret value.
15
+ * @deprecated since 2.21.0 — import `secretmanager` from `@tailor-platform/sdk/runtime` and call `secretmanager.getSecret()` instead. Importing this object into a resolver, executor, or workflow file bundles the raw values passed to `defineSecretManager()` into that function's deployed code, which fails to build once any value comes from `process.env`. codemod: v3/secrets-get-to-secretmanager
16
+ * @param vault - Vault name
17
+ * @param secret - Secret name
18
+ * @returns The secret value, or undefined if not present
19
+ */
13
20
  get<V extends Extract<keyof T, string>, S extends Extract<keyof T[V], string>>(vault: V, secret: S): Promise<string | undefined>;
21
+ /**
22
+ * Retrieve multiple secret values from the same vault.
23
+ * @deprecated since 2.21.0 — import `secretmanager` from `@tailor-platform/sdk/runtime` and call `secretmanager.getSecrets()` instead (it returns a partial record keyed by name, not an array in call order). Importing this object into a resolver, executor, or workflow file bundles the raw values passed to `defineSecretManager()` into that function's deployed code, which fails to build once any value comes from `process.env`. codemod: v3/secrets-get-to-secretmanager
24
+ * @param vault - Vault name
25
+ * @param secrets - Secret names to fetch
26
+ * @returns Values in the same order as `secrets`; `undefined` for any not present
27
+ */
14
28
  getAll<V extends Extract<keyof T, string>, S extends Extract<keyof T[V], string>>(vault: V, secrets: readonly S[]): Promise<(string | undefined)[]>;
15
29
  } & SecretsDefinitionBrand;
16
30
  /**
@@ -432,8 +432,9 @@ declare function object<const F extends Record<string, TailorAnyDBField> & Exclu
432
432
  array: true;
433
433
  } ? true : false;
434
434
  }, FieldOutput<InferFieldsOutput<F>, Opt>, F>;
435
- declare const idField: TailorDBFieldInstance<"uuid", FieldOptions, string>;
436
- type idField = typeof idField;
435
+ declare function createIdField(): TailorDBFieldInstance<"uuid", FieldOptions, string>;
436
+ type idField = ReturnType<typeof createIdField>;
437
+ declare let idField: idField | undefined;
437
438
  type DBTable<F extends {
438
439
  id?: never;
439
440
  } & Record<string, TailorAnyDBField>, Defined extends DefinedDBTypeMetadata = DefinedDBTypeMetadata> = TailorDBInstance<{
@@ -0,0 +1,32 @@
1
+ //#region src/configure/types/secret-vault-name.d.ts
2
+ export interface SecretVaultNameRegistry {}
3
+ /**
4
+ * Secret Manager vault name declared via `defineSecretManager()`.
5
+ *
6
+ * When `tailor.d.ts` is generated (via `tailor deploy`/`generate`), this is narrowed
7
+ * to the union of vault names declared via `defineSecretManager()` (autocompleted),
8
+ * while still accepting any other string. Unlike the other `*NameRegistry` types,
9
+ * declaring some vaults does not reject the rest: Secret Manager vaults can also be
10
+ * managed imperatively via the CLI, entirely outside `defineSecretManager()`, so a
11
+ * vault name absent from the registry is not necessarily a mistake.
12
+ */
13
+ export type SecretVaultName = keyof SecretVaultNameRegistry extends never ? string : keyof SecretVaultNameRegistry | (string & {});
14
+ /**
15
+ * Secret name narrowed to the vault `V`, looked up in registry `R`.
16
+ *
17
+ * Generic over the registry so type-level tests can exercise this narrowing against
18
+ * a local, disposable registry shape instead of `declare module`-augmenting the real
19
+ * `SecretVaultNameRegistry` — that augmentation is ambient and leaks into every other
20
+ * file type-checked in the same program, not just the test file that declares it.
21
+ */
22
+ export type SecretNameForRegistry<V, R> = V extends keyof R ? R[V] & string : string;
23
+ /**
24
+ * Secret name narrowed to the vault `V`.
25
+ *
26
+ * Inside a vault declared via `defineSecretManager()`, only that vault's declared
27
+ * secret names are accepted — the config is the source of truth for that vault, so
28
+ * an unlisted name is a typo. For any other vault (for example one managed only via
29
+ * the CLI), falls back to `string`.
30
+ */
31
+ export type SecretNameFor<V> = SecretNameForRegistry<V, SecretVaultNameRegistry>;
32
+ //#endregion
@@ -0,0 +1 @@
1
+ import{n as e}from"./crashreport-DFpRn-LS.mjs";export{e as reportCrash};
@@ -1,4 +1,4 @@
1
- import{n as e,r as t}from"./logger-72hM4JWZ.mjs";import{t as n}from"./package-json-C690ceex.mjs";import{n as r}from"./user-agent-vdHYF3QL.mjs";import{r as i,t as a}from"./secret-file-C9wp_FCX.mjs";import*as o from"pathe";import*as s from"node:fs";import{parseYAML as c}from"confbox";import{xdgConfig as l}from"xdg-basedir";import*as u from"node:crypto";import{isCI as d}from"std-env";import*as f from"node:os";function parseCrashReportConfig(){if(d)return{localEnabled:!1,remoteEnabled:!1,localDir:``};let e=(process.env.TAILOR_CRASH_REPORTS_LOCAL??`on`).toLowerCase()!==`off`,t=(process.env.TAILOR_CRASH_REPORTS_REMOTE??`off`).toLowerCase()===`on`,n=l?o.join(l,`tailor-platform`,`crash-reports`):``;return{localEnabled:e&&n!==``,remoteEnabled:t,localDir:n}}const p=`--- JSON ---`,m=`.crash.log`;function formatCrashReport(e){return[`Crash Report: ${e.id}`,`Timestamp: ${e.timestamp}`,`Error Type: ${e.errorType}`,``,`--- Environment ---`,`SDK Version: ${e.sdkVersion}`,`Node Version: ${e.nodeVersion}`,`OS: ${e.osPlatform} ${e.osRelease}`,`Arch: ${e.arch}`,``,`--- Command ---`,`Command: ${e.command}`,`Arguments: ${JSON.stringify(e.argv)}`,``,`--- Error ---`,`Name: ${e.errorName}`,`Message: ${e.errorMessage}`,``,`--- Stack Trace ---`,e.stackTrace||`(no stack trace available)`,``,p,JSON.stringify(e),``].join(`
1
+ import{a as e,i as t}from"./logger-Db-YRTwK.mjs";import{t as n}from"./package-json-C690ceex.mjs";import{n as r}from"./user-agent-vdHYF3QL.mjs";import{r as i,t as a}from"./secret-file-C9wp_FCX.mjs";import*as o from"pathe";import*as s from"node:fs";import{isCI as c}from"std-env";import{parseYAML as l}from"confbox";import{xdgConfig as u}from"xdg-basedir";import*as d from"node:crypto";import*as f from"node:os";function parseCrashReportConfig(){if(c)return{localEnabled:!1,remoteEnabled:!1,localDir:``};let e=(process.env.TAILOR_CRASH_REPORTS_LOCAL??`on`).toLowerCase()!==`off`,t=(process.env.TAILOR_CRASH_REPORTS_REMOTE??`off`).toLowerCase()===`on`,n=u?o.join(u,`tailor-platform`,`crash-reports`):``;return{localEnabled:e&&n!==``,remoteEnabled:t,localDir:n}}const p=`--- JSON ---`,m=`.crash.log`;function formatCrashReport(e){return[`Crash Report: ${e.id}`,`Timestamp: ${e.timestamp}`,`Error Type: ${e.errorType}`,``,`--- Environment ---`,`SDK Version: ${e.sdkVersion}`,`Node Version: ${e.nodeVersion}`,`OS: ${e.osPlatform} ${e.osRelease}`,`Arch: ${e.arch}`,``,`--- Command ---`,`Command: ${e.command}`,`Arguments: ${JSON.stringify(e.argv)}`,``,`--- Error ---`,`Name: ${e.errorName}`,`Message: ${e.errorMessage}`,``,`--- Stack Trace ---`,e.stackTrace||`(no stack trace available)`,``,p,JSON.stringify(e),``].join(`
2
2
  `)}function generateFilename(e){return`${e.timestamp.replace(/[:.]/g,`-`)}-${e.id.slice(0,8)}${m}`}function cleanupOldFiles(e){try{let t=s.readdirSync(e).filter(e=>e.endsWith(m)).toSorted().toReversed();for(let n of t.slice(10))s.unlinkSync(o.join(e,n))}catch{}}function writeCrashReport(e,t){try{a(t);let n=generateFilename(e),r=o.join(t,n),s=formatCrashReport(e);return i(r,s),cleanupOldFiles(t),r}catch{return}}async function sendCrashReport(e,t){try{let n=process.env.TAILOR_CRASH_REPORT_ENDPOINT||`https://sdk-error-tracking-926vh9t4cl.erp.dev/query`,r=await fetch(n,{method:`POST`,headers:{"Content-Type":`application/json`,"User-Agent":t},body:JSON.stringify({query:`
3
3
  mutation SubmitCrashReport(
4
4
  $id: String!
@@ -37,6 +37,6 @@ mutation SubmitCrashReport(
37
37
  success
38
38
  }
39
39
  }`,variables:e}),signal:AbortSignal.timeout(5e3)});if(!r.ok)return!1;let i=await r.json();return!i.errors?.length&&i.data?.submitCrashReport.success===!0}catch{return!1}}const h=f.homedir(),g=/\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/gi,_=/\b[0-9a-fA-F]{32,}\b/g,v=/\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}\b/g,y=/(?:\/(?:[\w.@\- ]+\/)+[\w.@\- ]+)/g,b=/(?:[A-Za-z]:\\(?:[\w.@\- ]+\\)+[\w.@\- ]+)/g,x=/[?&][^?\s]*/g,S=/\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}\b/,C=/^[A-Za-z]:\\/,w=`packages/sdk/`;function lastSegment(e,t){return e.split(t).pop()??e}function sanitizeStackTrace(e){let t=e.search(/\n\s+at /),n;return n=t===-1?sanitizeMessage(e):sanitizeMessage(e.slice(0,t))+e.slice(t),n=n.replace(y,e=>{let t=e.indexOf(w);return t===-1?e.startsWith(h)?`~/<redacted>/${lastSegment(e,`/`)}`:`<external>/${lastSegment(e,`/`)}`:e.slice(t)}),n=n.replace(b,e=>{let t=e.replace(/\\/g,`/`),n=t.indexOf(w);return n===-1?`<external>/${lastSegment(e,`\\`)}`:t.slice(n)}),n}function sanitizeMessage(e){let t=e;return t=t.replace(/\nRequest:\s*[\s\S]*$/,`
40
- Request: <redacted>`),t=t.replace(g,`<uuid>`),t=t.replace(_,`<redacted>`),t=t.replace(v,`<email>`),t=t.replace(x,`?<redacted>`),t=t.replace(y,e=>`<path>/${lastSegment(e,`/`)}`),t=t.replace(b,e=>`<path>/${lastSegment(e,`\\`)}`),t}function sanitizeArgv(e){let t=[],n=!1;for(let r of e){if(n){if(!r.startsWith(`-`)){t.push(`<redacted>`),n=!1;continue}n=!1}if(r.startsWith(`-`)){let e=r.indexOf(`=`);if(e!==-1){t.push(`${r.slice(0,e)}=<redacted>`);continue}t.push(r),n=!0;continue}if(r.startsWith(`/`)&&r.includes(`/`,1)){t.push(`<path>`);continue}if(C.test(r)){t.push(`<path>`);continue}if(S.test(r)){t.push(`<email>`);continue}t.push(r)}return t}function parseCommand(){let e=process.argv.slice(2),t=[];for(let n of e){if(n.startsWith(`-`)||t.length>=3)break;t.push(n)}return t.join(` `)||`<unknown>`}function buildCrashReport(e){let{error:n,sdkVersion:r,errorType:i}=e,a=n instanceof Error,o=a?n.message:String(n),s=a&&n.stack?n.stack:``,c=a?n.name:`UnknownError`,l=readCurrentUser();return{id:u.randomUUID(),timestamp:new Date().toISOString(),sdkVersion:r,nodeVersion:process.version,osPlatform:process.platform,osRelease:f.release(),arch:process.arch,command:sanitizeMessage(t(parseCommand())),argv:sanitizeArgv(process.argv.map(t)),errorName:t(c),errorMessage:sanitizeMessage(t(o)),stackTrace:sanitizeStackTrace(t(s)),errorType:i,userId:l?.id?t(l.id):null,userEmail:l?.email?t(l.email):null}}function readCurrentUser(){try{if(!l)return null;let e=o.join(l,`tailor-platform`,`config.yaml`);if(!s.existsSync(e))return null;let t=c(s.readFileSync(e,`utf-8`)),n=t?.current_user??null;if(!n)return null;let r=t.users?.[n]?.email;return{id:n,email:typeof r==`string`?r:legacyEmail(n)}}catch{return null}}function legacyEmail(e){return e.includes(`@`)?e:null}async function reportCrash(t,i){try{let a=parseCrashReportConfig();if(!a.localEnabled&&!a.remoteEnabled)return;let o=(await n()).version??`unknown`,s=buildCrashReport({error:t,sdkVersion:o,errorType:i});if(a.localEnabled){let t=writeCrashReport(s,a.localDir);t&&e.log([``,`An unexpected error occurred. A crash report has been saved to:`,` ${t}`,``,`To submit this report:`,` tailor crashreport send --file "${t}"`].join(`
41
- `))}a.remoteEnabled&&await sendCrashReport(s,r(o))}catch{}}function initCrashReporting(){let t=parseCrashReportConfig();if(!t.localEnabled&&!t.remoteEnabled)return;let handleFatal=(t,n)=>{let r=t instanceof Error?t.message:String(t);e.error(r),reportCrash(t,n).finally(()=>{process.exit(1)})};process.on(`uncaughtException`,e=>handleFatal(e,`uncaughtException`)),process.on(`unhandledRejection`,e=>handleFatal(e,`unhandledRejection`))}export{p as a,m as i,reportCrash as n,parseCrashReportConfig as o,sendCrashReport as r,initCrashReporting as t};
42
- //# sourceMappingURL=crashreport-Cyuz1qiu.mjs.map
40
+ Request: <redacted>`),t=t.replace(g,`<uuid>`),t=t.replace(_,`<redacted>`),t=t.replace(v,`<email>`),t=t.replace(x,`?<redacted>`),t=t.replace(y,e=>`<path>/${lastSegment(e,`/`)}`),t=t.replace(b,e=>`<path>/${lastSegment(e,`\\`)}`),t}function sanitizeArgv(e){let t=[],n=!1;for(let r of e){if(n){if(!r.startsWith(`-`)){t.push(`<redacted>`),n=!1;continue}n=!1}if(r.startsWith(`-`)){let e=r.indexOf(`=`);if(e!==-1){t.push(`${r.slice(0,e)}=<redacted>`);continue}t.push(r),n=!0;continue}if(r.startsWith(`/`)&&r.includes(`/`,1)){t.push(`<path>`);continue}if(C.test(r)){t.push(`<path>`);continue}if(S.test(r)){t.push(`<email>`);continue}t.push(r)}return t}function parseCommand(){let e=process.argv.slice(2),t=[];for(let n of e){if(n.startsWith(`-`)||t.length>=3)break;t.push(n)}return t.join(` `)||`<unknown>`}function buildCrashReport(t){let{error:n,sdkVersion:r,errorType:i}=t,a=n instanceof Error,o=a?n.message:String(n),s=a&&n.stack?n.stack:``,c=a?n.name:`UnknownError`,l=readCurrentUser();return{id:d.randomUUID(),timestamp:(/* @__PURE__ */ new Date()).toISOString(),sdkVersion:r,nodeVersion:process.version,osPlatform:process.platform,osRelease:f.release(),arch:process.arch,command:sanitizeMessage(e(parseCommand())),argv:sanitizeArgv(process.argv.map(e)),errorName:e(c),errorMessage:sanitizeMessage(e(o)),stackTrace:sanitizeStackTrace(e(s)),errorType:i,userId:l?.id?e(l.id):null,userEmail:l?.email?e(l.email):null}}function readCurrentUser(){try{if(!u)return null;let e=o.join(u,`tailor-platform`,`config.yaml`);if(!s.existsSync(e))return null;let t=l(s.readFileSync(e,`utf-8`)),n=t?.current_user??null;if(!n)return null;let r=t.users?.[n]?.email;return{id:n,email:typeof r==`string`?r:legacyEmail(n)}}catch{return null}}function legacyEmail(e){return e.includes(`@`)?e:null}async function reportCrash(e,i){try{let a=parseCrashReportConfig();if(!a.localEnabled&&!a.remoteEnabled)return;let o=(await n()).version??`unknown`,s=buildCrashReport({error:e,sdkVersion:o,errorType:i});if(a.localEnabled){let e=writeCrashReport(s,a.localDir);e&&t.log([``,`An unexpected error occurred. A crash report has been saved to:`,` ${e}`,``,`To submit this report:`,` tailor crashreport send --file "${e}"`].join(`
41
+ `))}a.remoteEnabled&&await sendCrashReport(s,r(o))}catch{}}function initCrashReporting(){let e=parseCrashReportConfig();if(!e.localEnabled&&!e.remoteEnabled)return;let handleFatal=(e,n)=>{let r=e instanceof Error?e.message:String(e);t.error(r),reportCrash(e,n).finally(()=>{process.exit(1)})};process.on(`uncaughtException`,e=>handleFatal(e,`uncaughtException`)),process.on(`unhandledRejection`,e=>handleFatal(e,`unhandledRejection`))}export{p as a,m as i,reportCrash as n,parseCrashReportConfig as o,sendCrashReport as r,initCrashReporting as t};
42
+ //# sourceMappingURL=crashreport-DFpRn-LS.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"crashreport-Cyuz1qiu.mjs","names":[],"sources":["../src/cli/crashreport/config.ts","../src/cli/crashreport/writer.ts","../src/cli/crashreport/sender.ts","../src/cli/crashreport/sanitize.ts","../src/cli/crashreport/report.ts","../src/cli/crashreport/index.ts"],"sourcesContent":["import * as path from \"pathe\";\nimport { isCI } from \"std-env\";\nimport { xdgConfig } from \"xdg-basedir\";\n\nexport interface CrashReportConfig {\n readonly localEnabled: boolean;\n readonly remoteEnabled: boolean;\n readonly localDir: string;\n}\n\n/**\n * Parse crash report configuration from environment variables.\n * Local crash log writing is enabled by default (opt-out via TAILOR_CRASH_REPORTS_LOCAL=off).\n * Remote sending is disabled by default (opt-in via TAILOR_CRASH_REPORTS_REMOTE=on).\n * Both are auto-disabled in CI environments.\n * @returns Crash report configuration\n */\nexport function parseCrashReportConfig(): CrashReportConfig {\n if (isCI) {\n return {\n localEnabled: false,\n remoteEnabled: false,\n localDir: \"\",\n };\n }\n\n const localEnabled = (process.env.TAILOR_CRASH_REPORTS_LOCAL ?? \"on\").toLowerCase() !== \"off\";\n const remoteEnabled = (process.env.TAILOR_CRASH_REPORTS_REMOTE ?? \"off\").toLowerCase() === \"on\";\n const localDir = xdgConfig ? path.join(xdgConfig, \"tailor-platform\", \"crash-reports\") : \"\";\n\n return {\n localEnabled: localEnabled && localDir !== \"\",\n remoteEnabled,\n localDir,\n };\n}\n","import * as fs from \"node:fs\";\nimport * as path from \"pathe\";\nimport { ensureSecretDir, writeSecretFile } from \"#/cli/shared/secret-file\";\nimport type { CrashReport } from \"./report\";\n\nconst MAX_CRASH_FILES = 10;\n\n/** Marker line that separates human-readable content from the JSON footer. */\nexport const JSON_FOOTER_MARKER = \"--- JSON ---\";\n\n/** File extension for crash log files. */\nexport const CRASH_LOG_EXTENSION = \".crash.log\";\n\n/**\n * Format a CrashReport as human-readable text for local crash log files.\n * @param report - Crash report to format\n * @returns Formatted text content\n */\nexport function formatCrashReport(report: CrashReport): string {\n const lines = [\n `Crash Report: ${report.id}`,\n `Timestamp: ${report.timestamp}`,\n `Error Type: ${report.errorType}`,\n \"\",\n \"--- Environment ---\",\n `SDK Version: ${report.sdkVersion}`,\n `Node Version: ${report.nodeVersion}`,\n `OS: ${report.osPlatform} ${report.osRelease}`,\n `Arch: ${report.arch}`,\n \"\",\n \"--- Command ---\",\n `Command: ${report.command}`,\n `Arguments: ${JSON.stringify(report.argv)}`,\n \"\",\n \"--- Error ---\",\n `Name: ${report.errorName}`,\n `Message: ${report.errorMessage}`,\n \"\",\n \"--- Stack Trace ---\",\n report.stackTrace || \"(no stack trace available)\",\n \"\",\n JSON_FOOTER_MARKER,\n JSON.stringify(report),\n \"\",\n ];\n return lines.join(\"\\n\");\n}\n\n/**\n * Generate a filename for a crash log file.\n * Format: {timestamp}-{shortId}.crash.log\n * @param report - Crash report to generate filename for\n * @returns Filename string\n */\nfunction generateFilename(report: CrashReport): string {\n const safeTimestamp = report.timestamp.replace(/[:.]/g, \"-\");\n const shortId = report.id.slice(0, 8);\n return `${safeTimestamp}-${shortId}${CRASH_LOG_EXTENSION}`;\n}\n\n/**\n * Remove old crash log files, keeping only the most recent ones.\n * @param dir - Crash log directory\n */\nfunction cleanupOldFiles(dir: string): void {\n try {\n const files = fs\n .readdirSync(dir)\n .filter((f) => f.endsWith(CRASH_LOG_EXTENSION))\n .toSorted()\n .toReversed();\n\n for (const file of files.slice(MAX_CRASH_FILES)) {\n fs.unlinkSync(path.join(dir, file));\n }\n } catch {\n // Best-effort cleanup, ignore errors\n }\n}\n\n/**\n * Write a crash report to a local file.\n * Creates the directory if it doesn't exist. Keeps only the last 10 crash files.\n * Never throws - returns the file path on success or undefined on failure.\n * @param report - Crash report to write\n * @param dir - Directory to write the crash log file to\n * @returns File path on success, undefined on failure\n */\nexport function writeCrashReport(report: CrashReport, dir: string): string | undefined {\n try {\n ensureSecretDir(dir);\n\n const filename = generateFilename(report);\n const filePath = path.join(dir, filename);\n const content = formatCrashReport(report);\n\n writeSecretFile(filePath, content);\n cleanupOldFiles(dir);\n\n return filePath;\n } catch {\n return undefined;\n }\n}\n","import type { CrashReport } from \"./report\";\n\nconst SEND_TIMEOUT_MS = 5000;\nconst PRODUCTION_ENDPOINT = \"https://sdk-error-tracking-926vh9t4cl.erp.dev/query\";\n\nconst SUBMIT_MUTATION = `\nmutation SubmitCrashReport(\n $id: String!\n $timestamp: String!\n $sdkVersion: String!\n $nodeVersion: String!\n $osPlatform: String!\n $osRelease: String!\n $arch: String!\n $command: String!\n $argv: [String]\n $errorName: String!\n $errorMessage: String!\n $stackTrace: String\n $errorType: String!\n $userId: String\n $userEmail: String\n) {\n submitCrashReport(\n id: $id\n timestamp: $timestamp\n sdkVersion: $sdkVersion\n nodeVersion: $nodeVersion\n osPlatform: $osPlatform\n osRelease: $osRelease\n arch: $arch\n command: $command\n argv: $argv\n errorName: $errorName\n errorMessage: $errorMessage\n stackTrace: $stackTrace\n errorType: $errorType\n userId: $userId\n userEmail: $userEmail\n ) {\n success\n }\n}`;\n\n/**\n * Send a crash report to the remote endpoint via GraphQL mutation.\n * Best-effort: never throws, returns boolean success.\n * @param report - Crash report to send\n * @param ua - User-Agent header value\n * @returns true if the request succeeded, false otherwise\n */\nexport async function sendCrashReport(report: CrashReport, ua: string): Promise<boolean> {\n try {\n const endpoint = process.env.TAILOR_CRASH_REPORT_ENDPOINT || PRODUCTION_ENDPOINT;\n const response = await fetch(endpoint, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"User-Agent\": ua,\n },\n body: JSON.stringify({\n query: SUBMIT_MUTATION,\n variables: report,\n }),\n signal: AbortSignal.timeout(SEND_TIMEOUT_MS),\n });\n\n if (!response.ok) return false;\n\n const data = (await response.json()) as {\n errors?: unknown[];\n data?: { submitCrashReport: { success: boolean } };\n };\n if (data.errors?.length) return false;\n return data.data?.submitCrashReport.success === true;\n } catch {\n return false;\n }\n}\n","import * as os from \"node:os\";\n\nconst HOME_DIR = os.homedir();\n\n// Patterns for sanitization (global variants for use with .replace())\nconst UUID_PATTERN = /\\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\\b/gi;\nconst LONG_HEX_PATTERN = /\\b[0-9a-fA-F]{32,}\\b/g;\nconst EMAIL_PATTERN = /\\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}\\b/g;\nconst ABSOLUTE_PATH_PATTERN = /(?:\\/(?:[\\w.@\\- ]+\\/)+[\\w.@\\- ]+)/g;\nconst WINDOWS_PATH_PATTERN = /(?:[A-Za-z]:\\\\(?:[\\w.@\\- ]+\\\\)+[\\w.@\\- ]+)/g;\nconst URL_QUERY_PATTERN = /[?&][^?\\s]*/g;\n\n// Non-global variants for single-match .test() calls (avoids lastIndex state issues)\nconst EMAIL_TEST_PATTERN = /\\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}\\b/;\nconst WINDOWS_DRIVE_TEST_PATTERN = /^[A-Za-z]:\\\\/;\n\n// SDK package path marker for relative paths\nconst SDK_PACKAGE_MARKER = \"packages/sdk/\";\n\nfunction lastSegment(filePath: string, separator: string): string {\n return filePath.split(separator).pop() ?? filePath;\n}\n\n/**\n * Sanitize a stack trace by replacing absolute paths with relative SDK paths.\n * External paths are replaced with `<external>/filename.ext`.\n * Home directories are replaced with `~/<redacted>/`.\n * @param stack - Raw stack trace string\n * @returns Sanitized stack trace\n */\nexport function sanitizeStackTrace(stack: string): string {\n // V8 stack traces start with \"ErrorType: message\\n at ...\".\n // The error message may span multiple lines before the first \" at \" frame.\n // Apply message sanitization to all message lines so secrets embedded in\n // multiline error messages are redacted consistently with errorMessage.\n const firstFrameIndex = stack.search(/\\n\\s+at /);\n let result: string;\n if (firstFrameIndex !== -1) {\n result = sanitizeMessage(stack.slice(0, firstFrameIndex)) + stack.slice(firstFrameIndex);\n } else {\n result = sanitizeMessage(stack);\n }\n\n result = result.replace(ABSOLUTE_PATH_PATTERN, (match) => {\n const sdkIndex = match.indexOf(SDK_PACKAGE_MARKER);\n if (sdkIndex !== -1) {\n return match.slice(sdkIndex);\n }\n\n if (match.startsWith(HOME_DIR)) {\n return `~/<redacted>/${lastSegment(match, \"/\")}`;\n }\n\n return `<external>/${lastSegment(match, \"/\")}`;\n });\n result = result.replace(WINDOWS_PATH_PATTERN, (match) => {\n const normalized = match.replace(/\\\\/g, \"/\");\n const sdkIndex = normalized.indexOf(SDK_PACKAGE_MARKER);\n if (sdkIndex !== -1) {\n return normalized.slice(sdkIndex);\n }\n return `<external>/${lastSegment(match, \"\\\\\")}`;\n });\n return result;\n}\n\n/**\n * Sanitize an error message by redacting sensitive information.\n * Redacts: UUIDs, long hex tokens, email addresses, absolute paths, URL query strings.\n * @param message - Raw error message\n * @returns Sanitized error message\n */\nexport function sanitizeMessage(message: string): string {\n let result = message;\n // Strip serialized request/response bodies that may contain secrets\n result = result.replace(/\\nRequest:\\s*[\\s\\S]*$/, \"\\nRequest: <redacted>\");\n result = result.replace(UUID_PATTERN, \"<uuid>\");\n result = result.replace(LONG_HEX_PATTERN, \"<redacted>\");\n result = result.replace(EMAIL_PATTERN, \"<email>\");\n result = result.replace(URL_QUERY_PATTERN, \"?<redacted>\");\n result = result.replace(ABSOLUTE_PATH_PATTERN, (match) => `<path>/${lastSegment(match, \"/\")}`);\n result = result.replace(WINDOWS_PATH_PATTERN, (match) => `<path>/${lastSegment(match, \"\\\\\")}`);\n\n return result;\n}\n\n/**\n * Sanitize process.argv by keeping command/subcommand names and redacting\n * values of sensitive flags.\n * @param argv - Raw process.argv array\n * @returns Sanitized argv array\n */\nexport function sanitizeArgv(argv: string[]): string[] {\n const result: string[] = [];\n let redactNext = false;\n\n for (const arg of argv) {\n if (redactNext) {\n // If the next token is itself a flag, treat it as a new flag rather\n // than consuming it as the previous flag's value. This avoids leaking\n // the *next* flag's value (e.g., `--verbose --workspace-id secret`\n // would otherwise expose `secret`).\n if (!arg.startsWith(\"-\")) {\n result.push(\"<redacted>\");\n redactNext = false;\n continue;\n }\n redactNext = false;\n }\n\n if (arg.startsWith(\"-\")) {\n // --flag=value: keep flag name, redact value\n const eqIndex = arg.indexOf(\"=\");\n if (eqIndex !== -1) {\n result.push(`${arg.slice(0, eqIndex)}=<redacted>`);\n continue;\n }\n\n // --flag / -f: keep flag name, redact next arg as its value\n result.push(arg);\n redactNext = true;\n continue;\n }\n\n // Redact absolute paths\n if (arg.startsWith(\"/\") && arg.includes(\"/\", 1)) {\n result.push(\"<path>\");\n continue;\n }\n\n // Redact Windows-style absolute paths\n if (WINDOWS_DRIVE_TEST_PATTERN.test(arg)) {\n result.push(\"<path>\");\n continue;\n }\n\n // Redact email addresses\n if (EMAIL_TEST_PATTERN.test(arg)) {\n result.push(\"<email>\");\n continue;\n }\n\n result.push(arg);\n }\n\n return result;\n}\n","import * as crypto from \"node:crypto\";\nimport * as fs from \"node:fs\";\nimport * as os from \"node:os\";\nimport { parseYAML } from \"confbox\";\nimport * as path from \"pathe\";\nimport { xdgConfig } from \"xdg-basedir\";\nimport { redactSecrets } from \"#/cli/shared/logger\";\nimport { sanitizeArgv, sanitizeMessage, sanitizeStackTrace } from \"./sanitize\";\n\nexport type ErrorType = \"uncaughtException\" | \"unhandledRejection\" | \"handledError\";\n\nexport interface CrashReport {\n id: string;\n timestamp: string;\n sdkVersion: string;\n nodeVersion: string;\n osPlatform: string;\n osRelease: string;\n arch: string;\n command: string;\n argv: string[];\n errorName: string;\n errorMessage: string;\n stackTrace: string;\n errorType: ErrorType;\n userId: string | null;\n userEmail: string | null;\n}\n\ninterface BuildCrashReportOptions {\n error: unknown;\n sdkVersion: string;\n errorType: ErrorType;\n}\n\n// Maximum subcommand depth to keep (e.g., \"tailordb migrate generate\" = 3 tokens).\n// Positional arguments beyond this are potentially sensitive user input.\n// Accepted trade-off: plain-text positional args that don't match known patterns\n// (UUIDs, hex tokens, emails, paths) pass through to `command` and `argv`.\n// Full redaction would require embedding the CLI command tree here, which is fragile.\nconst MAX_COMMAND_TOKENS = 3;\n\n/**\n * Parse the command name from process.argv.\n * Extracts up to MAX_COMMAND_TOKENS non-flag arguments after the script name.\n * @returns Parsed command string\n */\nfunction parseCommand(): string {\n const args = process.argv.slice(2);\n const commandParts: string[] = [];\n for (const arg of args) {\n if (arg.startsWith(\"-\") || commandParts.length >= MAX_COMMAND_TOKENS) break;\n commandParts.push(arg);\n }\n return commandParts.join(\" \") || \"<unknown>\";\n}\n\n/**\n * Build a CrashReport data structure from an error and context.\n * All sensitive data is sanitized before inclusion: `redactSecrets` masks every registered\n * secret first, then the pattern-based sanitizers below strip known-shape values (UUIDs,\n * long hex, emails, paths) from what's left. `redactSecrets` must run first — the path\n * sanitizer intentionally keeps a path's basename (e.g. `/home/user/.../key.json` becomes\n * `<path>/key.json`), so a registered secret shaped like a path would have that basename\n * survive if the pattern sanitizer ran on it first. This report is written to a local file\n * (and optionally sent remotely) outside the CLI's normal stderr path.\n * @param options - Error, SDK version, and crash type\n * @returns Sanitized crash report\n */\nexport function buildCrashReport(options: BuildCrashReportOptions): CrashReport {\n const { error, sdkVersion, errorType } = options;\n\n const isError = error instanceof Error;\n const rawMessage = isError ? error.message : String(error);\n const rawStack = isError && error.stack ? error.stack : \"\";\n const errorName = isError ? error.name : \"UnknownError\";\n\n const currentUser = readCurrentUser();\n\n return {\n id: crypto.randomUUID(),\n timestamp: new Date().toISOString(),\n sdkVersion,\n nodeVersion: process.version,\n osPlatform: process.platform,\n osRelease: os.release(),\n arch: process.arch,\n command: sanitizeMessage(redactSecrets(parseCommand())),\n argv: sanitizeArgv(process.argv.map(redactSecrets)),\n errorName: redactSecrets(errorName),\n errorMessage: sanitizeMessage(redactSecrets(rawMessage)),\n stackTrace: sanitizeStackTrace(redactSecrets(rawStack)),\n errorType,\n userId: currentUser?.id ? redactSecrets(currentUser.id) : null,\n userEmail: currentUser?.email ? redactSecrets(currentUser.email) : null,\n };\n}\n\ntype CurrentUser = {\n id: string;\n email: string | null;\n};\n\n/**\n * Read current_user from Tailor Platform config without side effects.\n * Unlike readPlatformConfig(), this never triggers migration or logs warnings.\n * @returns The current user ID and email, or null if unavailable\n */\nfunction readCurrentUser(): CurrentUser | null {\n try {\n if (!xdgConfig) return null;\n const configPath = path.join(xdgConfig, \"tailor-platform\", \"config.yaml\");\n if (!fs.existsSync(configPath)) return null;\n const raw = parseYAML(fs.readFileSync(configPath, \"utf-8\")) as {\n current_user?: string | null;\n users?: Record<string, { email?: unknown } | undefined>;\n };\n // parseYAML returns null for empty documents\n // oxlint-disable-next-line typescript/no-unnecessary-condition\n const currentUser = raw?.current_user ?? null;\n if (!currentUser) return null;\n const email = raw.users?.[currentUser]?.email;\n return {\n id: currentUser,\n email: typeof email === \"string\" ? email : legacyEmail(currentUser),\n };\n } catch {\n return null;\n }\n}\n\nfunction legacyEmail(user: string): string | null {\n return user.includes(\"@\") ? user : null;\n}\n","import { logger } from \"#/cli/shared/logger\";\nimport { readPackageJson } from \"#/cli/shared/package-json\";\nimport { userAgentFromVersion } from \"#/cli/shared/user-agent\";\nimport { parseCrashReportConfig } from \"./config\";\nimport { buildCrashReport, type ErrorType } from \"./report\";\nimport { sendCrashReport } from \"./sender\";\nimport { writeCrashReport } from \"./writer\";\n\n/**\n * Report an unexpected crash. Writes a local crash log file and optionally\n * sends the report to a remote endpoint. Displays a user-facing message\n * with the crash log path and a command to submit the report.\n *\n * Never throws - all errors are silently caught.\n * @param error - The error that caused the crash\n * @param errorType - How the error was caught\n */\nexport async function reportCrash(error: unknown, errorType: ErrorType): Promise<void> {\n try {\n const config = parseCrashReportConfig();\n if (!config.localEnabled && !config.remoteEnabled) return;\n\n const packageJson = await readPackageJson();\n const sdkVersion = packageJson.version ?? \"unknown\";\n\n const report = buildCrashReport({ error, sdkVersion, errorType });\n\n if (config.localEnabled) {\n const filePath = writeCrashReport(report, config.localDir);\n if (filePath) {\n logger.log(\n [\n \"\",\n \"An unexpected error occurred. A crash report has been saved to:\",\n ` ${filePath}`,\n \"\",\n \"To submit this report:\",\n ` tailor crashreport send --file \"${filePath}\"`,\n ].join(\"\\n\"),\n );\n }\n }\n\n if (config.remoteEnabled) {\n const ua = userAgentFromVersion(sdkVersion);\n await sendCrashReport(report, ua);\n }\n } catch {\n // Never throw from crash reporting\n }\n}\n\n/**\n * Register global uncaughtException and unhandledRejection handlers.\n * These catch errors outside the normal cleanup flow (e.g., during\n * argument parsing). Should be called once at CLI startup before runMain.\n */\nexport function initCrashReporting(): void {\n const config = parseCrashReportConfig();\n if (!config.localEnabled && !config.remoteEnabled) return;\n\n const handleFatal = (error: unknown, errorType: ErrorType) => {\n const message = error instanceof Error ? error.message : String(error);\n logger.error(message);\n void reportCrash(error, errorType).finally(() => {\n process.exit(1);\n });\n };\n\n process.on(\"uncaughtException\", (error) => handleFatal(error, \"uncaughtException\"));\n process.on(\"unhandledRejection\", (reason) => handleFatal(reason, \"unhandledRejection\"));\n}\n"],"mappings":"0ZAiBA,SAAgB,wBAA4C,CAC1D,GAAI,EACF,MAAO,CACL,aAAc,GACd,cAAe,GACf,SAAU,EACZ,EAGF,IAAM,GAAgB,QAAQ,IAAI,4BAA8B,KAAA,CAAM,YAAY,IAAM,MAClF,GAAiB,QAAQ,IAAI,6BAA+B,MAAA,CAAO,YAAY,IAAM,KACrF,EAAW,EAAY,EAAK,KAAK,EAAW,kBAAmB,eAAe,EAAI,GAExF,MAAO,CACL,aAAc,GAAgB,IAAa,GAC3C,gBACA,UACF,CACF,CC9BA,MAGa,EAAqB,eAGrB,EAAsB,aAOnC,SAAgB,kBAAkB,EAA6B,CA2B7D,MAAO,CAzBL,iBAAiB,EAAO,KAC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AAK,SAAS,GAAG,EAAI,EAAO,IACrC,CCpHA,eAAsB,YAAY,EAAgB,EAAqC,CACrF,GAAI,CACF,IAAM,EAAS,uBAAuB,EACtC,GAAI,CAAC,EAAO,cAAgB,CAAC,EAAO,cAAe,OAGnD,IAAM,GAAa,MADO,EAAgB,EAAA,CACX,SAAW,UAEpC,EAAS,iBAAiB,CAAE,QAAO,aAAY,WAAU,CAAC,EAEhE,GAAI,EAAO,aAAc,CACvB,IAAM,EAAW,iBAAiB,EAAQ,EAAO,QAAQ,EACrD,GACF,EAAO,IACL,CACE,GACA,kEACA,KAAK,IACL,GACA,yBACA,qCAAqC,EAAS,EAChD,CAAC,CAAC,KAAK;CAAI,CACb,CAEJ,CAEI,EAAO,eAET,MAAM,gBAAgB,EADX,EAAqB,CACF,CAAE,CAEpC,MAAQ,CAER,CACF,CAOA,SAAgB,oBAA2B,CACzC,IAAM,EAAS,uBAAuB,EACtC,GAAI,CAAC,EAAO,cAAgB,CAAC,EAAO,cAAe,OAEnD,IAAM,aAAe,EAAgB,IAAyB,CAC5D,IAAM,EAAU,aAAiB,MAAQ,EAAM,QAAU,OAAO,CAAK,EACrE,EAAO,MAAM,CAAO,EACpB,YAAiB,EAAO,CAAS,CAAC,CAAC,YAAc,CAC/C,QAAQ,KAAK,CAAC,CAChB,CAAC,CACH,EAEA,QAAQ,GAAG,oBAAsB,GAAU,YAAY,EAAO,mBAAmB,CAAC,EAClF,QAAQ,GAAG,qBAAuB,GAAW,YAAY,EAAQ,oBAAoB,CAAC,CACxF"}
1
+ {"version":3,"file":"crashreport-DFpRn-LS.mjs","names":[],"sources":["../src/cli/crashreport/config.ts","../src/cli/crashreport/writer.ts","../src/cli/crashreport/sender.ts","../src/cli/crashreport/sanitize.ts","../src/cli/crashreport/report.ts","../src/cli/crashreport/index.ts"],"sourcesContent":["import * as path from \"pathe\";\nimport { isCI } from \"std-env\";\nimport { xdgConfig } from \"xdg-basedir\";\n\nexport interface CrashReportConfig {\n readonly localEnabled: boolean;\n readonly remoteEnabled: boolean;\n readonly localDir: string;\n}\n\n/**\n * Parse crash report configuration from environment variables.\n * Local crash log writing is enabled by default (opt-out via TAILOR_CRASH_REPORTS_LOCAL=off).\n * Remote sending is disabled by default (opt-in via TAILOR_CRASH_REPORTS_REMOTE=on).\n * Both are auto-disabled in CI environments.\n * @returns Crash report configuration\n */\nexport function parseCrashReportConfig(): CrashReportConfig {\n if (isCI) {\n return {\n localEnabled: false,\n remoteEnabled: false,\n localDir: \"\",\n };\n }\n\n const localEnabled = (process.env.TAILOR_CRASH_REPORTS_LOCAL ?? \"on\").toLowerCase() !== \"off\";\n const remoteEnabled = (process.env.TAILOR_CRASH_REPORTS_REMOTE ?? \"off\").toLowerCase() === \"on\";\n const localDir = xdgConfig ? path.join(xdgConfig, \"tailor-platform\", \"crash-reports\") : \"\";\n\n return {\n localEnabled: localEnabled && localDir !== \"\",\n remoteEnabled,\n localDir,\n };\n}\n","import * as fs from \"node:fs\";\nimport * as path from \"pathe\";\nimport { ensureSecretDir, writeSecretFile } from \"#/cli/shared/secret-file\";\nimport type { CrashReport } from \"./report\";\n\nconst MAX_CRASH_FILES = 10;\n\n/** Marker line that separates human-readable content from the JSON footer. */\nexport const JSON_FOOTER_MARKER = \"--- JSON ---\";\n\n/** File extension for crash log files. */\nexport const CRASH_LOG_EXTENSION = \".crash.log\";\n\n/**\n * Format a CrashReport as human-readable text for local crash log files.\n * @param report - Crash report to format\n * @returns Formatted text content\n */\nexport function formatCrashReport(report: CrashReport): string {\n const lines = [\n `Crash Report: ${report.id}`,\n `Timestamp: ${report.timestamp}`,\n `Error Type: ${report.errorType}`,\n \"\",\n \"--- Environment ---\",\n `SDK Version: ${report.sdkVersion}`,\n `Node Version: ${report.nodeVersion}`,\n `OS: ${report.osPlatform} ${report.osRelease}`,\n `Arch: ${report.arch}`,\n \"\",\n \"--- Command ---\",\n `Command: ${report.command}`,\n `Arguments: ${JSON.stringify(report.argv)}`,\n \"\",\n \"--- Error ---\",\n `Name: ${report.errorName}`,\n `Message: ${report.errorMessage}`,\n \"\",\n \"--- Stack Trace ---\",\n report.stackTrace || \"(no stack trace available)\",\n \"\",\n JSON_FOOTER_MARKER,\n JSON.stringify(report),\n \"\",\n ];\n return lines.join(\"\\n\");\n}\n\n/**\n * Generate a filename for a crash log file.\n * Format: {timestamp}-{shortId}.crash.log\n * @param report - Crash report to generate filename for\n * @returns Filename string\n */\nfunction generateFilename(report: CrashReport): string {\n const safeTimestamp = report.timestamp.replace(/[:.]/g, \"-\");\n const shortId = report.id.slice(0, 8);\n return `${safeTimestamp}-${shortId}${CRASH_LOG_EXTENSION}`;\n}\n\n/**\n * Remove old crash log files, keeping only the most recent ones.\n * @param dir - Crash log directory\n */\nfunction cleanupOldFiles(dir: string): void {\n try {\n const files = fs\n .readdirSync(dir)\n .filter((f) => f.endsWith(CRASH_LOG_EXTENSION))\n .toSorted()\n .toReversed();\n\n for (const file of files.slice(MAX_CRASH_FILES)) {\n fs.unlinkSync(path.join(dir, file));\n }\n } catch {\n // Best-effort cleanup, ignore errors\n }\n}\n\n/**\n * Write a crash report to a local file.\n * Creates the directory if it doesn't exist. Keeps only the last 10 crash files.\n * Never throws - returns the file path on success or undefined on failure.\n * @param report - Crash report to write\n * @param dir - Directory to write the crash log file to\n * @returns File path on success, undefined on failure\n */\nexport function writeCrashReport(report: CrashReport, dir: string): string | undefined {\n try {\n ensureSecretDir(dir);\n\n const filename = generateFilename(report);\n const filePath = path.join(dir, filename);\n const content = formatCrashReport(report);\n\n writeSecretFile(filePath, content);\n cleanupOldFiles(dir);\n\n return filePath;\n } catch {\n return undefined;\n }\n}\n","import type { CrashReport } from \"./report\";\n\nconst SEND_TIMEOUT_MS = 5000;\nconst PRODUCTION_ENDPOINT = \"https://sdk-error-tracking-926vh9t4cl.erp.dev/query\";\n\nconst SUBMIT_MUTATION = `\nmutation SubmitCrashReport(\n $id: String!\n $timestamp: String!\n $sdkVersion: String!\n $nodeVersion: String!\n $osPlatform: String!\n $osRelease: String!\n $arch: String!\n $command: String!\n $argv: [String]\n $errorName: String!\n $errorMessage: String!\n $stackTrace: String\n $errorType: String!\n $userId: String\n $userEmail: String\n) {\n submitCrashReport(\n id: $id\n timestamp: $timestamp\n sdkVersion: $sdkVersion\n nodeVersion: $nodeVersion\n osPlatform: $osPlatform\n osRelease: $osRelease\n arch: $arch\n command: $command\n argv: $argv\n errorName: $errorName\n errorMessage: $errorMessage\n stackTrace: $stackTrace\n errorType: $errorType\n userId: $userId\n userEmail: $userEmail\n ) {\n success\n }\n}`;\n\n/**\n * Send a crash report to the remote endpoint via GraphQL mutation.\n * Best-effort: never throws, returns boolean success.\n * @param report - Crash report to send\n * @param ua - User-Agent header value\n * @returns true if the request succeeded, false otherwise\n */\nexport async function sendCrashReport(report: CrashReport, ua: string): Promise<boolean> {\n try {\n const endpoint = process.env.TAILOR_CRASH_REPORT_ENDPOINT || PRODUCTION_ENDPOINT;\n const response = await fetch(endpoint, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"User-Agent\": ua,\n },\n body: JSON.stringify({\n query: SUBMIT_MUTATION,\n variables: report,\n }),\n signal: AbortSignal.timeout(SEND_TIMEOUT_MS),\n });\n\n if (!response.ok) return false;\n\n const data = (await response.json()) as {\n errors?: unknown[];\n data?: { submitCrashReport: { success: boolean } };\n };\n if (data.errors?.length) return false;\n return data.data?.submitCrashReport.success === true;\n } catch {\n return false;\n }\n}\n","import * as os from \"node:os\";\n\nconst HOME_DIR = os.homedir();\n\n// Patterns for sanitization (global variants for use with .replace())\nconst UUID_PATTERN = /\\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\\b/gi;\nconst LONG_HEX_PATTERN = /\\b[0-9a-fA-F]{32,}\\b/g;\nconst EMAIL_PATTERN = /\\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}\\b/g;\nconst ABSOLUTE_PATH_PATTERN = /(?:\\/(?:[\\w.@\\- ]+\\/)+[\\w.@\\- ]+)/g;\nconst WINDOWS_PATH_PATTERN = /(?:[A-Za-z]:\\\\(?:[\\w.@\\- ]+\\\\)+[\\w.@\\- ]+)/g;\nconst URL_QUERY_PATTERN = /[?&][^?\\s]*/g;\n\n// Non-global variants for single-match .test() calls (avoids lastIndex state issues)\nconst EMAIL_TEST_PATTERN = /\\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}\\b/;\nconst WINDOWS_DRIVE_TEST_PATTERN = /^[A-Za-z]:\\\\/;\n\n// SDK package path marker for relative paths\nconst SDK_PACKAGE_MARKER = \"packages/sdk/\";\n\nfunction lastSegment(filePath: string, separator: string): string {\n return filePath.split(separator).pop() ?? filePath;\n}\n\n/**\n * Sanitize a stack trace by replacing absolute paths with relative SDK paths.\n * External paths are replaced with `<external>/filename.ext`.\n * Home directories are replaced with `~/<redacted>/`.\n * @param stack - Raw stack trace string\n * @returns Sanitized stack trace\n */\nexport function sanitizeStackTrace(stack: string): string {\n // V8 stack traces start with \"ErrorType: message\\n at ...\".\n // The error message may span multiple lines before the first \" at \" frame.\n // Apply message sanitization to all message lines so secrets embedded in\n // multiline error messages are redacted consistently with errorMessage.\n const firstFrameIndex = stack.search(/\\n\\s+at /);\n let result: string;\n if (firstFrameIndex !== -1) {\n result = sanitizeMessage(stack.slice(0, firstFrameIndex)) + stack.slice(firstFrameIndex);\n } else {\n result = sanitizeMessage(stack);\n }\n\n result = result.replace(ABSOLUTE_PATH_PATTERN, (match) => {\n const sdkIndex = match.indexOf(SDK_PACKAGE_MARKER);\n if (sdkIndex !== -1) {\n return match.slice(sdkIndex);\n }\n\n if (match.startsWith(HOME_DIR)) {\n return `~/<redacted>/${lastSegment(match, \"/\")}`;\n }\n\n return `<external>/${lastSegment(match, \"/\")}`;\n });\n result = result.replace(WINDOWS_PATH_PATTERN, (match) => {\n const normalized = match.replace(/\\\\/g, \"/\");\n const sdkIndex = normalized.indexOf(SDK_PACKAGE_MARKER);\n if (sdkIndex !== -1) {\n return normalized.slice(sdkIndex);\n }\n return `<external>/${lastSegment(match, \"\\\\\")}`;\n });\n return result;\n}\n\n/**\n * Sanitize an error message by redacting sensitive information.\n * Redacts: UUIDs, long hex tokens, email addresses, absolute paths, URL query strings.\n * @param message - Raw error message\n * @returns Sanitized error message\n */\nexport function sanitizeMessage(message: string): string {\n let result = message;\n // Strip serialized request/response bodies that may contain secrets\n result = result.replace(/\\nRequest:\\s*[\\s\\S]*$/, \"\\nRequest: <redacted>\");\n result = result.replace(UUID_PATTERN, \"<uuid>\");\n result = result.replace(LONG_HEX_PATTERN, \"<redacted>\");\n result = result.replace(EMAIL_PATTERN, \"<email>\");\n result = result.replace(URL_QUERY_PATTERN, \"?<redacted>\");\n result = result.replace(ABSOLUTE_PATH_PATTERN, (match) => `<path>/${lastSegment(match, \"/\")}`);\n result = result.replace(WINDOWS_PATH_PATTERN, (match) => `<path>/${lastSegment(match, \"\\\\\")}`);\n\n return result;\n}\n\n/**\n * Sanitize process.argv by keeping command/subcommand names and redacting\n * values of sensitive flags.\n * @param argv - Raw process.argv array\n * @returns Sanitized argv array\n */\nexport function sanitizeArgv(argv: string[]): string[] {\n const result: string[] = [];\n let redactNext = false;\n\n for (const arg of argv) {\n if (redactNext) {\n // If the next token is itself a flag, treat it as a new flag rather\n // than consuming it as the previous flag's value. This avoids leaking\n // the *next* flag's value (e.g., `--verbose --workspace-id secret`\n // would otherwise expose `secret`).\n if (!arg.startsWith(\"-\")) {\n result.push(\"<redacted>\");\n redactNext = false;\n continue;\n }\n redactNext = false;\n }\n\n if (arg.startsWith(\"-\")) {\n // --flag=value: keep flag name, redact value\n const eqIndex = arg.indexOf(\"=\");\n if (eqIndex !== -1) {\n result.push(`${arg.slice(0, eqIndex)}=<redacted>`);\n continue;\n }\n\n // --flag / -f: keep flag name, redact next arg as its value\n result.push(arg);\n redactNext = true;\n continue;\n }\n\n // Redact absolute paths\n if (arg.startsWith(\"/\") && arg.includes(\"/\", 1)) {\n result.push(\"<path>\");\n continue;\n }\n\n // Redact Windows-style absolute paths\n if (WINDOWS_DRIVE_TEST_PATTERN.test(arg)) {\n result.push(\"<path>\");\n continue;\n }\n\n // Redact email addresses\n if (EMAIL_TEST_PATTERN.test(arg)) {\n result.push(\"<email>\");\n continue;\n }\n\n result.push(arg);\n }\n\n return result;\n}\n","import * as crypto from \"node:crypto\";\nimport * as fs from \"node:fs\";\nimport * as os from \"node:os\";\nimport { parseYAML } from \"confbox\";\nimport * as path from \"pathe\";\nimport { xdgConfig } from \"xdg-basedir\";\nimport { redactSecrets } from \"#/cli/shared/logger\";\nimport { sanitizeArgv, sanitizeMessage, sanitizeStackTrace } from \"./sanitize\";\n\nexport type ErrorType = \"uncaughtException\" | \"unhandledRejection\" | \"handledError\";\n\nexport interface CrashReport {\n id: string;\n timestamp: string;\n sdkVersion: string;\n nodeVersion: string;\n osPlatform: string;\n osRelease: string;\n arch: string;\n command: string;\n argv: string[];\n errorName: string;\n errorMessage: string;\n stackTrace: string;\n errorType: ErrorType;\n userId: string | null;\n userEmail: string | null;\n}\n\ninterface BuildCrashReportOptions {\n error: unknown;\n sdkVersion: string;\n errorType: ErrorType;\n}\n\n// Maximum subcommand depth to keep (e.g., \"tailordb migrate generate\" = 3 tokens).\n// Positional arguments beyond this are potentially sensitive user input.\n// Accepted trade-off: plain-text positional args that don't match known patterns\n// (UUIDs, hex tokens, emails, paths) pass through to `command` and `argv`.\n// Full redaction would require embedding the CLI command tree here, which is fragile.\nconst MAX_COMMAND_TOKENS = 3;\n\n/**\n * Parse the command name from process.argv.\n * Extracts up to MAX_COMMAND_TOKENS non-flag arguments after the script name.\n * @returns Parsed command string\n */\nfunction parseCommand(): string {\n const args = process.argv.slice(2);\n const commandParts: string[] = [];\n for (const arg of args) {\n if (arg.startsWith(\"-\") || commandParts.length >= MAX_COMMAND_TOKENS) break;\n commandParts.push(arg);\n }\n return commandParts.join(\" \") || \"<unknown>\";\n}\n\n/**\n * Build a CrashReport data structure from an error and context.\n * All sensitive data is sanitized before inclusion: `redactSecrets` masks every registered\n * secret first, then the pattern-based sanitizers below strip known-shape values (UUIDs,\n * long hex, emails, paths) from what's left. `redactSecrets` must run first — the path\n * sanitizer intentionally keeps a path's basename (e.g. `/home/user/.../key.json` becomes\n * `<path>/key.json`), so a registered secret shaped like a path would have that basename\n * survive if the pattern sanitizer ran on it first. This report is written to a local file\n * (and optionally sent remotely) outside the CLI's normal stderr path.\n * @param options - Error, SDK version, and crash type\n * @returns Sanitized crash report\n */\nexport function buildCrashReport(options: BuildCrashReportOptions): CrashReport {\n const { error, sdkVersion, errorType } = options;\n\n const isError = error instanceof Error;\n const rawMessage = isError ? error.message : String(error);\n const rawStack = isError && error.stack ? error.stack : \"\";\n const errorName = isError ? error.name : \"UnknownError\";\n\n const currentUser = readCurrentUser();\n\n return {\n id: crypto.randomUUID(),\n timestamp: new Date().toISOString(),\n sdkVersion,\n nodeVersion: process.version,\n osPlatform: process.platform,\n osRelease: os.release(),\n arch: process.arch,\n command: sanitizeMessage(redactSecrets(parseCommand())),\n argv: sanitizeArgv(process.argv.map(redactSecrets)),\n errorName: redactSecrets(errorName),\n errorMessage: sanitizeMessage(redactSecrets(rawMessage)),\n stackTrace: sanitizeStackTrace(redactSecrets(rawStack)),\n errorType,\n userId: currentUser?.id ? redactSecrets(currentUser.id) : null,\n userEmail: currentUser?.email ? redactSecrets(currentUser.email) : null,\n };\n}\n\ntype CurrentUser = {\n id: string;\n email: string | null;\n};\n\n/**\n * Read current_user from Tailor Platform config without side effects.\n * Unlike readPlatformConfig(), this never triggers migration or logs warnings.\n * @returns The current user ID and email, or null if unavailable\n */\nfunction readCurrentUser(): CurrentUser | null {\n try {\n if (!xdgConfig) return null;\n const configPath = path.join(xdgConfig, \"tailor-platform\", \"config.yaml\");\n if (!fs.existsSync(configPath)) return null;\n const raw = parseYAML(fs.readFileSync(configPath, \"utf-8\")) as {\n current_user?: string | null;\n users?: Record<string, { email?: unknown } | undefined>;\n };\n // parseYAML returns null for empty documents\n // oxlint-disable-next-line typescript/no-unnecessary-condition\n const currentUser = raw?.current_user ?? null;\n if (!currentUser) return null;\n const email = raw.users?.[currentUser]?.email;\n return {\n id: currentUser,\n email: typeof email === \"string\" ? email : legacyEmail(currentUser),\n };\n } catch {\n return null;\n }\n}\n\nfunction legacyEmail(user: string): string | null {\n return user.includes(\"@\") ? user : null;\n}\n","import { logger } from \"#/cli/shared/logger\";\nimport { readPackageJson } from \"#/cli/shared/package-json\";\nimport { userAgentFromVersion } from \"#/cli/shared/user-agent\";\nimport { parseCrashReportConfig } from \"./config\";\nimport { buildCrashReport, type ErrorType } from \"./report\";\nimport { sendCrashReport } from \"./sender\";\nimport { writeCrashReport } from \"./writer\";\n\n/**\n * Report an unexpected crash. Writes a local crash log file and optionally\n * sends the report to a remote endpoint. Displays a user-facing message\n * with the crash log path and a command to submit the report.\n *\n * Never throws - all errors are silently caught.\n * @param error - The error that caused the crash\n * @param errorType - How the error was caught\n */\nexport async function reportCrash(error: unknown, errorType: ErrorType): Promise<void> {\n try {\n const config = parseCrashReportConfig();\n if (!config.localEnabled && !config.remoteEnabled) return;\n\n const packageJson = await readPackageJson();\n const sdkVersion = packageJson.version ?? \"unknown\";\n\n const report = buildCrashReport({ error, sdkVersion, errorType });\n\n if (config.localEnabled) {\n const filePath = writeCrashReport(report, config.localDir);\n if (filePath) {\n logger.log(\n [\n \"\",\n \"An unexpected error occurred. A crash report has been saved to:\",\n ` ${filePath}`,\n \"\",\n \"To submit this report:\",\n ` tailor crashreport send --file \"${filePath}\"`,\n ].join(\"\\n\"),\n );\n }\n }\n\n if (config.remoteEnabled) {\n const ua = userAgentFromVersion(sdkVersion);\n await sendCrashReport(report, ua);\n }\n } catch {\n // Never throw from crash reporting\n }\n}\n\n/**\n * Register global uncaughtException and unhandledRejection handlers.\n * These catch errors outside the normal cleanup flow (e.g., during\n * argument parsing). Should be called once at CLI startup before runMain.\n */\nexport function initCrashReporting(): void {\n const config = parseCrashReportConfig();\n if (!config.localEnabled && !config.remoteEnabled) return;\n\n const handleFatal = (error: unknown, errorType: ErrorType) => {\n const message = error instanceof Error ? error.message : String(error);\n logger.error(message);\n void reportCrash(error, errorType).finally(() => {\n process.exit(1);\n });\n };\n\n process.on(\"uncaughtException\", (error) => handleFatal(error, \"uncaughtException\"));\n process.on(\"unhandledRejection\", (reason) => handleFatal(reason, \"unhandledRejection\"));\n}\n"],"mappings":"0ZAiBA,SAAgB,wBAA4C,CAC1D,GAAI,EACF,MAAO,CACL,aAAc,GACd,cAAe,GACf,SAAU,EACZ,EAGF,IAAM,GAAgB,QAAQ,IAAI,4BAA8B,KAAA,CAAM,YAAY,IAAM,MAClF,GAAiB,QAAQ,IAAI,6BAA+B,MAAA,CAAO,YAAY,IAAM,KACrF,EAAW,EAAY,EAAK,KAAK,EAAW,kBAAmB,eAAe,EAAI,GAExF,MAAO,CACL,aAAc,GAAgB,IAAa,GAC3C,gBACA,UACF,CACF,CC9BA,MAGa,EAAqB,eAGrB,EAAsB,aAOnC,SAAgB,kBAAkB,EAA6B,CA2B7D,MAAO,CAzBL,iBAAiB,EAAO,KACxB,cAAc,EAAO,YACrB,eAAe,EAAO,YACtB,GACA,sBACA,gBAAgB,EAAO,aACvB,iBAAiB,EAAO,cACxB,OAAO,EAAO,WAAW,GAAG,EAAO,YACnC,SAAS,EAAO,OAChB,GACA,kBACA,YAAY,EAAO,UACnB,cAAc,KAAK,UAAU,EAAO,IAAI,IACxC,GACA,gBACA,SAAS,EAAO,YAChB,YAAY,EAAO,eACnB,GACA,sBACA,EAAO,YAAc,6BACrB,GACA,EACA,KAAK,UAAU,CAAM,EACrB,EAES,CAAC,CAAC,KAAK;CAAI,CACxB,CAQA,SAAS,iBAAiB,EAA6B,CAGrD,MAAO,GAFe,EAAO,UAAU,QAAQ,QAAS,GAElC,EAAE,GADR,EAAO,GAAG,MAAM,EAAG,CACF,IAAI,GACvC,CAMA,SAAS,gBAAgB,EAAmB,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CAER,CACF,CAOA,SAAgB,oBAA2B,CACzC,IAAM,EAAS,uBAAuB,EACtC,GAAI,CAAC,EAAO,cAAgB,CAAC,EAAO,cAAe,OAEnD,IAAM,aAAe,EAAgB,IAAyB,CAC5D,IAAM,EAAU,aAAiB,MAAQ,EAAM,QAAU,OAAO,CAAK,EACrE,EAAO,MAAM,CAAO,EACpB,YAAiB,EAAO,CAAS,CAAC,CAAC,YAAc,CAC/C,QAAQ,KAAK,CAAC,CAChB,CAAC,CACH,EAEA,QAAQ,GAAG,oBAAsB,GAAU,YAAY,EAAO,mBAAmB,CAAC,EAClF,QAAQ,GAAG,qBAAuB,GAAW,YAAY,EAAQ,oBAAoB,CAAC,CACxF"}
@@ -1,2 +1,2 @@
1
- function getTemporal(){let e=globalThis.Temporal;if(!e)throw ReferenceError(`Temporal is unavailable. Use the Tailor Platform runtime or the SDK tailor-runtime Vitest environment.`);return e}const e={get PlainDate(){return getTemporal().PlainDate},get PlainTime(){return getTemporal().PlainTime},get PlainDateTime(){return getTemporal().PlainDateTime},get PlainYearMonth(){return getTemporal().PlainYearMonth},get PlainMonthDay(){return getTemporal().PlainMonthDay},get ZonedDateTime(){return getTemporal().ZonedDateTime},get Duration(){return getTemporal().Duration},get Instant(){return getTemporal().Instant},get Now(){return getTemporal().Now}};function formatDate(e){return formatDateTime(e).slice(0,10)}function formatDateTime(e){let t=e.getUTCFullYear();if(!Number.isFinite(t)||t<0||t>9999){let n=Number.isNaN(e.getTime())?`an invalid Date`:`year ${t}`;throw RangeError(`Expected a Date with a 4-digit year (0000-9999), but received ${n}`)}return e.toISOString()}function formatHoursMinutes(e,t){return`${String(e).padStart(2,`0`)}:${String(t).padStart(2,`0`)}`}function formatTime(e){if(!Number.isFinite(e.getTime()))throw RangeError(`Expected a valid Date, but received an invalid Date`);return formatHoursMinutes(e.getUTCHours(),e.getUTCMinutes())}function formatTemporal(e){let t=getTemporal();if(e instanceof t.PlainTime)return formatHoursMinutes(e.hour,e.minute);let n=e.toString({calendarName:`never`});if(!/^\d{4}-/.test(n)){let r=e instanceof t.Instant;throw RangeError(`Expected a Temporal.${r?`Instant`:`PlainDate`} with a 4-digit ${r?`UTC `:``}year (0000-9999), but received ${n}`)}return n}function serialize(e,t,n){if(e.metadata.array){if(!Array.isArray(t))return t;let r=t.map((t,r)=>serializeValue(e,t,`${n}[${r}]`));return r.every((e,n)=>e===t[n])?t:r}return serializeValue(e,t,n)}function describePathTarget(e){return e||`the top-level value`}function truncateForDescription(e){return e.length>100?`${e.slice(0,100)}...`:e}function describeReceivedValue(e){if(Array.isArray(e)){let t=e.slice(0,100),n=[...new Set(Array.from(t,e=>typeof e))];return n.length>0?`an array of ${n.join(`/`)}`:`an empty array`}if(typeof e==`string`)return`a string (${JSON.stringify(truncateForDescription(e))})`;let t=typeof e;return t===`object`?`an object`:t===`function`?`a function`:`a ${t} (${truncateForDescription(String(e))})`}function serializeValue(e,t,n){if(t==null)return t;let{type:r}=e,i=r===`date`||r===`datetime`||r===`time`,a=e.metadata.as;if(i&&(a===`date`||a===`temporal`)){let e=a===`date`?Date:r===`date`?getTemporal().PlainDate:r===`datetime`?getTemporal().Instant:getTemporal().PlainTime;if(!(t instanceof e)){let r=a===`date`?`Date`:`Temporal.${e.name}`;throw TypeError(`Expected a ${r} instance at ${describePathTarget(n)}, but received ${describeReceivedValue(t)}`)}try{return t instanceof Date?r===`datetime`?formatDateTime(t):r===`time`?formatTime(t):formatDate(t):formatTemporal(t)}catch(e){let t=e instanceof Error?e.message:String(e);throw RangeError(`Invalid date at ${describePathTarget(n)}: ${t}`,{cause:e})}}if(r!==`nested`||typeof t!=`object`||Array.isArray(t))return t;let o=t,s=o;for(let[t,r]of Object.entries(e.fields)){let e=serialize(r,o[t],n?`${n}.${t}`:t);e!==o[t]&&(s===o&&(s={...o}),Object.defineProperty(s,t,{value:e,enumerable:!0,configurable:!0,writable:!0}))}return s}function serializeDateFields(e,t){return serialize(e,t,``)}export{getTemporal as i,serializeDateFields as n,e as r,formatDate as t};
2
- //# sourceMappingURL=date-B7-oyTGE.mjs.map
1
+ function getTemporal(){let e=globalThis.Temporal;if(!e)throw ReferenceError(`Temporal is unavailable. Use the Tailor Platform runtime or the SDK tailor-runtime Vitest environment.`);return e}const e={get PlainDate(){return getTemporal().PlainDate},get PlainTime(){return getTemporal().PlainTime},get PlainDateTime(){return getTemporal().PlainDateTime},get PlainYearMonth(){return getTemporal().PlainYearMonth},get PlainMonthDay(){return getTemporal().PlainMonthDay},get ZonedDateTime(){return getTemporal().ZonedDateTime},get Duration(){return getTemporal().Duration},get Instant(){return getTemporal().Instant},get Now(){return getTemporal().Now}};function formatDate(e){return formatDateTime(e).slice(0,10)}function formatDateTime(e){let t=e.getUTCFullYear();if(!Number.isFinite(t)||t<0||t>9999){let n=Number.isNaN(e.getTime())?`an invalid Date`:`year ${t}`;throw RangeError(`Expected a Date with a 4-digit year (0000-9999), but received ${n}`)}return e.toISOString()}function formatHoursMinutes(e,t){return`${String(e).padStart(2,`0`)}:${String(t).padStart(2,`0`)}`}function formatTime(e){if(!Number.isFinite(e.getTime()))throw RangeError(`Expected a valid Date, but received an invalid Date`);return formatHoursMinutes(e.getUTCHours(),e.getUTCMinutes())}function formatTemporal(e){let t=getTemporal();if(e instanceof t.PlainTime)return formatHoursMinutes(e.hour,e.minute);let n=e.toString({calendarName:`never`});if(!/^\d{4}-/.test(n)){let r=e instanceof t.Instant;throw RangeError(`Expected a Temporal.${r?`Instant`:`PlainDate`} with a 4-digit ${r?`UTC `:``}year (0000-9999), but received ${n}`)}return n}function serialize(e,t,n){if(e.metadata.array){if(!Array.isArray(t))return t;let r=t.map((t,r)=>serializeValue(e,t,`${n}[${r}]`));return r.every((e,n)=>e===t[n])?t:r}return serializeValue(e,t,n)}function describePathTarget(e){return e||`the top-level value`}function truncateForDescription(e){return e.length>100?`${e.slice(0,100)}...`:e}function describeReceivedValue(e){if(Array.isArray(e)){let t=e.slice(0,100),n=[...new Set(Array.from(t,e=>typeof e))];return n.length>0?`an array of ${n.join(`/`)}`:`an empty array`}if(typeof e==`string`)return`a string (${JSON.stringify(truncateForDescription(e))})`;let t=typeof e;return t===`object`?`an object`:t===`function`?`a function`:`a ${t} (${truncateForDescription(String(e))})`}function dateRepresentationOf(e,t){return(e===`date`||e===`datetime`||e===`time`)&&(t===`date`||t===`temporal`)?t:void 0}function isDateRepresentationField(e,t){let n=dateRepresentationOf(e.type,e.metadata.as);return n!==void 0&&(t===void 0||n===t)}function throwInvalidDate(e,t){let n=e instanceof Error?e.message:String(e);throw RangeError(`Invalid date at ${describePathTarget(t)}: ${n}`,{cause:e})}function serializeAsDate(e,t,n){if(!(t instanceof Date))throw TypeError(`Expected a Date instance at ${describePathTarget(n)}, but received ${describeReceivedValue(t)}`);try{return e===`datetime`?formatDateTime(t):e===`time`?formatTime(t):formatDate(t)}catch(e){return throwInvalidDate(e,n)}}function serializeAsTemporal(e,t,n){let r=getTemporal(),i=e===`date`?r.PlainDate:e===`datetime`?r.Instant:r.PlainTime;if(!(t instanceof i))throw TypeError(`Expected a Temporal.${i.name} instance at ${describePathTarget(n)}, but received ${describeReceivedValue(t)}`);try{return formatTemporal(t)}catch(e){return throwInvalidDate(e,n)}}const t={date:globalThis.process?.env.__TAILOR_PLATFORM_BUNDLE_WITHOUT_DATE?void 0:serializeAsDate,temporal:globalThis.process?.env.__TAILOR_PLATFORM_BUNDLE_WITHOUT_TEMPORAL?void 0:serializeAsTemporal};function serializeValue(e,n,r){if(n==null)return n;let{type:i}=e,a=dateRepresentationOf(i,e.metadata.as);if(a){let e=t[a];if(!e)throw Error(`Serializing fields declared with as: "${a}" is not included in this bundle.`);return e(i,n,r)}if(i!==`nested`||typeof n!=`object`||Array.isArray(n))return n;let o=n,s=o;for(let[t,n]of Object.entries(e.fields)){let e=serialize(n,o[t],r?`${r}.${t}`:t);e!==o[t]&&(s===o&&(s={...o}),Object.defineProperty(s,t,{value:e,enumerable:!0,configurable:!0,writable:!0}))}return s}function hasDateRepresentationFields(e,t){return isDateRepresentationField(e,t)||Object.values(e.fields).some(e=>hasDateRepresentationFields(e,t))}function serializeDateFields(e,t){return serialize(e,t,``)}export{e as a,serializeDateFields as i,formatDate as n,getTemporal as o,hasDateRepresentationFields as r,dateRepresentationOf as t};
2
+ //# sourceMappingURL=date-Dri6Yas-.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"date-Dri6Yas-.mjs","names":[],"sources":["../src/runtime/temporal.ts","../src/runtime/date.ts"],"sourcesContent":["import type { Temporal as TemporalTypes } from \"temporal-spec\";\n\n/**\n * Get the host Temporal implementation when a value is needed.\n * @returns Host Temporal implementation\n * @internal\n */\nexport function getTemporal(): typeof TemporalTypes {\n const temporal = (globalThis as unknown as { Temporal?: typeof TemporalTypes }).Temporal;\n if (!temporal) {\n throw new ReferenceError(\n \"Temporal is unavailable. Use the Tailor Platform runtime or the SDK tailor-runtime Vitest environment.\",\n );\n }\n return temporal;\n}\n\n/**\n * Typed access to the runtime's Temporal API, without installing a polyfill.\n * Constructors are resolved on access so configuration files can load in Node.js.\n * @example\n * import { Temporal } from \"@tailor-platform/sdk/runtime\";\n * const tomorrow: Temporal.PlainDate = Temporal.Now.plainDateISO().add({ days: 1 });\n */\nexport const Temporal: typeof TemporalTypes = {\n get PlainDate() {\n return getTemporal().PlainDate;\n },\n get PlainTime() {\n return getTemporal().PlainTime;\n },\n get PlainDateTime() {\n return getTemporal().PlainDateTime;\n },\n get PlainYearMonth() {\n return getTemporal().PlainYearMonth;\n },\n get PlainMonthDay() {\n return getTemporal().PlainMonthDay;\n },\n get ZonedDateTime() {\n return getTemporal().ZonedDateTime;\n },\n get Duration() {\n return getTemporal().Duration;\n },\n get Instant() {\n return getTemporal().Instant;\n },\n get Now() {\n return getTemporal().Now;\n },\n};\n\n/** Temporal instance types supplied by the SDK, independent of TypeScript's lib settings. */\n// Type-only merging supports Temporal.PlainDate annotations on the value import.\n// oxlint-disable-next-line typescript/no-namespace\nexport declare namespace Temporal {\n /** The runtime Temporal.PlainDate instance. */\n type PlainDate = TemporalTypes.PlainDate;\n /** The runtime Temporal.PlainTime instance. */\n type PlainTime = TemporalTypes.PlainTime;\n /** The runtime Temporal.PlainDateTime instance. */\n type PlainDateTime = TemporalTypes.PlainDateTime;\n /** The runtime Temporal.PlainYearMonth instance. */\n type PlainYearMonth = TemporalTypes.PlainYearMonth;\n /** The runtime Temporal.PlainMonthDay instance. */\n type PlainMonthDay = TemporalTypes.PlainMonthDay;\n /** The runtime Temporal.ZonedDateTime instance. */\n type ZonedDateTime = TemporalTypes.ZonedDateTime;\n /** The runtime Temporal.Duration instance. */\n type Duration = TemporalTypes.Duration;\n /** The runtime Temporal.Instant instance. */\n type Instant = TemporalTypes.Instant;\n}\n","import { getTemporal } from \"./temporal\";\nimport type { FieldMetadata, TailorFieldType } from \"#/configure/types/field.types\";\nimport type { Temporal } from \"temporal-spec\";\n\n/**\n * Format a Date using its UTC calendar date.\n * @param date - Date to format\n * @returns Date string in YYYY-MM-DD format\n */\nexport function formatDate(date: Date): string {\n return formatDateTime(date).slice(0, 10);\n}\n\nfunction formatDateTime(date: Date): string {\n const year = date.getUTCFullYear();\n if (!Number.isFinite(year) || year < 0 || year > 9999) {\n const received = Number.isNaN(date.getTime()) ? \"an invalid Date\" : `year ${year}`;\n throw new RangeError(\n `Expected a Date with a 4-digit year (0000-9999), but received ${received}`,\n );\n }\n return date.toISOString();\n}\n\nfunction formatHoursMinutes(hour: number, minute: number): string {\n return `${String(hour).padStart(2, \"0\")}:${String(minute).padStart(2, \"0\")}`;\n}\n\nfunction formatTime(date: Date): string {\n if (!Number.isFinite(date.getTime())) {\n throw new RangeError(\"Expected a valid Date, but received an invalid Date\");\n }\n return formatHoursMinutes(date.getUTCHours(), date.getUTCMinutes());\n}\n\nfunction formatTemporal(value: Temporal.PlainDate | Temporal.Instant | Temporal.PlainTime): string {\n const Temporal = getTemporal();\n if (value instanceof Temporal.PlainTime) return formatHoursMinutes(value.hour, value.minute);\n const iso = value.toString({ calendarName: \"never\" });\n if (!/^\\d{4}-/.test(iso)) {\n const isInstant = value instanceof Temporal.Instant;\n throw new RangeError(\n `Expected a Temporal.${isInstant ? \"Instant\" : \"PlainDate\"} with a 4-digit ${isInstant ? \"UTC \" : \"\"}year (0000-9999), but received ${iso}`,\n );\n }\n return iso;\n}\n\ntype DateField = {\n readonly type: TailorFieldType;\n readonly metadata: FieldMetadata;\n readonly fields: Record<string, DateField>;\n};\n\ntype DateRepresentationField = {\n readonly type: TailorFieldType;\n readonly metadata: Pick<FieldMetadata, \"as\">;\n readonly fields: Record<string, DateRepresentationField>;\n};\n\nfunction serialize(field: DateField, value: unknown, path: string): unknown {\n if (field.metadata.array) {\n if (!Array.isArray(value)) return value;\n const converted = value.map((item, index) => serializeValue(field, item, `${path}[${index}]`));\n return converted.every((item, index) => item === value[index]) ? value : converted;\n }\n return serializeValue(field, value, path);\n}\n\nfunction describePathTarget(path: string): string {\n return path || \"the top-level value\";\n}\n\nconst MAX_DESCRIBED_VALUE_LENGTH = 100;\nconst MAX_DESCRIBED_ARRAY_SAMPLE = 100;\n\nfunction truncateForDescription(text: string): string {\n return text.length > MAX_DESCRIBED_VALUE_LENGTH\n ? `${text.slice(0, MAX_DESCRIBED_VALUE_LENGTH)}...`\n : text;\n}\n\nfunction describeReceivedValue(value: unknown): string {\n if (Array.isArray(value)) {\n const sample = value.slice(0, MAX_DESCRIBED_ARRAY_SAMPLE);\n const elementTypes = [...new Set(Array.from(sample, (item) => typeof item))];\n return elementTypes.length > 0 ? `an array of ${elementTypes.join(\"/\")}` : \"an empty array\";\n }\n if (typeof value === \"string\")\n return `a string (${JSON.stringify(truncateForDescription(value))})`;\n const type = typeof value;\n if (type === \"object\") return \"an object\";\n if (type === \"function\") return \"a function\";\n return `a ${type} (${truncateForDescription(String(value))})`;\n}\n\ntype DateRepresentation = \"date\" | \"temporal\";\n\n/**\n * Get the Date or Temporal representation a field converts its values to.\n * @param type - Field type\n * @param as - The field's `as` option\n * @returns The representation, or undefined when values stay strings\n * @internal\n */\nexport function dateRepresentationOf(\n type: TailorFieldType,\n as: FieldMetadata[\"as\"],\n): DateRepresentation | undefined {\n return (type === \"date\" || type === \"datetime\" || type === \"time\") &&\n (as === \"date\" || as === \"temporal\")\n ? as\n : undefined;\n}\n\nfunction isDateRepresentationField(\n field: DateRepresentationField,\n representation?: DateRepresentation,\n): boolean {\n const as = dateRepresentationOf(field.type, field.metadata.as);\n return as !== undefined && (representation === undefined || as === representation);\n}\n\ntype DateSerializer = (type: TailorFieldType, value: unknown, path: string) => string;\n\nfunction throwInvalidDate(error: unknown, path: string): never {\n const reason = error instanceof Error ? error.message : String(error);\n throw new RangeError(`Invalid date at ${describePathTarget(path)}: ${reason}`, {\n cause: error,\n });\n}\n\nfunction serializeAsDate(type: TailorFieldType, value: unknown, path: string): string {\n if (!(value instanceof Date)) {\n throw new TypeError(\n `Expected a Date instance at ${describePathTarget(path)}, but received ${describeReceivedValue(value)}`,\n );\n }\n try {\n if (type === \"datetime\") return formatDateTime(value);\n if (type === \"time\") return formatTime(value);\n return formatDate(value);\n } catch (error) {\n return throwInvalidDate(error, path);\n }\n}\n\nfunction serializeAsTemporal(type: TailorFieldType, value: unknown, path: string): string {\n const Temporal = getTemporal();\n const expected =\n type === \"date\"\n ? Temporal.PlainDate\n : type === \"datetime\"\n ? Temporal.Instant\n : Temporal.PlainTime;\n if (!(value instanceof expected)) {\n throw new TypeError(\n `Expected a Temporal.${expected.name} instance at ${describePathTarget(path)}, but received ${describeReceivedValue(value)}`,\n );\n }\n try {\n return formatTemporal(value);\n } catch (error) {\n return throwInvalidDate(error, path);\n }\n}\n\ntype MaybeProcessGlobal = { process?: { env: Record<string, string | undefined> } };\n\nconst dateSerializers: Record<DateRepresentation, DateSerializer | undefined> = {\n date: (globalThis as MaybeProcessGlobal).process?.env.__TAILOR_PLATFORM_BUNDLE_WITHOUT_DATE\n ? undefined\n : serializeAsDate,\n temporal: (globalThis as MaybeProcessGlobal).process?.env\n .__TAILOR_PLATFORM_BUNDLE_WITHOUT_TEMPORAL\n ? undefined\n : serializeAsTemporal,\n};\n\nfunction serializeValue(field: DateField, value: unknown, path: string): unknown {\n if (value === null || value === undefined) return value;\n const { type } = field;\n const as = dateRepresentationOf(type, field.metadata.as);\n if (as) {\n const serializeAs = dateSerializers[as];\n if (!serializeAs) {\n throw new Error(\n `Serializing fields declared with as: \"${as}\" is not included in this bundle.`,\n );\n }\n return serializeAs(type, value, path);\n }\n if (type !== \"nested\" || typeof value !== \"object\" || Array.isArray(value)) return value;\n const record = value as Record<string, unknown>;\n let result = record;\n for (const [key, child] of Object.entries(field.fields)) {\n const converted = serialize(child, record[key], path ? `${path}.${key}` : key);\n if (converted !== record[key]) {\n if (result === record) result = { ...record };\n Object.defineProperty(result, key, {\n value: converted,\n enumerable: true,\n configurable: true,\n writable: true,\n });\n }\n }\n return result;\n}\n\n/**\n * Check whether a field or any of its nested fields uses a Date or Temporal representation.\n * @param field - Field to inspect\n * @param representation - Only match fields using this representation\n * @returns Whether serializeDateFields would convert any value of the field\n * @internal\n */\nexport function hasDateRepresentationFields(\n field: DateRepresentationField,\n representation?: DateRepresentation,\n): boolean {\n return (\n isDateRepresentationField(field, representation) ||\n Object.values(field.fields).some((child) => hasDateRepresentationFields(child, representation))\n );\n}\n\n/**\n * Convert fields using Date or Temporal representations to date, datetime, or time strings.\n * @param field - Field defining the value's shape\n * @param value - Value to serialize\n * @returns Value with Date and Temporal fields converted to strings\n * @internal\n */\nexport function serializeDateFields(field: DateField, value: unknown): unknown {\n return serialize(field, value, \"\");\n}\n"],"mappings":"AAOA,SAAgB,aAAoC,CAClD,IAAM,EAAY,WAA8D,SAChF,GAAI,CAAC,EACH,MAAU,eACR,wGACF,EAEF,OAAO,CACT,CASA,MAAa,EAAiC,CAC5C,IAAI,WAAY,CACd,OAAO,YAAY,CAAC,CAAC,SACvB,EACA,IAAI,WAAY,CACd,OAAO,YAAY,CAAC,CAAC,SACvB,EACA,IAAI,eAAgB,CAClB,OAAO,YAAY,CA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,GAAI,EAAI,CACN,IAAM,EAAc,EAAgB,GACpC,GAAI,CAAC,EACH,MAAU,MACR,yCAAyC,EAAG,kCAC9C,EAEF,OAAO,EAAY,EAAM,EAAO,CAAI,CACtC,CACA,GAAI,IAAS,UAAY,OAAO,GAAU,UAAY,MAAM,QAAQ,CAAK,EAAG,OAAO,EACnF,IAAM,EAAS,EACX,EAAS,EACb,IAAK,GAAM,CAAC,EAAK,KAAU,OAAO,QAAQ,EAAM,MAAM,EAAG,CACvD,IAAM,EAAY,UAAU,EAAO,EAAO,GAAM,EAAO,GAAG,EAAK,GAAG,IAAQ,CAAG,EACzE,IAAc,EAAO,KACnB,IAAW,IAAQ,EAAS,CAAE,GAAG,CAAO,GAC5C,OAAO,eAAe,EAAQ,EAAK,CACjC,MAAO,EACP,WAAY,GACZ,aAAc,GACd,SAAU,EACZ,CAAC,EAEL,CACA,OAAO,CACT,CASA,SAAgB,4BACd,EACA,EACS,CACT,OACE,0BAA0B,EAAO,CAAc,GAC/C,OAAO,OAAO,EAAM,MAAM,CAAC,CAAC,KAAM,GAAU,4BAA4B,EAAO,CAAc,CAAC,CAElG,CASA,SAAgB,oBAAoB,EAAkB,EAAyB,CAC7E,OAAO,UAAU,EAAO,EAAO,EAAE,CACnC"}
@@ -1,7 +1,7 @@
1
- import{i as e}from"./logger-72hM4JWZ.mjs";function shellQuote(e){return process.platform===`win32`?/^[A-Za-z0-9_./:=@+\\-]+$/.test(e)?e:`"${e.replaceAll(`"`,`\\"`)}"`:/^[A-Za-z0-9_./:=@+-]+$/.test(e)?e:`'${e.replaceAll(`'`,`'"'"'`)}'`}function needsArgvRendering(e){return process.platform===`win32`&&e.some(e=>/[%$!]/.test(e))}function formatCopyableCommand(e){return needsArgvRendering(e)?`argv ${JSON.stringify(e)}`:e.map(shellQuote).join(` `)}function formatNextAction(e){let t=[e.command,...e.args],n=formatCopyableCommand(t);return needsArgvRendering(t)?`with ${n}`:`\`${n}\``}function formatError(t){let n=[e.error(`Error${t.code?` [${t.code}]`:``}: ${t.message}`)];return t.details&&n.push(`\n ${e.dim(`Details:`)} ${t.details.split(`
1
+ import{o as e}from"./logger-Db-YRTwK.mjs";function shellQuote(e){return process.platform===`win32`?/^[A-Za-z0-9_./:=@+\\-]+$/.test(e)?e:`"${e.replaceAll(`"`,`\\"`)}"`:/^[A-Za-z0-9_./:=@+-]+$/.test(e)?e:`'${e.replaceAll(`'`,`'"'"'`)}'`}function needsArgvRendering(e){return process.platform===`win32`&&e.some(e=>/[%$!]/.test(e))}function formatCopyableCommand(e){return needsArgvRendering(e)?`argv ${JSON.stringify(e)}`:e.map(shellQuote).join(` `)}function formatNextAction(e){let t=[e.command,...e.args],n=formatCopyableCommand(t);return needsArgvRendering(t)?`with ${n}`:`\`${n}\``}function formatError(t){let n=[e.error(`Error${t.code?` [${t.code}]`:``}: ${t.message}`)];return t.details&&n.push(`\n ${e.dim(`Details:`)} ${t.details.split(`
2
2
  `).join(`
3
3
  `)}`),t.suggestion&&n.push(`\n ${e.info(`Suggestion:`)} ${t.suggestion.split(`
4
4
  `).join(`
5
5
  `)}`),t.command&&n.push(`\n ${e.dim(`Help:`)} Run \`tailor ${t.command} --help\` for usage information.`),t.next&&n.push(`\n ${e.info(`Next:`)} Run ${formatNextAction(t.next)}.`),n.join(``)}function CLIError(e){let t=Error(e.message,e.cause===void 0?void 0:{cause:e.cause});return t.name=`CLIError`,t.code=e.code,t.details=e.details,t.suggestion=e.suggestion,t.command=e.command,t.next=e.next,t.context=e.context,t.format=()=>formatError(t),t}function isCLIError(e){return e instanceof Error&&e.name===`CLIError`}function errorSummary(e){return isCLIError(e)?[e.message,e.details,e.suggestion].filter(Boolean).join(`
6
6
  `):e instanceof Error?e.message:String(e)}function internalError(e,t){return Error(e,t)}function toError(e){return e instanceof Error?e:Error(String(e),{cause:e})}const t=/does not provide an export named '(?!default')([^']+)'/;function typeOnlyImportHint(e){if(!(e instanceof SyntaxError))return;let n=t.exec(e.message)?.[1];if(n)return`If '${n}' is a type, import it with \`import type\` (or the inline \`type\` modifier). The CLI runs TypeScript by stripping types from each file in isolation, so type-only exports do not exist at runtime. Set "verbatimModuleSyntax": true in tsconfig.json to catch this at typecheck.`}export{internalError as a,typeOnlyImportHint as c,formatNextAction as i,errorSummary as n,isCLIError as o,formatCopyableCommand as r,toError as s,CLIError as t};
7
- //# sourceMappingURL=errors-BjJnpXkK.mjs.map
7
+ //# sourceMappingURL=errors-C9zGf4nz.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"errors-BjJnpXkK.mjs","names":[],"sources":["../src/cli/shared/errors.ts"],"sourcesContent":["import { styles } from \"./logger\";\nimport type { Jsonifiable } from \"type-fest\";\n\n/**\n * Options for creating a CLI error\n */\ninterface CLIErrorOptions {\n /** Stable machine-readable failure code, such as `WORKSPACE_NOT_FOUND`. */\n code: string;\n message: string;\n details?: string;\n suggestion?: string;\n command?: string;\n next?: CLIErrorNextAction;\n context?: Readonly<Record<string, Jsonifiable | undefined>>;\n cause?: unknown;\n}\n\nexport type CLIErrorNextAction = {\n /** Executable name, such as `tailor`. */\n command: string;\n /** Arguments passed directly to the executable. */\n args: readonly string[];\n};\n\n/**\n * CLI error interface with formatted output\n */\nexport interface CLIError extends Error {\n readonly code: string;\n readonly details?: string;\n readonly suggestion?: string;\n readonly command?: string;\n readonly next?: CLIErrorNextAction;\n readonly context?: Readonly<Record<string, Jsonifiable | undefined>>;\n format(): string;\n}\n\ntype CLIErrorInternal = Error & {\n code: string;\n details?: string;\n suggestion?: string;\n command?: string;\n next?: CLIErrorNextAction;\n context?: Readonly<Record<string, Jsonifiable | undefined>>;\n format(): string;\n};\n\nfunction shellQuote(value: string): string {\n if (process.platform === \"win32\") {\n if (/^[A-Za-z0-9_./:=@+\\\\-]+$/.test(value)) return value;\n return `\"${value.replaceAll('\"', '\\\\\"')}\"`;\n }\n if (/^[A-Za-z0-9_./:=@+-]+$/.test(value)) return value;\n return `'${value.replaceAll(\"'\", `'\"'\"'`)}'`;\n}\n\nfunction needsArgvRendering(argv: readonly string[]): boolean {\n // cmd.exe/PowerShell expand %, $, and ! even inside double quotes, so no\n // quoting can keep such values literal on Windows.\n return process.platform === \"win32\" && argv.some((value) => /[%$!]/.test(value));\n}\n\n/**\n * Render an argv array as a copyable command line for the current platform's shell\n * @param {readonly string[]} argv - Executable name followed by its arguments\n * @returns {string} A shell-quoted command line, or an `argv [...]` JSON rendering when the platform shell cannot keep a value literal\n */\nexport function formatCopyableCommand(argv: readonly string[]): string {\n if (needsArgvRendering(argv)) {\n return `argv ${JSON.stringify(argv)}`;\n }\n return argv.map(shellQuote).join(\" \");\n}\n\n/**\n * Format an executable and argv as a shell-safe user-facing command.\n * @param next - Executable and arguments to format\n * @returns Shell command, or an argv representation when shell quoting is unsafe\n */\nexport function formatNextAction(next: CLIErrorNextAction): string {\n const argv = [next.command, ...next.args];\n const rendered = formatCopyableCommand(argv);\n return needsArgvRendering(argv) ? `with ${rendered}` : `\\`${rendered}\\``;\n}\n\n/**\n * Format CLI error for output\n * @param error - CLIError instance to format\n * @returns Formatted error message\n */\nfunction formatError(error: CLIError): string {\n const parts: string[] = [\n styles.error(`Error${error.code ? ` [${error.code}]` : \"\"}: ${error.message}`),\n ];\n\n if (error.details) {\n parts.push(`\\n ${styles.dim(\"Details:\")} ${error.details.split(\"\\n\").join(\"\\n \")}`);\n }\n\n if (error.suggestion) {\n parts.push(`\\n ${styles.info(\"Suggestion:\")} ${error.suggestion.split(\"\\n\").join(\"\\n \")}`);\n }\n\n if (error.command) {\n parts.push(\n `\\n ${styles.dim(\"Help:\")} Run \\`tailor ${error.command} --help\\` for usage information.`,\n );\n }\n\n if (error.next) {\n parts.push(`\\n ${styles.info(\"Next:\")} Run ${formatNextAction(error.next)}.`);\n }\n\n return parts.join(\"\");\n}\n\n/**\n * Create a CLI error with formatted output\n * @param options - Options to construct a CLIError\n * @returns Constructed CLIError instance\n */\nexport function CLIError(options: CLIErrorOptions): CLIError {\n const error = new Error(\n options.message,\n options.cause === undefined ? undefined : { cause: options.cause },\n ) as CLIErrorInternal;\n error.name = \"CLIError\";\n error.code = options.code;\n error.details = options.details;\n error.suggestion = options.suggestion;\n error.command = options.command;\n error.next = options.next;\n error.context = options.context;\n error.format = () => formatError(error);\n return error;\n}\n\n/**\n * Type guard to check if an error is a CLIError\n * @param error - Error to check\n * @returns True if the error is a CLIError\n */\nexport function isCLIError(error: unknown): error is CLIError {\n return error instanceof Error && error.name === \"CLIError\";\n}\n\n/**\n * Summarize a failure as plain text for reports that carry a single error string.\n * CLI errors contribute their details and suggestion so the remediation survives.\n * @param error - Failure to summarize\n * @returns Message followed by any details and suggestion, one per line\n */\nexport function errorSummary(error: unknown): string {\n if (isCLIError(error)) {\n return [error.message, error.details, error.suggestion].filter(Boolean).join(\"\\n\");\n }\n return error instanceof Error ? error.message : String(error);\n}\n\n/**\n * Create an error for an SDK invariant violation that no user action can fix.\n * The result is a plain Error, so JSON output reports it as `UNEXPECTED_ERROR`\n * and crash reporting treats it like any other unexpected failure.\n * @param message - Description of the violated invariant\n * @param options - Standard Error options, such as `cause`\n * @returns Plain Error instance\n */\nexport function internalError(message: string, options?: ErrorOptions): Error {\n return new Error(message, options);\n}\n\n/**\n * Convert a caught value into an Error, keeping Error instances as-is\n * @param value - Caught value\n * @returns The value itself when it is an Error, otherwise an Error of its string form with the value as `cause`\n */\nexport function toError(value: unknown): Error {\n return value instanceof Error ? value : new Error(String(value), { cause: value });\n}\n\nconst MISSING_NAMED_EXPORT_PATTERN = /does not provide an export named '(?!default')([^']+)'/;\n\n/**\n * Suggest `import type` when importing user code fails on a missing named\n * export. The CLI strips types from each file in isolation, so a type-only\n * export does not exist at runtime and a plain import of it fails to link.\n * @param error - Error thrown while importing user modules\n * @returns Suggestion text, or undefined when the error is not that failure\n */\nexport function typeOnlyImportHint(error: unknown): string | undefined {\n if (!(error instanceof SyntaxError)) return undefined;\n const name = MISSING_NAMED_EXPORT_PATTERN.exec(error.message)?.[1];\n if (!name) return undefined;\n return (\n `If '${name}' is a type, import it with \\`import type\\` (or the inline \\`type\\` modifier). ` +\n \"The CLI runs TypeScript by stripping types from each file in isolation, so type-only exports do not exist at runtime. \" +\n 'Set \"verbatimModuleSyntax\": true in tsconfig.json to catch this at typecheck.'\n );\n}\n"],"mappings":"0CAgDA,SAAS,WAAW,EAAuB,CAMzC,OALI,QAAQ,WAAa,QACnB,2BAA2B,KAAK,CAAK,EAAU,EAC5C,IAAI,EAAM,WAAW,IAAK,KAAK,EAAE,GAEtC,yBAAyB,KAAK,CAAK,EAAU,EAC1C,IAAI,EAAM,WAAW,IAAK,OAAO,EAAE,EAC5C,CAEA,SAAS,mBAAmB,EAAkC,CAG5D,OAAO,QAAQ,WAAa,SAAW,EAAK,KAAM,GAAU,QAAQ,KAAK,CAAK,CAAC,CACjF,CAOA,SAAgB,sBAAsB,EAAiC,CAIrE,OAHI,mBAAmB,CAAI,EAClB,QAAQ,KAAK,UAAU,CAAI,IAE7B,EAAK,IAAI,UAAU,CAAC,CAAC,KAAK,GAAG,CACtC,CAOA,SAAgB,iBAAiB,EAAkC,CACjE,IAAM,EAAO,CAAC,EAAK,QAAS,GAAG,EAAK,IAAI,EAClC,EAAW,sBAAsB,CAAI,EAC3C,OAAO,mBAAmB,CAAI,EAAI,QAAQ,IAAa,KAAK,EAAS,GACvE,CAOA,SAAS,YAAY,EAAyB,CAC5C,IAAM,EAAkB,CACtB,EAAO,MAAM,QAAQ,EAAM,KAAO,KAAK,EAAM,KAAK,GAAK,GAAG,IAAI,EAAM,SAAS,CAC/E,EAoBA,OAlBI,EAAM,SACR,EAAM,KAAK,OAAO,EAAO,IAAI,UAAU,EAAE,GAAG,EAAM,QAAQ,MAAM;CAAI,CAAC,CAAC,KAAK;GAAM,GAAG,EAGlF,EAAM,YACR,EAAM,KAAK,OAAO,EAAO,KAAK,aAAa,EAAE,GAAG,EAAM,WAAW,MAAM;CAAI,CAAC,CAAC,KAAK;GAAM,GAAG,EAGzF,EAAM,SACR,EAAM,KACJ,OAAO,EAA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ent":["import { styles } from \"./logger\";\nimport type { Jsonifiable } from \"type-fest\";\n\n/**\n * Options for creating a CLI error\n */\ninterface CLIErrorOptions {\n /** Stable machine-readable failure code, such as `WORKSPACE_NOT_FOUND`. */\n code: string;\n message: string;\n details?: string;\n suggestion?: string;\n command?: string;\n next?: CLIErrorNextAction;\n context?: Readonly<Record<string, Jsonifiable | undefined>>;\n cause?: unknown;\n}\n\nexport type CLIErrorNextAction = {\n /** Executable name, such as `tailor`. */\n command: string;\n /** Arguments passed directly to the executable. */\n args: readonly string[];\n};\n\n/**\n * CLI error interface with formatted output\n */\nexport interface CLIError extends Error {\n readonly code: string;\n readonly details?: string;\n readonly suggestion?: string;\n readonly command?: string;\n readonly next?: CLIErrorNextAction;\n readonly context?: Readonly<Record<string, Jsonifiable | undefined>>;\n format(): string;\n}\n\ntype CLIErrorInternal = Error & {\n code: string;\n details?: string;\n suggestion?: string;\n command?: string;\n next?: CLIErrorNextAction;\n context?: Readonly<Record<string, Jsonifiable | undefined>>;\n format(): string;\n};\n\nfunction shellQuote(value: string): string {\n if (process.platform === \"win32\") {\n if (/^[A-Za-z0-9_./:=@+\\\\-]+$/.test(value)) return value;\n return `\"${value.replaceAll('\"', '\\\\\"')}\"`;\n }\n if (/^[A-Za-z0-9_./:=@+-]+$/.test(value)) return value;\n return `'${value.replaceAll(\"'\", `'\"'\"'`)}'`;\n}\n\nfunction needsArgvRendering(argv: readonly string[]): boolean {\n // cmd.exe/PowerShell expand %, $, and ! even inside double quotes, so no\n // quoting can keep such values literal on Windows.\n return process.platform === \"win32\" && argv.some((value) => /[%$!]/.test(value));\n}\n\n/**\n * Render an argv array as a copyable command line for the current platform's shell\n * @param {readonly string[]} argv - Executable name followed by its arguments\n * @returns {string} A shell-quoted command line, or an `argv [...]` JSON rendering when the platform shell cannot keep a value literal\n */\nexport function formatCopyableCommand(argv: readonly string[]): string {\n if (needsArgvRendering(argv)) {\n return `argv ${JSON.stringify(argv)}`;\n }\n return argv.map(shellQuote).join(\" \");\n}\n\n/**\n * Format an executable and argv as a shell-safe user-facing command.\n * @param next - Executable and arguments to format\n * @returns Shell command, or an argv representation when shell quoting is unsafe\n */\nexport function formatNextAction(next: CLIErrorNextAction): string {\n const argv = [next.command, ...next.args];\n const rendered = formatCopyableCommand(argv);\n return needsArgvRendering(argv) ? `with ${rendered}` : `\\`${rendered}\\``;\n}\n\n/**\n * Format CLI error for output\n * @param error - CLIError instance to format\n * @returns Formatted error message\n */\nfunction formatError(error: CLIError): string {\n const parts: string[] = [\n styles.error(`Error${error.code ? ` [${error.code}]` : \"\"}: ${error.message}`),\n ];\n\n if (error.details) {\n parts.push(`\\n ${styles.dim(\"Details:\")} ${error.details.split(\"\\n\").join(\"\\n \")}`);\n }\n\n if (error.suggestion) {\n parts.push(`\\n ${styles.info(\"Suggestion:\")} ${error.suggestion.split(\"\\n\").join(\"\\n \")}`);\n }\n\n if (error.command) {\n parts.push(\n `\\n ${styles.dim(\"Help:\")} Run \\`tailor ${error.command} --help\\` for usage information.`,\n );\n }\n\n if (error.next) {\n parts.push(`\\n ${styles.info(\"Next:\")} Run ${formatNextAction(error.next)}.`);\n }\n\n return parts.join(\"\");\n}\n\n/**\n * Create a CLI error with formatted output\n * @param options - Options to construct a CLIError\n * @returns Constructed CLIError instance\n */\nexport function CLIError(options: CLIErrorOptions): CLIError {\n const error = new Error(\n options.message,\n options.cause === undefined ? undefined : { cause: options.cause },\n ) as CLIErrorInternal;\n error.name = \"CLIError\";\n error.code = options.code;\n error.details = options.details;\n error.suggestion = options.suggestion;\n error.command = options.command;\n error.next = options.next;\n error.context = options.context;\n error.format = () => formatError(error);\n return error;\n}\n\n/**\n * Type guard to check if an error is a CLIError\n * @param error - Error to check\n * @returns True if the error is a CLIError\n */\nexport function isCLIError(error: unknown): error is CLIError {\n return error instanceof Error && error.name === \"CLIError\";\n}\n\n/**\n * Summarize a failure as plain text for reports that carry a single error string.\n * CLI errors contribute their details and suggestion so the remediation survives.\n * @param error - Failure to summarize\n * @returns Message followed by any details and suggestion, one per line\n */\nexport function errorSummary(error: unknown): string {\n if (isCLIError(error)) {\n return [error.message, error.details, error.suggestion].filter(Boolean).join(\"\\n\");\n }\n return error instanceof Error ? error.message : String(error);\n}\n\n/**\n * Create an error for an SDK invariant violation that no user action can fix.\n * The result is a plain Error, so JSON output reports it as `UNEXPECTED_ERROR`\n * and crash reporting treats it like any other unexpected failure.\n * @param message - Description of the violated invariant\n * @param options - Standard Error options, such as `cause`\n * @returns Plain Error instance\n */\nexport function internalError(message: string, options?: ErrorOptions): Error {\n return new Error(message, options);\n}\n\n/**\n * Convert a caught value into an Error, keeping Error instances as-is\n * @param value - Caught value\n * @returns The value itself when it is an Error, otherwise an Error of its string form with the value as `cause`\n */\nexport function toError(value: unknown): Error {\n return value instanceof Error ? value : new Error(String(value), { cause: value });\n}\n\nconst MISSING_NAMED_EXPORT_PATTERN = /does not provide an export named '(?!default')([^']+)'/;\n\n/**\n * Suggest `import type` when importing user code fails on a missing named\n * export. The CLI strips types from each file in isolation, so a type-only\n * export does not exist at runtime and a plain import of it fails to link.\n * @param error - Error thrown while importing user modules\n * @returns Suggestion text, or undefined when the error is not that failure\n */\nexport function typeOnlyImportHint(error: unknown): string | undefined {\n if (!(error instanceof SyntaxError)) return undefined;\n const name = MISSING_NAMED_EXPORT_PATTERN.exec(error.message)?.[1];\n if (!name) return undefined;\n return (\n `If '${name}' is a type, import it with \\`import type\\` (or the inline \\`type\\` modifier). ` +\n \"The CLI runs TypeScript by stripping types from each file in isolation, so type-only exports do not exist at runtime. \" +\n 'Set \"verbatimModuleSyntax\": true in tsconfig.json to catch this at typecheck.'\n );\n}\n"],"mappings":"0CAgDA,SAAS,WAAW,EAAuB,CAMzC,OALI,QAAQ,WAAa,QACnB,2BAA2B,KAAK,CAAK,EAAU,EAC5C,IAAI,EAAM,WAAW,IAAK,KAAK,EAAE,GAEtC,yBAAyB,KAAK,CAAK,EAAU,EAC1C,IAAI,EAAM,WAAW,IAAK,OAAO,EAAE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QAAU,EAAQ,QACxB,EAAM,WAAa,EAAQ,WAC3B,EAAM,QAAU,EAAQ,QACxB,EAAM,KAAO,EAAQ,KACrB,EAAM,QAAU,EAAQ,QACxB,EAAM,WAAe,YAAY,CAAK,EAC/B,CACT,CAOA,SAAgB,WAAW,EAAmC,CAC5D,OAAO,aAAiB,OAAS,EAAM,OAAS,UAClD,CAQA,SAAgB,aAAa,EAAwB,CAInD,OAHI,WAAW,CAAK,EACX,CAAC,EAAM,QAAS,EAAM,QAAS,EAAM,UAAU,CAAC,CAAC,OAAO,OAAO,CAAC,CAAC,KAAK;CAAI,EAE5E,aAAiB,MAAQ,EAAM,QAAU,OAAO,CAAK,CAC9D,CAUA,SAAgB,cAAc,EAAiB,EAA+B,CAC5E,OAAW,MAAM,EAAS,CAAO,CACnC,CAOA,SAAgB,QAAQ,EAAuB,CAC7C,OAAO,aAAiB,MAAQ,EAAY,MAAM,OAAO,CAAK,EAAG,CAAE,MAAO,CAAM,CAAC,CACnF,CAEA,MAAM,EAA+B,yDASrC,SAAgB,mBAAmB,EAAoC,CACrE,GAAI,EAAE,aAAiB,aAAc,OACrC,IAAM,EAAO,EAA6B,KAAK,EAAM,OAAO,CAAC,GAAG,GAC3D,KACL,MACE,OAAO,EAAK,mRAIhB"}
@@ -0,0 +1,2 @@
1
+ import*as e from"globals";const t=e.default??e,n=/* @__PURE__ */ new Set([...Object.keys(t.builtin??{}),...Object.keys(t[`shared-node-browser`]??{})]),r=new Set(Object.keys(t.node??{}).filter(e=>!n.has(e)));export{r as n,n as t};
2
+ //# sourceMappingURL=es-builtins-SfvXRVoG.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"es-builtins-BHCXINQp.mjs","names":[],"sources":["../src/utils/es-builtins.ts"],"sourcesContent":["import * as globals from \"globals\";\n\ntype GlobalsShape = {\n builtin?: Record<string, boolean>;\n \"shared-node-browser\"?: Record<string, boolean>;\n node?: Record<string, boolean>;\n};\n\nconst globalsMap: GlobalsShape =\n (globals as unknown as { default?: GlobalsShape }).default ?? globals;\n\n/**\n * Runtime globals available in the PF execution environment.\n * Identifiers in this set are excluded from free variable detection\n * since they are always available in the runtime environment.\n *\n * Combines globals.builtin (ECMAScript language builtins) and\n * globals['shared-node-browser'] (shared runtime globals like\n * console, fetch, setTimeout, etc.) from the `globals` npm package.\n */\nexport const ES_BUILTINS = new Set([\n ...Object.keys(globalsMap.builtin ?? {}),\n ...Object.keys(globalsMap[\"shared-node-browser\"] ?? {}),\n]);\n\n/**\n * Node-only ambient globals (`process`, `Buffer`, `require`, `setImmediate`,\n * etc.) that `@types/node` puts in the global scope but that are absent from\n * `ES_BUILTINS`, so the Tailor Platform runtime never defines them. Sourced\n * from the same `globals` package as `ES_BUILTINS` instead of a hand-curated\n * list, so a newly recognized Node-only global can't be silently omitted.\n */\nexport const NODE_ONLY_GLOBALS = new Set(\n Object.keys(globalsMap.node ?? {}).filter((name) => !ES_BUILTINS.has(name)),\n);\n"],"mappings":"0BAQA,MAAM,EACH,EAAkD,SAAW,EAWnD,EAAc,IAAI,IAAI,CACjC,GAAG,OAAO,KAAK,EAAW,SAAW,CAAC,CAAC,EACvC,GAAG,OAAO,KAAK,EAAW,wBAA0B,CAAC,CAAC,CACxD,CAAC,EASY,EAAoB,IAAI,IACnC,OAAO,KAAK,EAAW,MAAQ,CAAC,CAAC,CAAC,CAAC,OAAQ,GAAS,CAAC,EAAY,IAAI,CAAI,CAAC,CAC5E"}
1
+ {"version":3,"file":"es-builtins-SfvXRVoG.mjs","names":[],"sources":["../src/utils/es-builtins.ts"],"sourcesContent":["import * as globals from \"globals\";\n\ntype GlobalsShape = {\n builtin?: Record<string, boolean>;\n \"shared-node-browser\"?: Record<string, boolean>;\n node?: Record<string, boolean>;\n};\n\nconst globalsMap: GlobalsShape =\n (globals as unknown as { default?: GlobalsShape }).default ?? globals;\n\n/**\n * Runtime globals available in the PF execution environment.\n * Identifiers in this set are excluded from free variable detection\n * since they are always available in the runtime environment.\n *\n * Combines globals.builtin (ECMAScript language builtins) and\n * globals['shared-node-browser'] (shared runtime globals like\n * console, fetch, setTimeout, etc.) from the `globals` npm package.\n */\nexport const ES_BUILTINS = new Set([\n ...Object.keys(globalsMap.builtin ?? {}),\n ...Object.keys(globalsMap[\"shared-node-browser\"] ?? {}),\n]);\n\n/**\n * Node-only ambient globals (`process`, `Buffer`, `require`, `setImmediate`,\n * etc.) that `@types/node` puts in the global scope but that are absent from\n * `ES_BUILTINS`, so the Tailor Platform runtime never defines them. Sourced\n * from the same `globals` package as `ES_BUILTINS` instead of a hand-curated\n * list, so a newly recognized Node-only global can't be silently omitted.\n */\nexport const NODE_ONLY_GLOBALS = new Set(\n Object.keys(globalsMap.node ?? {}).filter((name) => !ES_BUILTINS.has(name)),\n);\n"],"mappings":"0BAQA,MAAM,EACH,EAAkD,SAAW,EAWnD,kBAAc,IAAI,IAAI,CACjC,GAAG,OAAO,KAAK,EAAW,SAAW,CAAC,CAAC,EACvC,GAAG,OAAO,KAAK,EAAW,wBAA0B,CAAC,CAAC,CACxD,CAAC,EASY,EAAoB,IAAI,IACnC,OAAO,KAAK,EAAW,MAAQ,CAAC,CAAC,CAAC,CAAC,OAAQ,GAAS,CAAC,EAAY,IAAI,CAAI,CAAC,CAC5E"}
@@ -0,0 +1,2 @@
1
+ import{n as e,o as t,t as n}from"./date-Dri6Yas-.mjs";const r={uuid:/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,date:/^(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})$/,time:/^(?<hour>[01]\d|2[0-3]):(?<minute>[0-5]\d)$/,datetime:/^(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})[Tt](?<hour>[01]\d|2[0-3]):(?<minute>[0-5]\d):(?<second>[0-5]\d|60)(\.(?<fraction>\d+))?(?<offset>[Zz]|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/,decimal:/^-?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/};function isNestedObject(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Date)}function validateBaseValue(e){let{field:t,value:n,pathArray:i,issues:a}=e,o=i.length>0?i:void 0,s=a.length;switch(t.type){case`string`:typeof n!=`string`&&a.push({message:`Expected a string: received ${String(n)}`,path:o});break;case`integer`:(typeof n!=`number`||!Number.isInteger(n))&&a.push({message:`Expected an integer: received ${String(n)}`,path:o});break;case`float`:(typeof n!=`number`||!Number.isFinite(n))&&a.push({message:`Expected a number: received ${String(n)}`,path:o});break;case`boolean`:typeof n!=`boolean`&&a.push({message:`Expected a boolean: received ${String(n)}`,path:o});break;case`uuid`:(typeof n!=`string`||!r.uuid.test(n))&&a.push({message:`Expected a valid UUID: received ${String(n)}`,path:o});break;case`date`:(typeof n!=`string`||!r.date.test(n))&&a.push({message:`Expected to match "yyyy-MM-dd" format: received ${String(n)}`,path:o});break;case`datetime`:(typeof n!=`string`||!r.datetime.test(n))&&a.push({message:`Expected to match ISO format: received ${String(n)}`,path:o});break;case`time`:(typeof n!=`string`||!r.time.test(n))&&a.push({message:`Expected to match "HH:mm" format: received ${String(n)}`,path:o});break;case`decimal`:(typeof n!=`string`||!r.decimal.test(n))&&a.push({message:`Expected a decimal string: received ${String(n)}`,path:o});break;case`enum`:if(t._metadata.allowedValues){let e=t._metadata.allowedValues.map(e=>e.value);(typeof n!=`string`||!e.includes(n))&&a.push({message:`Must be one of [${e.join(`, `)}]: received ${String(n)}`,path:o})}break;case`nested`:{if(!isNestedObject(n))return a.push({message:`Expected an object: received ${String(n)}`,path:o}),!1;let r=!0;for(let[a,o]of Object.entries(t.fields)){let t=n[a];validateBaseField({...e,field:o,value:t,pathArray:i.concat(a)})||(r=!1)}return r}}return a.length===s}function validateCustomValue(e,t){let{value:n,pathArray:r,issues:i}=e,a=r.length>0?r:void 0;for(let e of t){let t=e({value:n});typeof t==`string`&&i.push({message:t,path:a})}}function validateBaseField(e){let{field:t,value:n,pathArray:r,issues:i}=e,a=r.length>0?r:void 0,o=n==null;if(t._metadata.required&&o)return i.push({message:`Required field is missing`,path:a}),!1;if(!t._metadata.required&&o)return!0;let s=!0;if(t._metadata.array){if(!Array.isArray(n))return i.push({message:`Expected an array`,path:a}),!1;for(let t=0;t<n.length;t++)validateBaseValue({...e,value:n[t],pathArray:r.concat(`[${t}]`)})||(s=!1)}else s=validateBaseValue(e);return s}function validateCustomField(e){let{field:t,value:n,pathArray:r}=e;if(n==null)return;if(t.type===`nested`){let i=t._metadata.array?n:[n];for(let n=0;n<i.length;n++){let a=i[n],o=t._metadata.array?r.concat(`[${n}]`):r;for(let[n,r]of Object.entries(t.fields))validateCustomField({...e,field:r,value:a[n],pathArray:o.concat(n)})}}let i=t._metadata.validate;i?.length&&validateCustomValue(e,i)}function parseInternal(e,t=a){let{value:n}=e,r=[],i={...e,issues:r};return validateBaseField(i)&&(n=deserializeDates(i,t),r.length===0&&validateCustomField({...i,value:n})),r.length>0?{issues:r}:{value:n??null}}function rejectLeapSecond(e,t){if(e===`datetime`&&t.slice(17,19)===`60`)throw RangeError(`Leap seconds are not supported`)}function parseAsDate(t,n){rejectLeapSecond(t,n);let r=new Date(t===`date`?`${n}T00:00:00.000Z`:t===`time`?`1970-01-01T${n}:00.000Z`:n);if(!Number.isFinite(r.getTime()))throw RangeError(`Invalid Date`);if(t!==`time`){let t=n.slice(0,10);if(e(/* @__PURE__ */ new Date(`${t}T00:00:00.000Z`))!==t)throw RangeError(`Invalid calendar date`)}return r}function parseAsTemporal(e,n){rejectLeapSecond(e,n);let r=t();return e===`date`?r.PlainDate.from(n):e===`datetime`?r.Instant.from(n):r.PlainTime.from(n)}const i={date:parseAsDate,temporal:parseAsTemporal},a={date:globalThis.process?.env.__TAILOR_PLATFORM_BUNDLE_WITHOUT_DATE?void 0:parseAsDate,temporal:globalThis.process?.env.__TAILOR_PLATFORM_BUNDLE_WITHOUT_TEMPORAL?void 0:parseAsTemporal};function deserializeDates(e,t){let{field:r,value:i,issues:a,pathArray:o}=e;if(i==null)return i;let convert=(i,o)=>{let{type:s}=r,c=n(s,r._metadata.as);if(c){let e=t[c];if(!e)throw Error(`Parsing fields declared with as: "${c}" is not included in this bundle. Parse them with parseDateFields, exported by "@tailor-platform/sdk/runtime".`);try{return e(s,String(i))}catch(e){if(!(e instanceof RangeError))throw e;return a.push({message:`Expected a valid ${s===`date`?`calendar date`:s}: received ${i}`,path:o.length>0?o:void 0}),i}}if(r.type!==`nested`)return i;let l=i,u=l;for(let[n,i]of Object.entries(r.fields)){let r=deserializeDates({...e,field:i,value:l[n],pathArray:o.concat(n)},t);r!==l[n]&&(u===l&&(u={...l}),Object.defineProperty(u,n,{value:r,enumerable:!0,configurable:!0,writable:!0}))}return u};if(!r._metadata.array)return convert(i,o);let s=i,c=s.map((e,t)=>convert(e,o.concat(`[${t}]`)));return c.every((e,t)=>e===s[t])?i:c}function parseInputFields(e){let{fields:t,...n}=e;return parseInternal({...n,field:{type:`nested`,fields:t,_metadata:{required:!0}},pathArray:[]})}function parseDateFields(e,t){return parseInternal({...t,field:e,pathArray:[]},i)}export{parseInternal as i,parseDateFields as n,parseInputFields as r,isNestedObject as t};
2
+ //# sourceMappingURL=field-parse-DhnFs9WG.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"field-parse-DhnFs9WG.mjs","names":[],"sources":["../src/runtime/field-parse.ts"],"sourcesContent":["import { dateRepresentationOf, formatDate } from \"./date\";\nimport { getTemporal } from \"./temporal\";\nimport type { FieldMetadata, TailorFieldType } from \"#/configure/types/field.types\";\nimport type { TailorPrincipal } from \"#/runtime/types\";\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\n\nconst regex = {\n uuid: /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,\n date: /^(?<year>\\d{4})-(?<month>\\d{2})-(?<day>\\d{2})$/,\n time: /^(?<hour>[01]\\d|2[0-3]):(?<minute>[0-5]\\d)$/,\n datetime:\n /^(?<year>\\d{4})-(?<month>\\d{2})-(?<day>\\d{2})[Tt](?<hour>[01]\\d|2[0-3]):(?<minute>[0-5]\\d):(?<second>[0-5]\\d|60)(\\.(?<fraction>\\d+))?(?<offset>[Zz]|[+-](?:[01]\\d|2[0-3]):[0-5]\\d)$/,\n decimal: /^-?(\\d+\\.?\\d*|\\.\\d+)([eE][+-]?\\d+)?$/,\n} as const;\n\n/**\n * Whether a value is an acceptable shape for a nested field. Runtime input may\n * not match the declared field type, so anything this rejects is reported\n * against the field rather than recursed into.\n * @param value - The value to check\n * @returns `true` when the value is a plain object the parser recurses into\n */\nexport function isNestedObject(value: unknown): value is Record<string, unknown> {\n return (\n typeof value === \"object\" && value !== null && !Array.isArray(value) && !(value instanceof Date)\n );\n}\n\nexport type FieldParseArgs = {\n value: unknown;\n data: unknown;\n invoker: TailorPrincipal | null;\n};\n\nexport type FieldParseInternalArgs = {\n value: unknown;\n data: unknown;\n invoker: TailorPrincipal | null;\n pathArray: string[];\n};\n\nexport type FieldRuntime<T extends TailorFieldType = TailorFieldType> = {\n readonly type: T;\n readonly fields: Record<string, FieldRuntime>;\n _metadata: FieldMetadata;\n};\n\ntype FieldParseRuntimeArgs<T extends TailorFieldType> = FieldParseInternalArgs & {\n field: FieldRuntime<T>;\n};\n\ntype FieldValidationArgs<T extends TailorFieldType> = FieldParseRuntimeArgs<T> & {\n issues: StandardSchemaV1.Issue[];\n};\n\nfunction validateBaseValue<T extends TailorFieldType>(args: FieldValidationArgs<T>): boolean {\n const { field, value, pathArray, issues } = args;\n const path = pathArray.length > 0 ? pathArray : undefined;\n const initialIssueCount = issues.length;\n\n switch (field.type) {\n case \"string\":\n if (typeof value !== \"string\") {\n issues.push({\n message: `Expected a string: received ${String(value)}`,\n path,\n });\n }\n break;\n\n case \"integer\":\n if (typeof value !== \"number\" || !Number.isInteger(value)) {\n issues.push({\n message: `Expected an integer: received ${String(value)}`,\n path,\n });\n }\n break;\n\n case \"float\":\n if (typeof value !== \"number\" || !Number.isFinite(value)) {\n issues.push({\n message: `Expected a number: received ${String(value)}`,\n path,\n });\n }\n break;\n\n case \"boolean\":\n if (typeof value !== \"boolean\") {\n issues.push({\n message: `Expected a boolean: received ${String(value)}`,\n path,\n });\n }\n break;\n\n case \"uuid\":\n if (typeof value !== \"string\" || !regex.uuid.test(value)) {\n issues.push({\n message: `Expected a valid UUID: received ${String(value)}`,\n path,\n });\n }\n break;\n case \"date\":\n if (typeof value !== \"string\" || !regex.date.test(value)) {\n issues.push({\n message: `Expected to match \"yyyy-MM-dd\" format: received ${String(value)}`,\n path,\n });\n }\n break;\n case \"datetime\":\n if (typeof value !== \"string\" || !regex.datetime.test(value)) {\n issues.push({\n message: `Expected to match ISO format: received ${String(value)}`,\n path,\n });\n }\n break;\n case \"time\":\n if (typeof value !== \"string\" || !regex.time.test(value)) {\n issues.push({\n message: `Expected to match \"HH:mm\" format: received ${String(value)}`,\n path,\n });\n }\n break;\n case \"decimal\":\n if (typeof value !== \"string\" || !regex.decimal.test(value)) {\n issues.push({\n message: `Expected a decimal string: received ${String(value)}`,\n path,\n });\n }\n break;\n\n case \"enum\":\n if (field._metadata.allowedValues) {\n const allowedValues = field._metadata.allowedValues.map((v) => v.value);\n if (typeof value !== \"string\" || !allowedValues.includes(value)) {\n issues.push({\n message: `Must be one of [${allowedValues.join(\", \")}]: received ${String(value)}`,\n path,\n });\n }\n }\n break;\n\n case \"nested\": {\n if (!isNestedObject(value)) {\n issues.push({\n message: `Expected an object: received ${String(value)}`,\n path,\n });\n return false;\n }\n\n let nestedBaseValid = true;\n for (const [fieldName, nestedField] of Object.entries(field.fields)) {\n const fieldValue = value[fieldName];\n if (\n !validateBaseField({\n ...args,\n field: nestedField,\n value: fieldValue,\n pathArray: pathArray.concat(fieldName),\n })\n ) {\n nestedBaseValid = false;\n }\n }\n return nestedBaseValid;\n }\n }\n\n return issues.length === initialIssueCount;\n}\n\nfunction validateCustomValue<T extends TailorFieldType>(\n args: FieldValidationArgs<T>,\n validateFns: NonNullable<FieldMetadata[\"validate\"]>,\n): void {\n const { value, pathArray, issues } = args;\n const path = pathArray.length > 0 ? pathArray : undefined;\n\n for (const fn of validateFns) {\n const result = fn({ value });\n if (typeof result === \"string\") {\n issues.push({\n message: result,\n path,\n });\n }\n }\n}\n\nfunction validateBaseField<T extends TailorFieldType>(args: FieldValidationArgs<T>): boolean {\n const { field, value, pathArray, issues } = args;\n const path = pathArray.length > 0 ? pathArray : undefined;\n\n const isNullOrUndefined = value === null || value === undefined;\n if (field._metadata.required && isNullOrUndefined) {\n issues.push({\n message: \"Required field is missing\",\n path,\n });\n return false;\n }\n\n if (!field._metadata.required && isNullOrUndefined) {\n return true;\n }\n\n let baseValid = true;\n if (field._metadata.array) {\n if (!Array.isArray(value)) {\n issues.push({\n message: \"Expected an array\",\n path,\n });\n return false;\n }\n\n for (let i = 0; i < value.length; i++) {\n if (\n !validateBaseValue({\n ...args,\n value: value[i],\n pathArray: pathArray.concat(`[${i}]`),\n })\n ) {\n baseValid = false;\n }\n }\n } else {\n baseValid = validateBaseValue(args);\n }\n\n return baseValid;\n}\n\nfunction validateCustomField<T extends TailorFieldType>(args: FieldValidationArgs<T>): void {\n const { field, value, pathArray } = args;\n if (value === null || value === undefined) {\n return;\n }\n\n if (field.type === \"nested\") {\n const records = field._metadata.array\n ? (value as Record<string, unknown>[])\n : [value as Record<string, unknown>];\n\n for (let i = 0; i < records.length; i++) {\n const record = records[i] as Record<string, unknown>;\n const recordPath = field._metadata.array ? pathArray.concat(`[${i}]`) : pathArray;\n for (const [fieldName, nestedField] of Object.entries(field.fields)) {\n validateCustomField({\n ...args,\n field: nestedField,\n value: record[fieldName],\n pathArray: recordPath.concat(fieldName),\n });\n }\n }\n }\n\n const validateFns = field._metadata.validate;\n if (validateFns?.length) {\n validateCustomValue(args, validateFns);\n }\n}\n\nexport function parseInternal<T extends TailorFieldType, Output>(\n args: FieldParseRuntimeArgs<T>,\n dateParsers: DateParsers = bundledDateParsers,\n): StandardSchemaV1.Result<Output> {\n let { value } = args;\n const issues: StandardSchemaV1.Issue[] = [];\n const validationArgs = { ...args, issues };\n const baseValid = validateBaseField(validationArgs);\n if (baseValid) {\n value = deserializeDates(validationArgs, dateParsers);\n if (issues.length === 0) {\n validateCustomField({ ...validationArgs, value });\n }\n }\n if (issues.length > 0) {\n return { issues };\n }\n\n return { value: (value ?? null) as Output };\n}\n\ntype DateParser = (type: TailorFieldType, text: string) => unknown;\n\ntype DateParsers = {\n readonly date: DateParser | undefined;\n readonly temporal: DateParser | undefined;\n};\n\nfunction rejectLeapSecond(type: TailorFieldType, text: string): void {\n if (type === \"datetime\" && text.slice(17, 19) === \"60\") {\n throw new RangeError(\"Leap seconds are not supported\");\n }\n}\n\nfunction parseAsDate(type: TailorFieldType, text: string): Date {\n rejectLeapSecond(type, text);\n const date = new Date(\n type === \"date\"\n ? `${text}T00:00:00.000Z`\n : type === \"time\"\n ? `1970-01-01T${text}:00.000Z`\n : text,\n );\n if (!Number.isFinite(date.getTime())) throw new RangeError(\"Invalid Date\");\n if (type !== \"time\") {\n const calendarDate = text.slice(0, 10);\n if (formatDate(new Date(`${calendarDate}T00:00:00.000Z`)) !== calendarDate) {\n throw new RangeError(\"Invalid calendar date\");\n }\n }\n return date;\n}\n\nfunction parseAsTemporal(type: TailorFieldType, text: string): unknown {\n rejectLeapSecond(type, text);\n const Temporal = getTemporal();\n if (type === \"date\") return Temporal.PlainDate.from(text);\n if (type === \"datetime\") return Temporal.Instant.from(text);\n return Temporal.PlainTime.from(text);\n}\n\nconst allDateParsers: DateParsers = { date: parseAsDate, temporal: parseAsTemporal };\n\ntype MaybeProcessGlobal = { process?: { env: Record<string, string | undefined> } };\n\nconst bundledDateParsers: DateParsers = {\n date: (globalThis as MaybeProcessGlobal).process?.env.__TAILOR_PLATFORM_BUNDLE_WITHOUT_DATE\n ? undefined\n : parseAsDate,\n temporal: (globalThis as MaybeProcessGlobal).process?.env\n .__TAILOR_PLATFORM_BUNDLE_WITHOUT_TEMPORAL\n ? undefined\n : parseAsTemporal,\n};\n\nfunction deserializeDates(\n args: FieldValidationArgs<TailorFieldType>,\n dateParsers: DateParsers,\n): unknown {\n const { field, value, issues, pathArray } = args;\n if (value === null || value === undefined) return value;\n const convert = (item: unknown, itemPath: string[]): unknown => {\n const { type } = field;\n const as = dateRepresentationOf(type, field._metadata.as);\n if (as) {\n const parse = dateParsers[as];\n if (!parse) {\n throw new Error(\n `Parsing fields declared with as: \"${as}\" is not included in this bundle. Parse them with parseDateFields, exported by \"@tailor-platform/sdk/runtime\".`,\n );\n }\n try {\n return parse(type, String(item));\n } catch (error) {\n if (!(error instanceof RangeError)) throw error;\n issues.push({\n message: `Expected a valid ${type === \"date\" ? \"calendar date\" : type}: received ${item}`,\n path: itemPath.length > 0 ? itemPath : undefined,\n });\n return item;\n }\n }\n if (field.type !== \"nested\") return item;\n const record = item as Record<string, unknown>;\n let result = record;\n for (const [key, child] of Object.entries(field.fields)) {\n const converted = deserializeDates(\n {\n ...args,\n field: child,\n value: record[key],\n pathArray: itemPath.concat(key),\n },\n dateParsers,\n );\n if (converted !== record[key]) {\n if (result === record) result = { ...record };\n Object.defineProperty(result, key, {\n value: converted,\n enumerable: true,\n configurable: true,\n writable: true,\n });\n }\n }\n return result;\n };\n if (!field._metadata.array) return convert(value, pathArray);\n const values = value as unknown[];\n const converted = values.map((item, index) => convert(item, pathArray.concat(`[${index}]`)));\n return converted.every((item, index) => item === values[index]) ? value : converted;\n}\n\ntype ParseInputFieldsArgs = FieldParseArgs & {\n fields: Record<string, FieldRuntime>;\n};\n\n/**\n * Validate a value against a record of input fields, treating the record as a\n * single required object — the same code path deployed functions run via\n * `t.object(fields).parse(...)`, so local validation matches platform behavior.\n * @param args - Input field definitions plus the value, context data, and user\n * @returns Validation result\n */\nexport function parseInputFields(args: ParseInputFieldsArgs): StandardSchemaV1.Result<unknown> {\n const { fields, ...parseArgs } = args;\n return parseInternal({\n ...parseArgs,\n field: { type: \"nested\", fields, _metadata: { required: true } },\n pathArray: [],\n });\n}\n\ntype ParsableField<Output> = FieldRuntime & {\n parse(args: FieldParseArgs): StandardSchemaV1.Result<Output>;\n};\n\n/**\n * Parse a value like `field.parse`, converting fields declared with `as: \"date\"` or\n * `as: \"temporal\"` even in bundles that leave that conversion out of `field.parse`.\n * @param field - Field defining the value's shape\n * @param args - Value to parse, with the context data and invoker passed to validators\n * @returns Validation result with Date and Temporal fields converted\n */\nexport function parseDateFields<Output>(\n field: ParsableField<Output>,\n args: FieldParseArgs,\n): StandardSchemaV1.Result<Output> {\n return parseInternal({ ...args, field, pathArray: [] }, allDateParsers);\n}\n"],"mappings":"sDAMA,MAAM,EAAQ,CACZ,KAAM,kEACN,KAAM,iDACN,KAAM,8CACN,SACE,sLACF,QAAS,sCACX,EASA,SAAgB,eAAe,EAAkD,CAC/E,OACE,OAAO,GAAU,YAAY,GAAkB,CAAC,MAAM,QAAQ,CAAK,GAAK,EAAE,aAAiB,KAE/F,CA6BA,SAAS,kBAA6C,EAAuC,CAC3F,GAAM,CAAE,QAAO,QAAO,YAAW,UAAW,EACtC,EAAO,EAAU,OAAS,EAAI,EAAY,IAAA,GAC1C,EAAoB,EAAO,OAEjC,OAAQ,EAAM,KAAd,CACE,IAAK,SACC,OAAO,GAAU,UACnB,EAAO,KAAK,CACV,QAAS,+BAA+B,OAAO,CAAK,IACpD,MACF,CAAC,EAEH,MAEF,IAAK,WACC,OAAO,GAAU,UAAY,CAAC,OAAO,UAAU,CAAK,IACtD,EAAO,KAAK,CACV,QAAS,iCAAiC,OAAO,CAAK,IACtD,MACF,CAAC,EAEH,MAEF,IAAK,SACC,OAAO,GAAU,UAAY,CAAC,OAAO,SAAS,CAAK,IACrD,EAAO,KAAK,CACV,QAAS,+BAA+B,OAAO,CAAK,IACpD,MACF,CAAC,EAEH,MAEF,IAAK,UACC,OAAO,GAAU,WACnB,EAAO,KAAK,CACV,QAAS,gCAAgC,OAAO,CAAK,IACrD,MACF,CAAC,EAEH,MAEF,IAAK,QACC,OA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,CAAC,EAEL,CACA,OAAO,CACT,EACA,GAAI,CAAC,EAAM,UAAU,MAAO,OAAO,QAAQ,EAAO,CAAS,EAC3D,IAAM,EAAS,EACT,EAAY,EAAO,KAAK,EAAM,IAAU,QAAQ,EAAM,EAAU,OAAO,IAAI,EAAM,EAAE,CAAC,CAAC,EAC3F,OAAO,EAAU,OAAO,EAAM,IAAU,IAAS,EAAO,EAAM,EAAI,EAAQ,CAC5E,CAaA,SAAgB,iBAAiB,EAA8D,CAC7F,GAAM,CAAE,SAAQ,GAAG,GAAc,EACjC,OAAO,cAAc,CACnB,GAAG,EACH,MAAO,CAAE,KAAM,SAAU,SAAQ,UAAW,CAAE,SAAU,EAAK,CAAE,EAC/D,UAAW,CAAC,CACd,CAAC,CACH,CAaA,SAAgB,gBACd,EACA,EACiC,CACjC,OAAO,cAAc,CAAE,GAAG,EAAM,QAAO,UAAW,CAAC,CAAE,EAAG,CAAc,CACxE"}
@@ -1,2 +1,2 @@
1
- import{t as e}from"./registry-HlEaGvl5.mjs";import{t}from"./platform-serialize-DkiTdHOt.mjs";function createDefaultWorkflowRuntime(){return{execJobFunction:e=>{throw Error(`No workflow job mock for "${e}". Acquire mockWorkflow() and call setJobHandler(...) or enqueueResult(...), or use runWorkflowLocally() for local workflow execution.`)},startWorkflow:async(n,r)=>(t(r),e),resumeWorkflowExecution:async e=>e,wait:e=>{throw Error(`No wait handler for "${e}". Acquire mockWorkflow() and call setWaitHandler(...).`)},resolve:async()=>{throw Error(`No resolve handler. Acquire mockWorkflow() and call setResolveHandler(...).`)}}}const n=`__tailorRuntimeActive`;var TailorErrorsMock=class extends Error{errors;constructor(e){if(!Array.isArray(e))throw TypeError(`TailorErrors: errors must be an array`);let t=e.map((e,t)=>{if(typeof e.message!=`string`)throw TypeError(`TailorErrors: errors[${t}].message must be a string`);if(!Array.isArray(e.path))throw TypeError(`TailorErrors: errors[${t}].path must be an array`);return{message:e.message,path:e.path}});super(`TailorErrors: ${JSON.stringify({errors:t})}`),this.name=`TailorErrors`,this.errors=t}},TailorDBFileErrorMock=class extends Error{code;cause;constructor(e,t,n){super(e),this.name=`TailorDBFileError`,this.code=t,this.cause=n}};function defaultGetInvoker(){return null}function noop(){}const r={debug:noop,info:noop,warn:noop,error:noop,setAttributes:noop};function installPlatformGlobals(e){let t=e;return t[n]=!0,t.tailor={context:{getInvoker:defaultGetInvoker},workflow:createDefaultWorkflowRuntime(),logger:{...r}},t.tailordb={},t.TailorErrors=TailorErrorsMock,t.TailorDBFileError=TailorDBFileErrorMock,{[Symbol.dispose](){cleanupPlatformGlobals(e)}}}function cleanupPlatformGlobals(e){let t=e;delete t.tailordb,delete t.tailor,delete t.TailorErrors,delete t.TailorDBFileError,delete t[n]}export{cleanupPlatformGlobals as n,installPlatformGlobals as r,n as t};
2
- //# sourceMappingURL=globals-CMHSnj4w.mjs.map
1
+ import{t as e}from"./registry-BijIDRVA.mjs";import{t}from"./platform-serialize-DkiTdHOt.mjs";function createDefaultWorkflowRuntime(){return{execJobFunction:e=>{throw Error(`No workflow job mock for "${e}". Acquire mockWorkflow() and call setJobHandler(...) or enqueueResult(...), or use runWorkflowLocally() for local workflow execution.`)},startWorkflow:async(n,r)=>(t(r),e),resumeWorkflowExecution:async e=>e,wait:e=>{throw Error(`No wait handler for "${e}". Acquire mockWorkflow() and call setWaitHandler(...).`)},resolve:async()=>{throw Error(`No resolve handler. Acquire mockWorkflow() and call setResolveHandler(...).`)}}}const n=`__tailorRuntimeActive`;var TailorErrorsMock=class extends Error{errors;constructor(e){if(!Array.isArray(e))throw TypeError(`TailorErrors: errors must be an array`);let t=e.map((e,t)=>{if(typeof e.message!=`string`)throw TypeError(`TailorErrors: errors[${t}].message must be a string`);if(!Array.isArray(e.path))throw TypeError(`TailorErrors: errors[${t}].path must be an array`);return{message:e.message,path:e.path}});super(`TailorErrors: ${JSON.stringify({errors:t})}`),this.name=`TailorErrors`,this.errors=t}},TailorDBFileErrorMock=class extends Error{code;cause;constructor(e,t,n){super(e),this.name=`TailorDBFileError`,this.code=t,this.cause=n}};function defaultGetInvoker(){return null}function noop(){}const r={debug:noop,info:noop,warn:noop,error:noop,setAttributes:noop};function installPlatformGlobals(e){let t=e;return t[n]=!0,t.tailor={context:{getInvoker:defaultGetInvoker},workflow:createDefaultWorkflowRuntime(),logger:{...r}},t.tailordb={},t.TailorErrors=TailorErrorsMock,t.TailorDBFileError=TailorDBFileErrorMock,{[Symbol.dispose](){cleanupPlatformGlobals(e)}}}function cleanupPlatformGlobals(e){let t=e;delete t.tailordb,delete t.tailor,delete t.TailorErrors,delete t.TailorDBFileError,delete t[n]}export{cleanupPlatformGlobals as n,installPlatformGlobals as r,n as t};
2
+ //# sourceMappingURL=globals-BCmGX05J.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"globals-CMHSnj4w.mjs","names":[],"sources":["../src/vitest/workflow-runtime.ts","../src/vitest/globals.ts"],"sourcesContent":["// Default `tailor.workflow` runner installed by the `tailor-runtime` environment.\n// Must stay free of `vitest` (`vi`): it loads via `./globals` in the environment\n// realm where `vi` is unavailable, hence relative imports only (no `@/` alias).\nimport { START_DEFAULT } from \"../configure/services/workflow/registry\";\nimport { platformSerialize } from \"../utils/test/platform-serialize\";\nimport type { ExecJobFunctionOptions, StartWorkflowOptions } from \"../runtime/workflow\";\n\nexport interface DefaultWorkflowRuntime {\n execJobFunction: (name: string, args?: unknown, options?: ExecJobFunctionOptions) => unknown;\n startWorkflow: (name: string, args?: unknown, options?: StartWorkflowOptions) => Promise<string>;\n resumeWorkflowExecution: (executionId: string) => Promise<string>;\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\nexport function createDefaultWorkflowRuntime(): DefaultWorkflowRuntime {\n const execJobFunction: DefaultWorkflowRuntime[\"execJobFunction\"] = (name) => {\n throw new Error(\n `No workflow job mock for \"${name}\". Acquire mockWorkflow() and call setJobHandler(...) or enqueueResult(...), or use runWorkflowLocally() for local workflow execution.`,\n );\n };\n const startWorkflow: DefaultWorkflowRuntime[\"startWorkflow\"] = async (_name, args) => {\n platformSerialize(args);\n return START_DEFAULT;\n };\n const resumeWorkflowExecution: DefaultWorkflowRuntime[\"resumeWorkflowExecution\"] = async (\n executionId,\n ) => executionId;\n return {\n execJobFunction,\n startWorkflow,\n resumeWorkflowExecution,\n wait: (key: string): unknown => {\n throw new Error(\n `No wait handler for \"${key}\". Acquire mockWorkflow() and call setWaitHandler(...).`,\n );\n },\n resolve: async (): Promise<void> => {\n throw new Error(\n \"No resolve handler. Acquire mockWorkflow() and call setResolveHandler(...).\",\n );\n },\n };\n}\n","/**\n * Base platform globals for the tailor-runtime test environment.\n *\n * This module is intentionally free of any `vitest` (`vi`) dependency so it can\n * be imported from the Vitest *environment* module (which runs in a realm where\n * `vi` is not available). It installs only the always-present structural pieces:\n *\n * - `globalThis.tailor` / `globalThis.tailordb` container objects\n * - `globalThis.tailor.context.getInvoker` default stub\n * - the platform error classes (`TailorErrors`,\n * `TailorDBFileError`)\n * - the `__tailorRuntimeActive` sentinel flag\n *\n * The per-namespace mock behavior (TailorDB client, workflow, secretmanager, …)\n * is installed on demand by the `xMock()` factories in `./mock`, which run in\n * test context where `vi` *is* available.\n */\n\nimport { createDefaultWorkflowRuntime } from \"./workflow-runtime\";\nimport type { ContextInvoker } from \"../runtime/context\";\nimport type { TailorDBFileErrorCode } from \"../runtime/file\";\n\n// Sentinel set when the tailor-runtime environment is active. setup.ts reads it\n// to decide whether to run its blocked-globals lifecycle and config-secret\n// loading.\nexport const RUNTIME_FLAG_KEY = \"__tailorRuntimeActive\";\n\n// ---------------------------------------------------------------------------\n// Error class mocks\n// ---------------------------------------------------------------------------\n\ninterface TailorErrorItem {\n message: string;\n path: (string | number)[];\n}\n\nclass TailorErrorsMock extends Error {\n errors: TailorErrorItem[];\n\n constructor(errors: TailorErrorItem[]) {\n if (!Array.isArray(errors)) {\n throw new TypeError(\"TailorErrors: errors must be an array\");\n }\n const validated = errors.map((e, i) => {\n if (typeof e.message !== \"string\") {\n throw new TypeError(`TailorErrors: errors[${i}].message must be a string`);\n }\n if (!Array.isArray(e.path)) {\n throw new TypeError(`TailorErrors: errors[${i}].path must be an array`);\n }\n return { message: e.message, path: e.path };\n });\n // Match the PF runtime's TailorErrors serialization, which prefixes the\n // JSON payload with \"TailorErrors: \". Other SDK code (e.g. apply\n // integration fixtures) strips this prefix before JSON.parse.\n super(`TailorErrors: ${JSON.stringify({ errors: validated })}`);\n this.name = \"TailorErrors\";\n this.errors = validated;\n }\n}\n\nclass TailorDBFileErrorMock extends Error {\n code?: TailorDBFileErrorCode;\n override cause: unknown;\n\n constructor(message: string, code?: TailorDBFileErrorCode, cause?: unknown) {\n super(message);\n this.name = \"TailorDBFileError\";\n this.code = code;\n this.cause = cause;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Base install / cleanup\n// ---------------------------------------------------------------------------\n\n// Stub-only injection. SDK consumers configure invokers at the body level\n// (resolver/executor/workflow `.body()` `invoker` arg) or, for bundled tests,\n// via `vi.spyOn(globalThis.tailor.context, \"getInvoker\")`.\nfunction defaultGetInvoker(): ContextInvoker | null {\n return null;\n}\n\n// No-op logger stub so `tailor.logger.*` calls in code under test don't throw\n// without an explicit `mockLogger()`. `mockLogger()` overlays vi.fn spies and\n// restores this on dispose.\nfunction noop(): void {}\nconst defaultLogger = {\n debug: noop,\n info: noop,\n warn: noop,\n error: noop,\n setAttributes: noop,\n};\n\n/**\n * Install the always-present base platform globals (containers, context stub,\n * error classes, runtime flag). Per-namespace mocks are layered on top by the\n * `xMock()` factories in `./mock`.\n *\n * Acquire with a `using` declaration and the globals are removed when the\n * scope exits; alternatively call `cleanupPlatformGlobals` yourself.\n * @param global - The global object to install into (typically `globalThis`)\n * @returns A `Disposable` that removes the installed globals\n */\nexport function installPlatformGlobals(global: typeof globalThis): Disposable {\n const g = global as Record<string, unknown>;\n\n g[RUNTIME_FLAG_KEY] = true;\n\n // Containers. Namespace mocks (secretmanager, …) are added to these by the\n // corresponding `xMock()` on acquisition. `workflow` carries a default\n // runner: job/wait/resolve calls throw a helpful error, and workflow starts\n // return a placeholder execution id, unless overlaid by `mockWorkflow()` or\n // `runWorkflowLocally()`.\n g.tailor = {\n context: { getInvoker: defaultGetInvoker },\n workflow: createDefaultWorkflowRuntime(),\n logger: { ...defaultLogger },\n };\n g.tailordb = {};\n\n g.TailorErrors = TailorErrorsMock;\n g.TailorDBFileError = TailorDBFileErrorMock;\n\n return {\n [Symbol.dispose]() {\n cleanupPlatformGlobals(global);\n },\n };\n}\n\n/**\n * Remove the base platform globals (and anything the namespace mocks layered on\n * top, since they live under the same containers).\n * @param global - The global object to clean up (typically `globalThis`)\n */\nexport function cleanupPlatformGlobals(global: typeof globalThis): void {\n const g = global as Record<string, unknown>;\n delete g.tailordb;\n delete g.tailor;\n delete g.TailorErrors;\n delete g.TailorDBFileError;\n delete g[RUNTIME_FLAG_KEY];\n}\n"],"mappings":"6FAmBA,SAAgB,8BAAuD,CAarE,MAAO,CACL,gBAbkE,GAAS,CAC3E,MAAU,MACR,6BAA6B,EAAK,uIACpC,CACF,EAUE,oBAToE,EAAO,KAC3E,EAAkB,CAAI,EACf,GAQP,6BALA,IACG,EAKH,KAAO,GAAyB,CAC9B,MAAU,MACR,wBAAwB,EAAI,wDAC9B,CACF,EACA,QAAS,SAA2B,CAClC,MAAU,MACR,6EACF,CACF,CACF,CACF,CCtBA,MAAa,EAAmB,wBAWhC,IAAM,iBAAN,cAA+B,KAAM,CACnC,OAEA,YAAY,EAA2B,CACrC,GAAI,CAAC,MAAM,QAAQ,CAAM,EACvB,MAAU,UAAU,uCAAuC,EAE7D,IAAM,EAAY,EAAO,KAAK,EAAG,IAAM,CACrC,GAAI,OAAO,EAAE,SAAY,SACvB,MAAU,UAAU,wBAAwB,EAAE,2BAA2B,EAE3E,GAAI,CAAC,MAAM,QAAQ,EAAE,IAAI,EACvB,MAAU,UAAU,wBAAwB,EAAE,wBAAwB,EAExE,MAAO,CAAE,QAAS,EAAE,QAAS,KAAM,EAAE,IAAK,CAC5C,CAAC,EAID,MAAM,iBAAiB,KAAK,UAAU,CAAE,OAAQ,CAAU,CAAC,GAAG,EAC9D,KAAK,KAAO,eACZ,KAAK,OAAS,CAChB,CACF,EAEM,sBAAN,cAAoC,KAAM,CACxC,KACA,MAEA,YAAY,EAAiB,EAA8B,EAAiB,CAC1E,MAAM,CAAO,EACb,KAAK,KAAO,oBACZ,KAAK,KAAO,EACZ,KAAK,MAAQ,CACf,CACF,EASA,SAAS,mBAA2C,CAClD,OAAO,IACT,CAKA,SAAS,MAAa,CAAC,CACvB,MAAM,EAAgB,CACpB,MAAO,KACP,KAAM,KACN,KAAM,KACN,MAAO,KACP,cAAe,IACjB,EAYA,SAAgB,uBAAuB,EAAuC,CAC5E,IAAM,EAAI,EAmBV,MAjBA,GAAE,GAAoB,GAOtB,EAAE,OAAS,CACT,QAAS,CAAE,WAAY,iBAAkB,EACzC,SAAU,6BAA6B,EACvC,OAAQ,CAAE,GAAG,CAAc,CAC7B,EACA,EAAE,SAAW,CAAC,EAEd,EAAE,aAAe,iBACjB,EAAE,kBAAoB,sBAEf,CACL,CAAC,OAAO,UAAW,CACjB,uBAAuB,CAAM,CAC/B,CACF,CACF,CAOA,SAAgB,uBAAuB,EAAiC,CACtE,IAAM,EAAI,EACV,OAAO,EAAE,SACT,OAAO,EAAE,OACT,OAAO,EAAE,aACT,OAAO,EAAE,kBACT,OAAO,EAAE,EACX"}
1
+ {"version":3,"file":"globals-BCmGX05J.mjs","names":[],"sources":["../src/vitest/workflow-runtime.ts","../src/vitest/globals.ts"],"sourcesContent":["// Default `tailor.workflow` runner installed by the `tailor-runtime` environment.\n// Must stay free of `vitest` (`vi`): it loads via `./globals` in the environment\n// realm where `vi` is unavailable, hence relative imports only (no `@/` alias).\nimport { START_DEFAULT } from \"../configure/services/workflow/registry\";\nimport { platformSerialize } from \"../utils/test/platform-serialize\";\nimport type { ExecJobFunctionOptions, StartWorkflowOptions } from \"../runtime/workflow\";\n\nexport interface DefaultWorkflowRuntime {\n execJobFunction: (name: string, args?: unknown, options?: ExecJobFunctionOptions) => unknown;\n startWorkflow: (name: string, args?: unknown, options?: StartWorkflowOptions) => Promise<string>;\n resumeWorkflowExecution: (executionId: string) => Promise<string>;\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\nexport function createDefaultWorkflowRuntime(): DefaultWorkflowRuntime {\n const execJobFunction: DefaultWorkflowRuntime[\"execJobFunction\"] = (name) => {\n throw new Error(\n `No workflow job mock for \"${name}\". Acquire mockWorkflow() and call setJobHandler(...) or enqueueResult(...), or use runWorkflowLocally() for local workflow execution.`,\n );\n };\n const startWorkflow: DefaultWorkflowRuntime[\"startWorkflow\"] = async (_name, args) => {\n platformSerialize(args);\n return START_DEFAULT;\n };\n const resumeWorkflowExecution: DefaultWorkflowRuntime[\"resumeWorkflowExecution\"] = async (\n executionId,\n ) => executionId;\n return {\n execJobFunction,\n startWorkflow,\n resumeWorkflowExecution,\n wait: (key: string): unknown => {\n throw new Error(\n `No wait handler for \"${key}\". Acquire mockWorkflow() and call setWaitHandler(...).`,\n );\n },\n resolve: async (): Promise<void> => {\n throw new Error(\n \"No resolve handler. Acquire mockWorkflow() and call setResolveHandler(...).\",\n );\n },\n };\n}\n","/**\n * Base platform globals for the tailor-runtime test environment.\n *\n * This module is intentionally free of any `vitest` (`vi`) dependency so it can\n * be imported from the Vitest *environment* module (which runs in a realm where\n * `vi` is not available). It installs only the always-present structural pieces:\n *\n * - `globalThis.tailor` / `globalThis.tailordb` container objects\n * - `globalThis.tailor.context.getInvoker` default stub\n * - the platform error classes (`TailorErrors`,\n * `TailorDBFileError`)\n * - the `__tailorRuntimeActive` sentinel flag\n *\n * The per-namespace mock behavior (TailorDB client, workflow, secretmanager, …)\n * is installed on demand by the `xMock()` factories in `./mock`, which run in\n * test context where `vi` *is* available.\n */\n\nimport { createDefaultWorkflowRuntime } from \"./workflow-runtime\";\nimport type { ContextInvoker } from \"../runtime/context\";\nimport type { TailorDBFileErrorCode } from \"../runtime/file\";\n\n// Sentinel set when the tailor-runtime environment is active. setup.ts reads it\n// to decide whether to run its blocked-globals lifecycle and config-secret\n// loading.\nexport const RUNTIME_FLAG_KEY = \"__tailorRuntimeActive\";\n\n// ---------------------------------------------------------------------------\n// Error class mocks\n// ---------------------------------------------------------------------------\n\ninterface TailorErrorItem {\n message: string;\n path: (string | number)[];\n}\n\nclass TailorErrorsMock extends Error {\n errors: TailorErrorItem[];\n\n constructor(errors: TailorErrorItem[]) {\n if (!Array.isArray(errors)) {\n throw new TypeError(\"TailorErrors: errors must be an array\");\n }\n const validated = errors.map((e, i) => {\n if (typeof e.message !== \"string\") {\n throw new TypeError(`TailorErrors: errors[${i}].message must be a string`);\n }\n if (!Array.isArray(e.path)) {\n throw new TypeError(`TailorErrors: errors[${i}].path must be an array`);\n }\n return { message: e.message, path: e.path };\n });\n // Match the PF runtime's TailorErrors serialization, which prefixes the\n // JSON payload with \"TailorErrors: \". Other SDK code (e.g. apply\n // integration fixtures) strips this prefix before JSON.parse.\n super(`TailorErrors: ${JSON.stringify({ errors: validated })}`);\n this.name = \"TailorErrors\";\n this.errors = validated;\n }\n}\n\nclass TailorDBFileErrorMock extends Error {\n code?: TailorDBFileErrorCode;\n override cause: unknown;\n\n constructor(message: string, code?: TailorDBFileErrorCode, cause?: unknown) {\n super(message);\n this.name = \"TailorDBFileError\";\n this.code = code;\n this.cause = cause;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Base install / cleanup\n// ---------------------------------------------------------------------------\n\n// Stub-only injection. SDK consumers configure invokers at the body level\n// (resolver/executor/workflow `.body()` `invoker` arg) or, for bundled tests,\n// via `vi.spyOn(globalThis.tailor.context, \"getInvoker\")`.\nfunction defaultGetInvoker(): ContextInvoker | null {\n return null;\n}\n\n// No-op logger stub so `tailor.logger.*` calls in code under test don't throw\n// without an explicit `mockLogger()`. `mockLogger()` overlays vi.fn spies and\n// restores this on dispose.\nfunction noop(): void {}\nconst defaultLogger = {\n debug: noop,\n info: noop,\n warn: noop,\n error: noop,\n setAttributes: noop,\n};\n\n/**\n * Install the always-present base platform globals (containers, context stub,\n * error classes, runtime flag). Per-namespace mocks are layered on top by the\n * `xMock()` factories in `./mock`.\n *\n * Acquire with a `using` declaration and the globals are removed when the\n * scope exits; alternatively call `cleanupPlatformGlobals` yourself.\n * @param global - The global object to install into (typically `globalThis`)\n * @returns A `Disposable` that removes the installed globals\n */\nexport function installPlatformGlobals(global: typeof globalThis): Disposable {\n const g = global as Record<string, unknown>;\n\n g[RUNTIME_FLAG_KEY] = true;\n\n // Containers. Namespace mocks (secretmanager, …) are added to these by the\n // corresponding `xMock()` on acquisition. `workflow` carries a default\n // runner: job/wait/resolve calls throw a helpful error, and workflow starts\n // return a placeholder execution id, unless overlaid by `mockWorkflow()` or\n // `runWorkflowLocally()`.\n g.tailor = {\n context: { getInvoker: defaultGetInvoker },\n workflow: createDefaultWorkflowRuntime(),\n logger: { ...defaultLogger },\n };\n g.tailordb = {};\n\n g.TailorErrors = TailorErrorsMock;\n g.TailorDBFileError = TailorDBFileErrorMock;\n\n return {\n [Symbol.dispose]() {\n cleanupPlatformGlobals(global);\n },\n };\n}\n\n/**\n * Remove the base platform globals (and anything the namespace mocks layered on\n * top, since they live under the same containers).\n * @param global - The global object to clean up (typically `globalThis`)\n */\nexport function cleanupPlatformGlobals(global: typeof globalThis): void {\n const g = global as Record<string, unknown>;\n delete g.tailordb;\n delete g.tailor;\n delete g.TailorErrors;\n delete g.TailorDBFileError;\n delete g[RUNTIME_FLAG_KEY];\n}\n"],"mappings":"6FAmBA,SAAgB,8BAAuD,CAarE,MAAO,CACL,gBAbkE,GAAS,CAC3E,MAAU,MACR,6BAA6B,EAAK,uIACpC,CACF,EAUE,oBAToE,EAAO,KAC3E,EAAkB,CAAI,EACf,GAQP,6BALA,IACG,EAKH,KAAO,GAAyB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ACF,CAOA,SAAgB,uBAAuB,EAAiC,CACtE,IAAM,EAAI,EACV,OAAO,EAAE,SACT,OAAO,EAAE,OACT,OAAO,EAAE,aACT,OAAO,EAAE,kBACT,OAAO,EAAE,EACX"}
@@ -0,0 +1,2 @@
1
+ function getRawPluginTableName(e){let t=typeof e==`object`&&e&&`name`in e?e.name:void 0;return typeof t==`string`?t:void 0}function getPluginGenerationDependencies(e){let t=/* @__PURE__ */ new Set;return e.onTailorDBReady&&t.add(`tailordb`),e.onResolverReady&&t.add(`resolver`),e.onExecutorReady&&t.add(`executor`),t}function hasGenerationHooks(e){return!!(e.onTailorDBReady||e.onResolverReady||e.onExecutorReady)}function isPluginExecutorWithFile(e){return`resolve`in e&&`context`in e}export{isPluginExecutorWithFile as i,getRawPluginTableName as n,hasGenerationHooks as r,getPluginGenerationDependencies as t};
2
+ //# sourceMappingURL=guards-yDXyKC9F.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"guards-ForsrxnH.mjs","names":[],"sources":["../src/plugin/guards.ts"],"sourcesContent":["// Runtime guards and helpers for plugin authoring types.\n//\n// These live outside plugin/types.ts (a pure type module) because they are\n// runtime functions. The types they operate on are imported type-only.\nimport type {\n DependencyKind,\n PluginGeneratedExecutor,\n PluginGeneratedExecutorWithFile,\n} from \"./types\";\n\n/**\n * Reads a table name without assuming plugin output is a valid table object.\n * @param table - Raw table value returned by a plugin hook.\n * @returns The table name when it is a string; otherwise, undefined.\n */\nexport function getRawPluginTableName(table: unknown): string | undefined {\n const name =\n typeof table === \"object\" && table !== null && \"name\" in table ? table.name : undefined;\n return typeof name === \"string\" ? name : undefined;\n}\n\n/**\n * Collects the generation-time dependency kinds a plugin requires.\n * @param plugin - The plugin object to inspect.\n * @param plugin.onTailorDBReady - Hook for TailorDB readiness.\n * @param plugin.onResolverReady - Hook for resolver readiness.\n * @param plugin.onExecutorReady - Hook for executor readiness.\n * @returns Set of dependency kinds required by the plugin.\n */\nexport function getPluginGenerationDependencies(plugin: {\n onTailorDBReady?: unknown;\n onResolverReady?: unknown;\n onExecutorReady?: unknown;\n}): Set<DependencyKind> {\n const deps = new Set<DependencyKind>();\n if (plugin.onTailorDBReady) {\n deps.add(\"tailordb\");\n }\n if (plugin.onResolverReady) {\n deps.add(\"resolver\");\n }\n if (plugin.onExecutorReady) {\n deps.add(\"executor\");\n }\n return deps;\n}\n\n/**\n * Checks if a plugin has any generation-time hooks.\n * @param plugin - The plugin object to inspect.\n * @param plugin.onTailorDBReady - Hook for TailorDB readiness.\n * @param plugin.onResolverReady - Hook for resolver readiness.\n * @param plugin.onExecutorReady - Hook for executor readiness.\n * @returns True if the plugin has at least one generation hook.\n */\nexport function hasGenerationHooks(plugin: {\n onTailorDBReady?: unknown;\n onResolverReady?: unknown;\n onExecutorReady?: unknown;\n}): boolean {\n return !!(plugin.onTailorDBReady || plugin.onResolverReady || plugin.onExecutorReady);\n}\n\n/**\n * Checks if a plugin executor uses file-based resolution.\n * @param executor - The plugin executor to check.\n * @returns True if the executor uses file-based resolution.\n */\nexport function isPluginExecutorWithFile(\n executor: PluginGeneratedExecutor,\n): executor is PluginGeneratedExecutorWithFile {\n return \"resolve\" in executor && \"context\" in executor;\n}\n\n/**\n * The shape every plugin instance has, whatever else it carries.\n */\nexport interface PluginShaped {\n id: string;\n description: string;\n}\n\nfunction isPluginShaped(value: unknown): value is PluginShaped {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as Record<string, unknown>).id === \"string\" &&\n typeof (value as Record<string, unknown>).description === \"string\"\n );\n}\n\n/**\n * Picks the plugin arrays (`definePlugins()` results) out of a config module's\n * exports. An array counts only when every item is plugin-shaped, so an array\n * that mixes in anything else is left alone as a whole; every loader that reads\n * plugins from a config module goes through this so they agree on which ones exist.\n * @param configModule - The imported `tailor.config.ts` module namespace\n * @returns The exported arrays whose items are all plugin-shaped, in export order\n */\nexport function pickPluginArrays(configModule: object): PluginShaped[][] {\n const arrays: PluginShaped[][] = [];\n for (const value of Object.values(configModule)) {\n if (Array.isArray(value) && value.length > 0 && value.every(isPluginShaped)) {\n arrays.push(value);\n }\n }\n return arrays;\n}\n"],"mappings":"AAeA,SAAgB,sBAAsB,EAAoC,CACxE,IAAM,EACJ,OAAO,GAAU,UAAY,GAAkB,SAAU,EAAQ,EAAM,KAAO,IAAA,GAChF,OAAO,OAAO,GAAS,SAAW,EAAO,IAAA,EAC3C,CAUA,SAAgB,gCAAgC,EAIxB,CACtB,IAAM,EAAO,IAAI,IAUjB,OATI,EAAO,iBACT,EAAK,IAAI,UAAU,EAEjB,EAAO,iBACT,EAAK,IAAI,UAAU,EAEjB,EAAO,iBACT,EAAK,IAAI,UAAU,EAEd,CACT,CAUA,SAAgB,mBAAmB,EAIvB,CACV,MAAO,CAAC,EAAE,EAAO,iBAAmB,EAAO,iBAAmB,EAAO,gBACvE,CAOA,SAAgB,yBACd,EAC6C,CAC7C,MAAO,YAAa,GAAY,YAAa,CAC/C,CAUA,SAAS,eAAe,EAAuC,CAC7D,OACE,OAAO,GAAU,YACjB,GACA,OAAQ,EAAkC,IAAO,UACjD,OAAQ,EAAkC,aAAgB,QAE9D,CAUA,SAAgB,iBAAiB,EAAwC,CACvE,IAAM,EAA2B,CAAC,EAClC,IAAK,IAAM,KAAS,OAAO,OAAO,CAAY,EACxC,MAAM,QAAQ,CAAK,GAAK,EAAM,OAAS,GAAK,EAAM,MAAM,cAAc,GACxE,EAAO,KAAK,CAAK,EAGrB,OAAO,CACT"}
1
+ {"version":3,"file":"guards-yDXyKC9F.mjs","names":[],"sources":["../src/plugin/guards.ts"],"sourcesContent":["// Runtime guards and helpers for plugin authoring types.\n//\n// These live outside plugin/types.ts (a pure type module) because they are\n// runtime functions. The types they operate on are imported type-only.\nimport type {\n DependencyKind,\n PluginGeneratedExecutor,\n PluginGeneratedExecutorWithFile,\n} from \"./types\";\n\n/**\n * Reads a table name without assuming plugin output is a valid table object.\n * @param table - Raw table value returned by a plugin hook.\n * @returns The table name when it is a string; otherwise, undefined.\n */\nexport function getRawPluginTableName(table: unknown): string | undefined {\n const name =\n typeof table === \"object\" && table !== null && \"name\" in table ? table.name : undefined;\n return typeof name === \"string\" ? name : undefined;\n}\n\n/**\n * Collects the generation-time dependency kinds a plugin requires.\n * @param plugin - The plugin object to inspect.\n * @param plugin.onTailorDBReady - Hook for TailorDB readiness.\n * @param plugin.onResolverReady - Hook for resolver readiness.\n * @param plugin.onExecutorReady - Hook for executor readiness.\n * @returns Set of dependency kinds required by the plugin.\n */\nexport function getPluginGenerationDependencies(plugin: {\n onTailorDBReady?: unknown;\n onResolverReady?: unknown;\n onExecutorReady?: unknown;\n}): Set<DependencyKind> {\n const deps = new Set<DependencyKind>();\n if (plugin.onTailorDBReady) {\n deps.add(\"tailordb\");\n }\n if (plugin.onResolverReady) {\n deps.add(\"resolver\");\n }\n if (plugin.onExecutorReady) {\n deps.add(\"executor\");\n }\n return deps;\n}\n\n/**\n * Checks if a plugin has any generation-time hooks.\n * @param plugin - The plugin object to inspect.\n * @param plugin.onTailorDBReady - Hook for TailorDB readiness.\n * @param plugin.onResolverReady - Hook for resolver readiness.\n * @param plugin.onExecutorReady - Hook for executor readiness.\n * @returns True if the plugin has at least one generation hook.\n */\nexport function hasGenerationHooks(plugin: {\n onTailorDBReady?: unknown;\n onResolverReady?: unknown;\n onExecutorReady?: unknown;\n}): boolean {\n return !!(plugin.onTailorDBReady || plugin.onResolverReady || plugin.onExecutorReady);\n}\n\n/**\n * Checks if a plugin executor uses file-based resolution.\n * @param executor - The plugin executor to check.\n * @returns True if the executor uses file-based resolution.\n */\nexport function isPluginExecutorWithFile(\n executor: PluginGeneratedExecutor,\n): executor is PluginGeneratedExecutorWithFile {\n return \"resolve\" in executor && \"context\" in executor;\n}\n"],"mappings":"AAeA,SAAgB,sBAAsB,EAAoC,CACxE,IAAM,EACJ,OAAO,GAAU,UAAY,GAAkB,SAAU,EAAQ,EAAM,KAAO,IAAA,GAChF,OAAO,OAAO,GAAS,SAAW,EAAO,IAAA,EAC3C,CAUA,SAAgB,gCAAgC,EAIxB,CACtB,IAAM,kBAAO,IAAI,IAUjB,OATI,EAAO,iBACT,EAAK,IAAI,UAAU,EAEjB,EAAO,iBACT,EAAK,IAAI,UAAU,EAEjB,EAAO,iBACT,EAAK,IAAI,UAAU,EAEd,CACT,CAUA,SAAgB,mBAAmB,EAIvB,CACV,MAAO,CAAC,EAAE,EAAO,iBAAmB,EAAO,iBAAmB,EAAO,gBACvE,CAOA,SAAgB,yBACd,EAC6C,CAC7C,MAAO,YAAa,GAAY,YAAa,CAC/C"}
@@ -1,4 +1,4 @@
1
- import{t as e}from"./multiline-EyzjEwn9.mjs";import{n as t,r as n,t as r}from"./tailordb-ddl-Fgm2cNvT.mjs";import{resolve as i}from"pathe";function emptyUsedUtilityTypes(){return{Timestamp:!1,Serial:!1,ObjectColumnType:!1,ArrayColumnType:!1}}function mergeUsedUtilityTypes(e,t){return{Timestamp:e.Timestamp||t.Timestamp,Serial:e.Serial||t.Serial,ObjectColumnType:e.ObjectColumnType||t.ObjectColumnType,ArrayColumnType:e.ArrayColumnType||t.ArrayColumnType}}function getEnumType(e){let t=e.allowedValues;return t&&Array.isArray(t)?t.map(e=>`"${typeof e==`string`?e:e.value}"`).join(` | `):`string`}function getNestedType(e){let t=e.fields;if(!t||typeof t!=`object`)return{type:`string`,usedUtilityTypes:emptyUsedUtilityTypes()};let n=Object.entries(t).map(([e,t])=>{let n=generateFieldType(t);return{fieldType:`${e}${t.required===!0?``:`?`}: ${n.type}`,usedUtilityTypes:n.usedUtilityTypes}}),r=n.reduce((e,t)=>mergeUsedUtilityTypes(e,t.usedUtilityTypes),emptyUsedUtilityTypes()),i=n.map(e=>e.fieldType),a=`{\n ${i.join(`;
1
+ import{t as e}from"./multiline-EyzjEwn9.mjs";import{n as t,r as n,t as r}from"./tailordb-ddl-DqInYupv.mjs";import{resolve as i}from"pathe";function emptyUsedUtilityTypes(){return{Timestamp:!1,Serial:!1,ObjectColumnType:!1,ArrayColumnType:!1}}function mergeUsedUtilityTypes(e,t){return{Timestamp:e.Timestamp||t.Timestamp,Serial:e.Serial||t.Serial,ObjectColumnType:e.ObjectColumnType||t.ObjectColumnType,ArrayColumnType:e.ArrayColumnType||t.ArrayColumnType}}function getEnumType(e){let t=e.allowedValues;return t&&Array.isArray(t)?t.map(e=>`"${typeof e==`string`?e:e.value}"`).join(` | `):`string`}function getNestedType(e){let t=e.fields;if(!t||typeof t!=`object`)return{type:`string`,usedUtilityTypes:emptyUsedUtilityTypes()};let n=Object.entries(t).map(([e,t])=>{let n=generateFieldType(t);return{fieldType:`${e}${t.required===!0?``:`?`}: ${n.type}`,usedUtilityTypes:n.usedUtilityTypes}}),r=n.reduce((e,t)=>mergeUsedUtilityTypes(e,t.usedUtilityTypes),emptyUsedUtilityTypes()),i=n.map(e=>e.fieldType),a=`{\n ${i.join(`;
2
2
  `)}${i.length>0?`;`:``}\n}`,o=Object.values(t).some(e=>e.required!==!0),s=Object.values(t).some(e=>e.hooks?.create||e.default!==void 0||e.optionalOnCreate===!0);return r.Timestamp||o||s?{type:`ObjectColumnType<${a}>`,usedUtilityTypes:{...r,ObjectColumnType:!0}}:{type:a,usedUtilityTypes:r}}function getBaseType(e){let t=e.type,r=emptyUsedUtilityTypes();if(t===`enum`)return{type:getEnumType(e),usedUtilityTypes:r};if(t===`nested`)return getNestedType(e);let i=n(t);return r.Timestamp=i===`Timestamp`,{type:i,usedUtilityTypes:r}}function generateFieldType(e){let n=getBaseType(e),r={...n.usedUtilityTypes},i=e.array===!0,a=e.required!==!0,o=t.has(n.type),s=n.type;return i&&(o||s.startsWith(`ObjectColumnType<`)?(s=`ArrayColumnType<${n.type}>`,r.ArrayColumnType=!0):s=e.type===`enum`?`(${n.type})[]`:`${n.type}[]`),a&&(s=`${s} | null`),e.serial&&(r.Serial=!0,s=`Serial<${s}>`),(e.hooks?.create||e.default!==void 0||e.optionalOnCreate===!0)&&(s=`Generated<${s}>`),{type:s,usedUtilityTypes:r}}function generateTableInterface(t,n){let r=Object.entries(n).filter(([e])=>e!==`id`).map(([e,t])=>({fieldName:e,...generateFieldType(t)})),i=[`id: Generated<string>;`,...r.map(e=>`${e.fieldName}: ${e.type};`)],a=r.reduce((e,t)=>mergeUsedUtilityTypes(e,t.usedUtilityTypes),emptyUsedUtilityTypes());return{typeDef:e`
3
3
  ${t}: {
4
4
  ${i.join(`
@@ -40,4 +40,4 @@ import{t as e}from"./multiline-EyzjEwn9.mjs";import{n as t,r as n,t as r}from"./
40
40
 
41
41
  `)+`
42
42
  `}function toDDLTables(e){return Object.values(e).map(e=>({name:e.name,fields:Object.fromEntries(Object.entries(e.fields).map(([e,t])=>[e,t.config])),indexes:e.indexes}))}function generatePGliteSchemaModule(e){return r(e.map(({namespace:e,tables:t})=>({namespace:e,tables:toDDLTables(t)})),{generatedBy:`the kysely-type plugin`})}const a=`@tailor-platform/kysely-type`,o=`./generated/tailordb.ts`;function kyselyTypePlugin(e){return{id:a,description:`Generates Kysely type definitions for TailorDB tables`,pluginConfig:e,async onTailorDBReady(e){let{distPath:t,pgliteSchemaPath:n}=e.pluginConfig;if(n&&i(t)===i(n))throw Error(`distPath and pgliteSchemaPath must resolve to different files.`);let r=[];for(let t of e.tailordb){let e=[];for(let n of Object.values(t.tables)){let t=await processKyselyType(n);e.push(t)}e.length!==0&&r.push({namespace:t.namespace,types:e})}let a=[];if(r.length>0){let t=generateUnifiedKyselyTypes(r);a.push({path:e.pluginConfig.distPath,content:t}),e.pluginConfig.pgliteSchemaPath&&a.push({path:e.pluginConfig.pgliteSchemaPath,content:generatePGliteSchemaModule(e.tailordb.filter(e=>Object.keys(e.tables).length>0))})}return{files:a}}}}export{processKyselyFields as a,generateUnifiedKyselyTypes as i,a as n,kyselyTypePlugin as r,o as t};
43
- //# sourceMappingURL=kysely-type-B_oA8D1k.mjs.map
43
+ //# sourceMappingURL=kysely-type-C-iyFFH7.mjs.map