@tailor-platform/sdk 2.37.0 → 2.39.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 (113) hide show
  1. package/CHANGELOG.md +124 -0
  2. package/dist/{application-83WVdH85.mjs → application-OeNMQzOC.mjs} +1 -1
  3. package/dist/application-mNOJx9Y2.mjs +207 -0
  4. package/dist/application-mNOJx9Y2.mjs.map +1 -0
  5. package/dist/cli/commands/deploy/deploy.d.mts +1 -0
  6. package/dist/cli/commands/deploy/tailordb/migration-validation.d.mts +2 -0
  7. package/dist/cli/commands/executor/trigger.d.mts +1 -0
  8. package/dist/cli/commands/generate/seed/bundler.d.mts +7 -5
  9. package/dist/cli/commands/workspace/transform.d.mts +1 -2
  10. package/dist/cli/lib.d.mts +5 -3
  11. package/dist/cli/lib.mjs +1 -1
  12. package/dist/cli/lib.mjs.map +1 -1
  13. package/dist/cli/main.mjs +67 -61
  14. package/dist/cli/main.mjs.map +1 -1
  15. package/dist/cli/shared/args.d.mts +14 -5
  16. package/dist/cli/shared/build-options.d.mts +13 -0
  17. package/dist/cli/shared/client.d.mts +15 -3
  18. package/dist/cli/shared/error-json.d.mts +12 -26
  19. package/dist/cli/shared/script-workflow.d.mts +65 -0
  20. package/dist/cli/shared/seed-chunker.d.mts +3 -3
  21. package/dist/client-CqiPQgMG.mjs +2 -0
  22. package/dist/client-CqiPQgMG.mjs.map +1 -0
  23. package/dist/client-DO2_Xz_z.mjs +1 -0
  24. package/dist/completion/zsh-worker.zsh +193 -74
  25. package/dist/configure/index.mjs +1 -1
  26. package/dist/configure/index.mjs.map +1 -1
  27. package/dist/configure/services/auth/types.d.mts +20 -3
  28. package/dist/configure/services/executor/operation.d.mts +5 -4
  29. package/dist/configure/services/executor/trigger/webhook.d.mts +8 -1
  30. package/dist/configure/services/http-adapter/http-adapter.d.mts +1 -1
  31. package/dist/configure/services/index.d.mts +0 -1
  32. package/dist/configure/services/tailordb/types.d.mts +9 -0
  33. package/dist/context-CYBcQZyO.mjs +1 -0
  34. package/dist/context-aAgFGDBD.mjs +23 -0
  35. package/dist/context-aAgFGDBD.mjs.map +1 -0
  36. package/dist/{crashreport-D_wf4GZh.mjs → crashreport-CQTAlnbA.mjs} +2 -2
  37. package/dist/{crashreport-D_wf4GZh.mjs.map → crashreport-CQTAlnbA.mjs.map} +1 -1
  38. package/dist/crashreport-GRnWyDnF.mjs +1 -0
  39. package/dist/{errors-Dmdnq0zi.mjs → errors-9OOL3xOM.mjs} +6 -5
  40. package/dist/errors-9OOL3xOM.mjs.map +1 -0
  41. package/dist/field_behavior_pb-B196sUx6.mjs +2 -0
  42. package/dist/field_behavior_pb-B196sUx6.mjs.map +1 -0
  43. package/dist/{kysely-type-DVL90_oX.mjs → kysely-type-DhAZqdQg.mjs} +14 -10
  44. package/dist/kysely-type-DhAZqdQg.mjs.map +1 -0
  45. package/dist/notification_resource_pb-BZ0hCA01.mjs +1 -0
  46. package/dist/notification_resource_pb-Dwzah7gO.mjs +2 -0
  47. package/dist/notification_resource_pb-Dwzah7gO.mjs.map +1 -0
  48. package/dist/plugin/builtin/kysely-type/index.mjs +1 -1
  49. package/dist/register-ts-hook-CORbtrSN.mjs +1105 -0
  50. package/dist/register-ts-hook-CORbtrSN.mjs.map +1 -0
  51. package/dist/repl-editor-Bposemei.mjs +2 -0
  52. package/dist/repl-editor-Bposemei.mjs.map +1 -0
  53. package/dist/resource_pb-elY668ZB.mjs +2 -0
  54. package/dist/resource_pb-elY668ZB.mjs.map +1 -0
  55. package/dist/{secret-file-DiuEcLFP.mjs → secret-file-CSXzcg4c.mjs} +2 -2
  56. package/dist/{secret-file-DiuEcLFP.mjs.map → secret-file-CSXzcg4c.mjs.map} +1 -1
  57. package/dist/service-B2vx6CGM.mjs +2 -0
  58. package/dist/{service-DDrbdyd-.mjs.map → service-B2vx6CGM.mjs.map} +1 -1
  59. package/dist/service-Bkz_TB5v.mjs +9 -0
  60. package/dist/service-Bkz_TB5v.mjs.map +1 -0
  61. package/dist/service-Dffd4how.mjs +1 -0
  62. package/dist/service_pb-Bethc2NW.mjs +1 -0
  63. package/dist/service_pb-CfpSriCy.mjs +2 -0
  64. package/dist/service_pb-CfpSriCy.mjs.map +1 -0
  65. package/dist/syntax-diagnostic-BQgOV8Fz.mjs +2 -0
  66. package/dist/syntax-diagnostic-BQgOV8Fz.mjs.map +1 -0
  67. package/dist/validation-errors-ChvCG6wT.mjs +3 -0
  68. package/dist/validation-errors-ChvCG6wT.mjs.map +1 -0
  69. package/{LICENSE → dist/vendor/graphql/LICENSE} +6 -6
  70. package/dist/vendor/graphql/language/KindTypeMap.d.mts +3 -0
  71. package/dist/vendor/graphql/language/ast.d.mts +784 -0
  72. package/dist/vendor/graphql/language/kinds_.d.mts +203 -0
  73. package/dist/vendor/graphql/language/source.d.mts +46 -0
  74. package/dist/vendor/graphql/language/tokenKind.d.mts +35 -0
  75. package/dist/vitest/index.mjs +1 -1
  76. package/dist/vitest/index.mjs.map +1 -1
  77. package/dist/workspace_resource_pb-Cow7mrJY.mjs +2 -0
  78. package/dist/workspace_resource_pb-Cow7mrJY.mjs.map +1 -0
  79. package/docs/cli/application.md +16 -12
  80. package/docs/cli/executor.md +13 -17
  81. package/docs/cli/function.md +1 -1
  82. package/docs/cli/notification.md +128 -0
  83. package/docs/cli/tailordb.md +26 -57
  84. package/docs/cli/workspace.md +3 -4
  85. package/docs/cli-reference.md +228 -48
  86. package/docs/configuration.md +28 -0
  87. package/docs/github-actions.md +241 -38
  88. package/docs/migration/v2.md +5 -3
  89. package/docs/services/auth.md +5 -0
  90. package/docs/services/executor.md +2 -0
  91. package/docs/services/tailordb/index.md +6 -2
  92. package/docs/services/tailordb/migration.md +54 -57
  93. package/docs/testing.md +0 -1
  94. package/package.json +25 -21
  95. package/dist/application-Cida-j1g.mjs +0 -207
  96. package/dist/application-Cida-j1g.mjs.map +0 -1
  97. package/dist/configure/services/http-adapter/index.d.mts +0 -2
  98. package/dist/crashreport-C2AcQNTe.mjs +0 -1
  99. package/dist/errors-Dmdnq0zi.mjs.map +0 -1
  100. package/dist/kysely-type-DVL90_oX.mjs.map +0 -1
  101. package/dist/register-ts-hook-Ht4zCseV.mjs +0 -1115
  102. package/dist/register-ts-hook-Ht4zCseV.mjs.map +0 -1
  103. package/dist/repl-editor-DkrCZmmg.mjs +0 -2
  104. package/dist/repl-editor-DkrCZmmg.mjs.map +0 -1
  105. package/dist/service-CZ0EdD2-.mjs +0 -10
  106. package/dist/service-CZ0EdD2-.mjs.map +0 -1
  107. package/dist/service-DDrbdyd-.mjs +0 -2
  108. package/dist/service-WhSyhaho.mjs +0 -1
  109. package/dist/service_pb-BMHhVot2.mjs +0 -1
  110. package/dist/service_pb-BxMSK0gg.mjs +0 -2
  111. package/dist/service_pb-BxMSK0gg.mjs.map +0 -1
  112. package/dist/workspace_resource_pb-7smKERdZ.mjs +0 -2
  113. package/dist/workspace_resource_pb-7smKERdZ.mjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"crashreport-D_wf4GZh.mjs","names":["redactSecrets","logger","readPackageJson","userAgentFromVersion","writeSecretFile","ensureSecretDir","path","fs","crypto","os","isCI","localEnabled","remoteEnabled","localDir","xdgConfig","JSON_FOOTER_MARKER","CRASH_LOG_EXTENSION","report","files","dir","f","file","filename","filePath","content","endpoint","response","ua","data","HOME_DIR","UUID_PATTERN","LONG_HEX_PATTERN","EMAIL_PATTERN","ABSOLUTE_PATH_PATTERN","WINDOWS_PATH_PATTERN","URL_QUERY_PATTERN","EMAIL_TEST_PATTERN","WINDOWS_DRIVE_TEST_PATTERN","SDK_PACKAGE_MARKER","separator","firstFrameIndex","stack","result","sdkIndex","match","normalized","message","redactNext","arg","argv","eqIndex","args","commandParts","options","isError","error","rawMessage","rawStack","errorName","currentUser","configPath","raw","parseYAML","email","user","config","sdkVersion","errorType","reason"],"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":"A,0ZAiBA,SAAgB,wBAA4C,CAC1D,GAAIU,EACF,MAAO,CACL,aAAc,GACd,cAAe,GACf,SAAU,EACZ,EAGF,IAAMC,GAAgB,QAAQ,IAAI,4BAA8B,KAAA,CAAM,YAAY,IAAM,MAClFC,GAAiB,QAAQ,IAAI,6BAA+B,MAAA,CAAO,YAAY,IAAM,KACrFC,EAAWC,EAAYR,EAAK,KAAKQ,EAAW,kBAAmB,eAAe,EAAI,GAExF,MAAO,CACL,aAAcH,GAAgBE,IAAa,GAC3C,gBACA,UACF,CACF,CC9BA,MAGaE,EAAqB,eAGrBC,EAAsB,aAOnC,SAAgB,kBAAkB,EAA6B,CA2B7D,MAAO,CAzBL,iBAAiBC,EAAO,KACxB,cAAcA,EAAO,YACrB,eAAeA,EAAO,YACtB,GACA,sBACA,gBAAgBA,EAAO,aACvB,iBAAiBA,EAAO,cACxB,OAAOA,EAAO,WAAW,GAAGA,EAAO,YACnC,SAASA,EAAO,OAChB,GACA,kBACA,YAAYA,EAAO,UACnB,cAAc,KAAK,UAAUA,EAAO,IAAI,IACxC,GACA,gBACA,SAASA,EAAO,YAChB,YAAYA,EAAO,eACnB,GACA,sBACAA,EAAO,YAAc,6BACrB,GACAF,EACA,KAAK,UAAUE,CAAM,EACrB,EAES,CAAC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ACX,SAAW,UAEpCe,EAAS,iBAAiB,CAAE,QAAO,aAAY,WAAU,CAAC,EAEhE,GAAIgD,EAAO,aAAc,CACvB,IAAM1C,EAAW,iBAAiBN,EAAQgD,EAAO,QAAQ,EACrD1C,GACFtB,EAAO,IACL,CACE,GACA,kEACA,KAAKsB,IACL,GACA,yBACA,qCAAqCA,EAAS,EAChD,CAAC,CAAC,KAAK;CAAI,CACb,CAEJ,CAEI0C,EAAO,eAET,MAAM,gBAAgBhD,EADXd,EAAqB+D,CACF,CAAE,CAEpC,MAAQ,CAER,CACF,CAOA,SAAgB,oBAA2B,CACzC,IAAMD,EAAS,uBAAuB,EACtC,GAAI,CAACA,EAAO,cAAgB,CAACA,EAAO,cAAe,OAEnD,IAAM,aAAe,EAAgB,IAAyB,CAC5D,IAAMnB,EAAUS,aAAiB,MAAQA,EAAM,QAAU,OAAOA,CAAK,EACrEtD,EAAO,MAAM6C,CAAO,EACpB,YAAiBS,EAAOY,CAAS,CAAC,CAAC,YAAc,CAC/C,QAAQ,KAAK,CAAC,CAChB,CAAC,CACH,EAEA,QAAQ,GAAG,oBAAsB,GAAU,YAAYZ,EAAO,mBAAmB,CAAC,EAClF,QAAQ,GAAG,qBAAuB,GAAW,YAAYa,EAAQ,oBAAoB,CAAC,CACxF,C"}
1
+ {"version":3,"file":"crashreport-CQTAlnbA.mjs","names":["redactSecrets","logger","readPackageJson","userAgentFromVersion","writeSecretFile","ensureSecretDir","path","fs","crypto","os","isCI","localEnabled","remoteEnabled","localDir","xdgConfig","JSON_FOOTER_MARKER","CRASH_LOG_EXTENSION","report","files","dir","f","file","filename","filePath","content","endpoint","response","ua","data","HOME_DIR","UUID_PATTERN","LONG_HEX_PATTERN","EMAIL_PATTERN","ABSOLUTE_PATH_PATTERN","WINDOWS_PATH_PATTERN","URL_QUERY_PATTERN","EMAIL_TEST_PATTERN","WINDOWS_DRIVE_TEST_PATTERN","SDK_PACKAGE_MARKER","separator","firstFrameIndex","stack","result","sdkIndex","match","normalized","message","redactNext","arg","argv","eqIndex","args","commandParts","options","isError","error","rawMessage","rawStack","errorName","currentUser","configPath","raw","parseYAML","email","user","config","sdkVersion","errorType","reason"],"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":"A,0ZAiBA,SAAgB,wBAA4C,CAC1D,GAAIU,EACF,MAAO,CACL,aAAc,GACd,cAAe,GACf,SAAU,EACZ,EAGF,IAAMC,GAAgB,QAAQ,IAAI,4BAA8B,KAAA,CAAM,YAAY,IAAM,MAClFC,GAAiB,QAAQ,IAAI,6BAA+B,MAAA,CAAO,YAAY,IAAM,KACrFC,EAAWC,EAAYR,EAAK,KAAKQ,EAAW,kBAAmB,eAAe,EAAI,GAExF,MAAO,CACL,aAAcH,GAAgBE,IAAa,GAC3C,gBACA,UACF,CACF,CC9BA,MAGaE,EAAqB,eAGrBC,EAAsB,aAOnC,SAAgB,kBAAkB,EAA6B,CA2B7D,MAAO,CAzBL,iBAAiBC,EAAO,KACxB,cAAcA,EAAO,YACrB,eAAeA,EAAO,YACtB,GACA,sBACA,gBAAgBA,EAAO,aACvB,iBAAiBA,EAAO,cACxB,OAAOA,EAAO,WAAW,GAAGA,EAAO,YACnC,SAASA,EAAO,OACh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AAS,GAAG,EAAIA,EAAO,IACrC,CCpHA,eAAsB,YAAY,EAAgB,EAAqC,CACrF,GAAI,CACF,IAAMC,EAAS,uBAAuB,EACtC,GAAI,CAACA,EAAO,cAAgB,CAACA,EAAO,cAAe,OAGnD,IAAMC,GAAa,MADOhE,EAAgB,EAAA,CACX,SAAW,UAEpCe,EAAS,iBAAiB,CAAE,QAAO,aAAY,WAAU,CAAC,EAEhE,GAAIgD,EAAO,aAAc,CACvB,IAAM1C,EAAW,iBAAiBN,EAAQgD,EAAO,QAAQ,EACrD1C,GACFtB,EAAO,IACL,CACE,GACA,kEACA,KAAKsB,IACL,GACA,yBACA,qCAAqCA,EAAS,EAChD,CAAC,CAAC,KAAK;CAAI,CACb,CAEJ,CAEI0C,EAAO,eAET,MAAM,gBAAgBhD,EADXd,EAAqB+D,CACF,CAAE,CAEpC,MAAQ,CAER,CACF,CAOA,SAAgB,oBAA2B,CACzC,IAAMD,EAAS,uBAAuB,EACtC,GAAI,CAACA,EAAO,cAAgB,CAACA,EAAO,cAAe,OAEnD,IAAM,aAAe,EAAgB,IAAyB,CAC5D,IAAMnB,EAAUS,aAAiB,MAAQA,EAAM,QAAU,OAAOA,CAAK,EACrEtD,EAAO,MAAM6C,CAAO,EACpB,YAAiBS,EAAOY,CAAS,CAAC,CAAC,YAAc,CAC/C,QAAQ,KAAK,CAAC,CAChB,CAAC,CACH,EAEA,QAAQ,GAAG,oBAAsB,GAAU,YAAYZ,EAAO,mBAAmB,CAAC,EAClF,QAAQ,GAAG,qBAAuB,GAAW,YAAYa,EAAQ,oBAAoB,CAAC,CACxF,C"}
@@ -0,0 +1 @@
1
+ export{n as reportCrash}from"./crashreport-CQTAlnbA.mjs";
@@ -2,11 +2,12 @@ import{formatWithOptions as e,stripVTControlCharacters as t,styleText as n}from"
2
2
  `?!1:t<=31||t===127}function normalizeControlCharacters(e){let t=e.match(s)??[];return e.split(s).map(e=>{let t=[];for(let n of e)n===` `?t.push(` `.repeat(8)):isStrippableControlCharacter(n)||t.push(n);return t.join(``)}).reduce((e,n,r)=>e+n+(t[r]??``),``)}function sanitizeCell(e){return normalizeControlCharacters(String(e??``).replace(c,`
3
3
  `))}const u=/^(?:\p{Default_Ignorable_Code_Point}|\p{Control}|\p{Format}|\p{Nonspacing_Mark}|\p{Enclosing_Mark}|\p{Surrogate})+$/v,d=/^\p{RGI_Emoji}$/v;function displayWidth(e){let t=0;for(let{segment:n}of l.segment(e.replace(s,``))){if(u.test(n))continue;if(d.test(n)){t+=2;continue}let e=n.codePointAt(0);t+=e===void 0?0:a(e)}return t}function toCellLines(e){return e.split(`
4
4
  `).map(e=>({text:e,width:displayWidth(e)}))}function padCell(e,t){return e.text+` `.repeat(Math.max(0,t-e.width))}function renderBorder(e,t,n,r){return e+r.map(e=>`─`.repeat(e+2)).join(t)+n}function validateConsistentColumnCount(e){let t=e[0]?.length;t!==void 0&&e.forEach((e,n)=>{if(e.length!==t)throw Error(`renderTable: all rows must have the same number of columns (expected ${t}, row ${n} has ${e.length}).`)})}function renderTable(e,t={}){let n=e.map(e=>e.map(sanitizeCell));validateConsistentColumnCount(n);let r=n.length,i=n[0]?.length??0;if(r===0||i===0)return``;let a=n.map(e=>Array.from({length:i},(t,n)=>toCellLines(e[n]??``))),o=Array.from({length:i},(e,t)=>maxOf(a.map(e=>maxOf((e[t]??[]).map(e=>e.width))))),shouldDrawLine=e=>t.singleLine?e===0||e===r:(t.drawHorizontalLine??(()=>!0))(e,r),s=[];return shouldDrawLine(0)&&s.push(renderBorder(`┌`,`┬`,`┐`,o)),a.forEach((e,t)=>{let n=maxOf(e.map(e=>e.length),1);for(let t=0;t<n;t++){let n=e.map((e,n)=>padCell(e[t]??{text:``,width:0},o[n]??0));s.push(`│ ${n.join(` │ `)} │`)}t<r-1&&shouldDrawLine(t+1)&&s.push(renderBorder(`├`,`┼`,`┤`,o))}),shouldDrawLine(r)&&s.push(renderBorder(`└`,`┴`,`┘`,o)),`${s.join(`
5
- `)}\n`}const f=/* @__PURE__ */ new Set([`true`,`t`,`yes`,`y`,`on`,`1`]),p=/* @__PURE__ */ new Set([`false`,`f`,`no`,`n`,`off`,`0`]);function parseBoolean(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t!==``){if(f.has(t))return!0;if(p.has(t))return!1}}const m=`TAILOR_JSON_OUTPUT`;function interactiveTerminal(){return!i&&process.stdin.isTTY===!0&&process.stdout.isTTY===!0}function jsonModeRemedy(e){let t=y;switch(e){case`agent`:return` JSON output is enabled because an AI coding agent${t?` (${t})`:``} was detected; pass --json=false or set ${m}=false to restore prompts.`;case`flag`:return t?` JSON output is enabled by --json; pass --json=false instead to restore prompts.`:` JSON output is enabled by --json; drop it to restore prompts.`;case`env`:return t?` JSON output is enabled by ${m}; set it to false to restore prompts.`:` JSON output is enabled by ${m}; unset it to restore prompts.`;case`both`:return t?` JSON output is enabled by --json and ${m}; pass --json=false instead of the flag to restore prompts.`:` JSON output is enabled by --json and ${m}; drop the flag and unset the variable to restore prompts.`}}var CIPromptError=class extends Error{constructor(e){let t=_&&v!==void 0&&interactiveTerminal()?jsonModeRemedy(v):``;super((e??`Interactive prompts are not available in this environment. Provide the required options explicitly.`)+t),this.name=`CIPromptError`}};const h={success:o.green,error:o.red,warning:o.yellow,info:o.cyan,create:o.green,update:o.yellow,delete:o.red,replace:o.magenta,unchanged:o.gray,bold:o.bold,dim:o.gray,highlight:o.cyanBright,successBright:o.greenBright,errorBright:o.redBright,resourceType:o.bold,resourceName:o.cyan,path:o.cyan,value:o.white,placeholder:e=>o.italic(o.gray(e))},g={success:h.success(`✓`),error:h.error(`✖`),warning:h.warning(`⚠`),info:h.info(`i`),create:h.create(`+`),update:h.update(`~`),delete:h.delete(`-`),replace:h.replace(`±`),bullet:h.dim(`•`),arrow:h.dim(`→`)};let _=!1,v,y,b;const x=/* @__PURE__ */ new Set,S=`<redacted>`;function buildAutomaton(e){let t={children:/* @__PURE__ */ new Map,fail:void 0,outputs:[]};t.fail=t;for(let n of e){let e=t;for(let r=0;r<n.length;r++){let i=n[r],a=e.children.get(i);a||(a={children:/* @__PURE__ */ new Map,fail:t,outputs:[]},e.children.set(i,a)),e=a}e.outputs.push(n)}let n=[...t.children.values()];for(let e=0;e<n.length;e++){let r=n[e];for(let[e,i]of r.children){let a=r.fail;for(;a!==t&&!a.children.has(e);)a=a.fail;i.fail=a.children.get(e)??t,i.outputs=i.outputs.concat(i.fail.outputs),n.push(i)}}return t}let C=null;function getAutomaton(){return C??=buildAutomaton(x),C}function findSecretSpans(e){let t=[],n=getAutomaton(),r=n;for(let i=0;i<e.length;i++){let a=e[i];for(;r!==n&&!r.children.has(a);)r=r.fail;r=r.children.get(a)??n;for(let e of r.outputs)t.push([i+1-e.length,i+1])}return t}function redactSecrets(e){if(x.size===0)return e;let t=[];for(let n=0,r;(r=e.indexOf(S,n))!==-1;)t.push([r,r+10]),n=r+10;let n=findSecretSpans(e).filter(([e,n])=>!t.some(([t,r])=>e>=t&&n<=r));if(n.length===0)return e;n.sort(([e],[t])=>e-t);let r=[];for(let e of n){let t=r.at(-1);t&&e[0]<=t[1]?t[1]=Math.max(t[1],e[1]):r.push(e)}let i=``,a=0;for(let[t,n]of r)i+=e.slice(a,t)+S,a=n;return i+e.slice(a)}function renderWithRedaction(e,n){let r=n(redactSecrets(e)),i=t(r),a=redactSecrets(i);return a===i?r:a}function renderRedacted(e,t){return renderWithRedaction(t,t=>renderFor(e,t))}function plainRedacted(e){return renderWithRedaction(e,t)}const w={info:`ℹ`,success:`✔`,warn:`⚠`,error:`✖`,debug:`⚙`,trace:`→`,log:``},T={info:h.info,success:h.success,warn:h.warning,error:h.error,debug:h.dim,trace:h.dim,log:e=>e};function formatLogLine(e){let{mode:t,indent:n,type:r,message:i,timestamp:a}=e,o=n>0?` `.repeat(n):``,s=T[r]||(e=>e);if(t===`plain`)return`${o}${s(i)}\n`;let c=w[r]||``,l=s(`${c?`${c} `:``}${i}`);return`${o}${a??``}${l}\n`}function writeLog(t,n,r){let i=r?.mode??`default`,a=r?.indent??0,o={breakLength:process.stdout.columns||80},s=formatLogLine({mode:i,indent:a,type:t,message:e(o,n),timestamp:i===`stream`?`${(/* @__PURE__ */ new Date()).toLocaleTimeString()} `:``});process.stderr.write(renderRedacted(process.stderr,s))}function setJsonDefaultAgent(e){y=e}function jsonDefaultAgent(){return y}const E={get jsonMode(){return _},set jsonMode(e){_=e,e||(v=void 0)},setJsonMode(e,t){_=e,v=e?t:void 0},get verbose(){return b??(parseBoolean(process.env.DEBUG)===!0||process.env.RUNNER_DEBUG===`1`)},set verbose(e){b=e},info(e,t){writeLog(`info`,e,t)},success(e,t){writeLog(`success`,e,t)},warn(e,t){writeLog(`warn`,e,t)},error(e,t){writeLog(`error`,e,t)},log(e){writeLog(`log`,e,{mode:`plain`})},newline(){process.stderr.write(`
6
- `)},debug(e){E.verbose&&writeLog(`log`,h.dim(e),{mode:`plain`})},registerSecret(e){if(typeof e!=`string`||[...e].length<4)return;let t=x.size;x.add(e);let n=JSON.stringify(e).slice(1,-1);n!==e&&x.add(n);let r=new URLSearchParams([[`v`,e]]).toString().slice(2);r!==e&&x.add(r),x.size!==t&&(C=null)},out(e,t){if(typeof e==`string`){process.stdout.write(renderFor(process.stdout,e.endsWith(`
5
+ `)}\n`}const f=/* @__PURE__ */ new Set([`true`,`t`,`yes`,`y`,`on`,`1`]),p=/* @__PURE__ */ new Set([`false`,`f`,`no`,`n`,`off`,`0`]);function parseBoolean(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t!==``){if(f.has(t))return!0;if(p.has(t))return!1}}const m=`TAILOR_JSON_OUTPUT`;function interactiveTerminal(){return!i&&process.stdin.isTTY===!0&&process.stdout.isTTY===!0}function jsonModeRemedy(e){let t=y;switch(e){case`agent`:return` JSON output is enabled because an AI coding agent${t?` (${t})`:``} was detected; pass --json=false or set ${m}=false to restore prompts.`;case`flag`:return t?` JSON output is enabled by --json; pass --json=false instead to restore prompts.`:` JSON output is enabled by --json; drop it to restore prompts.`;case`env`:return t?` JSON output is enabled by ${m}; set it to false to restore prompts.`:` JSON output is enabled by ${m}; unset it to restore prompts.`;case`both`:return t?` JSON output is enabled by --json and ${m}; pass --json=false instead of the flag to restore prompts.`:` JSON output is enabled by --json and ${m}; drop the flag and unset the variable to restore prompts.`}}var CIPromptError=class extends Error{constructor(e){let t=_&&v!==void 0&&interactiveTerminal()?jsonModeRemedy(v):``;super((e??`Interactive prompts are not available in this environment. Provide the required options explicitly.`)+t),this.name=`CIPromptError`}};const h={success:o.green,error:o.red,warning:o.yellow,info:o.cyan,create:o.green,update:o.yellow,delete:o.red,replace:o.magenta,unchanged:o.gray,bold:o.bold,dim:o.gray,highlight:o.cyanBright,successBright:o.greenBright,errorBright:o.redBright,resourceType:o.bold,resourceName:o.cyan,path:o.cyan,value:o.white,placeholder:e=>o.italic(o.gray(e))},g={success:h.success(`✓`),error:h.error(`✖`),warning:h.warning(`⚠`),info:h.info(`i`),create:h.create(`+`),update:h.update(`~`),delete:h.delete(`-`),replace:h.replace(`±`),bullet:h.dim(`•`),arrow:h.dim(`→`)};let _=!1,v,y,b;const x=/* @__PURE__ */ new Set,S=`<redacted>`;function buildAutomaton(e){let t={children:/* @__PURE__ */ new Map,fail:void 0,outputs:[]};t.fail=t;for(let n of e){let e=t;for(let r=0;r<n.length;r++){let i=n[r],a=e.children.get(i);a||(a={children:/* @__PURE__ */ new Map,fail:t,outputs:[]},e.children.set(i,a)),e=a}e.outputs.push(n)}let n=[...t.children.values()];for(let e=0;e<n.length;e++){let r=n[e];for(let[e,i]of r.children){let a=r.fail;for(;a!==t&&!a.children.has(e);)a=a.fail;i.fail=a.children.get(e)??t,i.outputs=i.outputs.concat(i.fail.outputs),n.push(i)}}return t}let C=null;function getAutomaton(){return C??=buildAutomaton(x),C}function findSecretSpans(e){let t=[],n=getAutomaton(),r=n;for(let i=0;i<e.length;i++){let a=e[i];for(;r!==n&&!r.children.has(a);)r=r.fail;r=r.children.get(a)??n;for(let e of r.outputs)t.push([i+1-e.length,i+1])}return t}function redactSecrets(e){if(x.size===0)return e;let t=[];for(let n=0,r;(r=e.indexOf(S,n))!==-1;)t.push([r,r+10]),n=r+10;let n=findSecretSpans(e).filter(([e,n])=>!t.some(([t,r])=>e>=t&&n<=r));if(n.length===0)return e;n.sort(([e],[t])=>e-t);let r=[];for(let e of n){let t=r.at(-1);t&&e[0]<=t[1]?t[1]=Math.max(t[1],e[1]):r.push(e)}let i=``,a=0;for(let[t,n]of r)i+=e.slice(a,t)+S,a=n;return i+e.slice(a)}function renderWithRedaction(e,n){let r=n(redactSecrets(e)),i=t(r),a=redactSecrets(i);return a===i?r:a}function renderRedacted(e,t){return renderWithRedaction(t,t=>renderFor(e,t))}function plainRedacted(e){return renderWithRedaction(e,t)}const w=/[\u0000-\u0008\u000b-\u001f\u007f-\u009f\u2028\u2029]/g;function sanitizeTerminalText(e){return t(e).replace(w,``).replace(/\s+/g,` `).trim()}function sanitizeTerminalBlock(e){return t(e).replace(/\r\n?/g,`
6
+ `).replace(w,``)}const T={info:`ℹ`,success:`✔`,warn:`⚠`,error:`✖`,debug:`⚙`,trace:`→`,log:``},E={info:h.info,success:h.success,warn:h.warning,error:h.error,debug:h.dim,trace:h.dim,log:e=>e};function formatLogLine(e){let{mode:t,indent:n,type:r,message:i,timestamp:a}=e,o=n>0?` `.repeat(n):``,s=E[r]||(e=>e);if(t===`plain`)return`${o}${s(i)}\n`;let c=T[r]||``,l=s(`${c?`${c} `:``}${i}`);return`${o}${a??``}${l}\n`}function writeLog(t,n,r){let i=r?.mode??`default`,a=r?.indent??0,o={breakLength:process.stdout.columns||80},s=formatLogLine({mode:i,indent:a,type:t,message:e(o,n),timestamp:i===`stream`?`${(/* @__PURE__ */ new Date()).toLocaleTimeString()} `:``});process.stderr.write(renderRedacted(process.stderr,s))}function setJsonDefaultAgent(e){y=e}function jsonDefaultAgent(){return y}const D={get jsonMode(){return _},set jsonMode(e){_=e,e||(v=void 0)},setJsonMode(e,t){_=e,v=e?t:void 0},get verbose(){return b??(parseBoolean(process.env.DEBUG)===!0||process.env.RUNNER_DEBUG===`1`)},set verbose(e){b=e},info(e,t){writeLog(`info`,e,t)},success(e,t){writeLog(`success`,e,t)},warn(e,t){writeLog(`warn`,e,t)},error(e,t){writeLog(`error`,e,t)},log(e){writeLog(`log`,e,{mode:`plain`})},newline(){process.stderr.write(`
7
+ `)},debug(e){D.verbose&&writeLog(`log`,h.dim(e),{mode:`plain`})},registerSecret(e){if(typeof e!=`string`||[...e].length<4)return;let t=x.size;x.add(e);let n=JSON.stringify(e).slice(1,-1);n!==e&&x.add(n);let r=new URLSearchParams([[`v`,e]]).toString().slice(2);r!==e&&x.add(r),x.size!==t&&(C=null)},out(e,t){if(typeof e==`string`){process.stdout.write(renderFor(process.stdout,e.endsWith(`
7
8
  `)?e:e+`
8
- `));return}if(this.jsonMode){console.log(JSON.stringify(e));return}let n=t?.display,formatValue=(e,n=!1)=>t?.showNull&&e===null?`NULL`:e==null?`N/A`:e instanceof Date?r(e,{addSuffix:!0}):typeof e==`object`?n?JSON.stringify(e,null,2):JSON.stringify(e):String(e),isExcluded=e=>n!==void 0&&e in n&&n[e]===null,transformValue=(e,t,r,i=!1)=>{if(n&&e in n){let i=n[e];if(i)return i(t,r)}return formatValue(t,i)};if(!Array.isArray(e)){let t=renderTable(Object.entries(e).filter(([e])=>!isExcluded(e)).map(([t,n])=>[t,transformValue(t,n,e,!0)]),{singleLine:!1});process.stdout.write(renderFor(process.stdout,t));return}if(e.length===0)return;let i=Array.from(new Set(e.flatMap(e=>Object.keys(e)))).filter(e=>!isExcluded(e));if(i.length===0)return;let a=renderTable([i,...e.map(e=>i.map(t=>transformValue(t,e[t],e)))],{drawHorizontalLine:(e,t)=>e===0||e===1||e===t});process.stdout.write(renderFor(process.stdout,a))}},D=/^[A-Za-z0-9_./:=@+-]+$/,O=/^[A-Za-z0-9_./:=@+\\-]+$/,k=/[%$"`“”„\p{Cc}]|\\$|^~(?:[\\/]|$)/u,A=/"|\s.*\\$|^~(?:[\\/]|$)/;function quotePosixArg(e){return D.test(e)?e:`'${e.replaceAll(`'`,`'"'"'`)}'`}function isPowerShellBare(e){return O.test(e)&&!/^(@|[+-]?\.?\d)/.test(e)&&e!==`--`&&!/^-[^-].*[.:]/.test(e)}function quotePowerShellArg(e){return isPowerShellBare(e)?e:`'${e.replace(/['‘’‚‛]/g,`$&$&`)}'`}function quoteCmdArg(e){if(O.test(e)&&!e.endsWith(`\\`))return e;let t=`"`,n=0;for(let r of e)r===`\\`?n++:(t+=r===`"`?`${`\\`.repeat(n*2)}""`:`${`\\`.repeat(n)}${r===`%`?`%%cd:~,%`:r}`,n=0);return`${t}${`\\`.repeat(n*2)}"`}function formatWindowsCommandLines(e){if(e.every(e=>isPowerShellBare(e)||e!==``&&!k.test(e)))return{kind:`shared`,commandLine:e.map(e=>isPowerShellBare(e)?e:`"${e}"`).join(` `)};let t=e.map(quoteCmdArg).join(` `);return{kind:`perShell`,powershell:e.some(e=>e===``||A.test(e))?`cmd /d /s /c ${quotePowerShellArg(t)}`:e.map(quotePowerShellArg).join(` `),cmd:t}}function formatShellCommandLines(e){return process.platform===`win32`?formatWindowsCommandLines(e):{kind:`shared`,commandLine:e.map(quotePosixArg).join(` `)}}function formatCommandHint(e){let t=formatShellCommandLines([e.command,...e.args].map(e=>redactSecrets(e)));return t.kind===`shared`?`\`${t.commandLine}\``:`\`${t.powershell}\` in PowerShell or \`${t.cmd}\` in cmd.exe`}function redactAndIndent(e){return redactSecrets(e).split(`
9
+ `));return}if(this.jsonMode){console.log(JSON.stringify(e));return}let n=t?.display,formatValue=(e,n=!1)=>t?.showNull&&e===null?`NULL`:e==null?`N/A`:e instanceof Date?r(e,{addSuffix:!0}):typeof e==`object`?n?JSON.stringify(e,null,2):JSON.stringify(e):String(e),isExcluded=e=>n!==void 0&&e in n&&n[e]===null,transformValue=(e,t,r,i=!1)=>{if(n&&e in n){let i=n[e];if(i)return i(t,r)}return formatValue(t,i)};if(!Array.isArray(e)){let t=renderTable(Object.entries(e).filter(([e])=>!isExcluded(e)).map(([t,n])=>[t,transformValue(t,n,e,!0)]),{singleLine:!1});process.stdout.write(renderFor(process.stdout,t));return}if(e.length===0)return;let i=Array.from(new Set(e.flatMap(e=>Object.keys(e)))).filter(e=>!isExcluded(e));if(i.length===0)return;let a=renderTable([i,...e.map(e=>i.map(t=>transformValue(t,e[t],e)))],{drawHorizontalLine:(e,t)=>e===0||e===1||e===t});process.stdout.write(renderFor(process.stdout,a))}},O=/^[A-Za-z0-9_./:=@+-]+$/,k=/^[A-Za-z0-9_./:=@+\\-]+$/,A=/[%$"`“”„\p{Cc}]|\\$|^~(?:[\\/]|$)/u,j=/"|\s.*\\$|^~(?:[\\/]|$)/;function quotePosixArg(e){return O.test(e)?e:`'${e.replaceAll(`'`,`'"'"'`)}'`}function isPowerShellBare(e){return k.test(e)&&!/^(@|[+-]?\.?\d)/.test(e)&&e!==`--`&&!/^-[^-].*[.:]/.test(e)}function quotePowerShellArg(e){return isPowerShellBare(e)?e:`'${e.replace(/['‘’‚‛]/g,`$&$&`)}'`}function quoteCmdArg(e){if(k.test(e)&&!e.endsWith(`\\`))return e;let t=`"`,n=0;for(let r of e)r===`\\`?n++:(t+=r===`"`?`${`\\`.repeat(n*2)}""`:`${`\\`.repeat(n)}${r===`%`?`%%cd:~,%`:r}`,n=0);return`${t}${`\\`.repeat(n*2)}"`}function formatWindowsCommandLines(e){if(e.every(e=>isPowerShellBare(e)||e!==``&&!A.test(e)))return{kind:`shared`,commandLine:e.map(e=>isPowerShellBare(e)?e:`"${e}"`).join(` `)};let t=e.map(quoteCmdArg).join(` `);return{kind:`perShell`,powershell:e.some(e=>e===``||j.test(e))?`cmd /d /s /c ${quotePowerShellArg(t)}`:e.map(quotePowerShellArg).join(` `),cmd:t}}function formatShellCommandLines(e){return process.platform===`win32`?formatWindowsCommandLines(e):{kind:`shared`,commandLine:e.map(quotePosixArg).join(` `)}}function formatCommandHint(e){let t=formatShellCommandLines([e.command,...e.args].map(e=>redactSecrets(e)));return t.kind===`shared`?`\`${t.commandLine}\``:`\`${t.powershell}\` in PowerShell or \`${t.cmd}\` in cmd.exe`}function redactAndIndent(e){return redactSecrets(e).split(`
9
10
  `).join(`
10
11
  `)}function formatError(e){let t=[h.error(`Error${e.code?` [${e.code}]`:``}: ${e.message}`)];return e.details&&t.push(`\n ${h.dim(`Details:`)} ${redactAndIndent(e.details)}`),e.suggestion&&t.push(`\n ${h.info(`Suggestion:`)} ${redactAndIndent(e.suggestion)}`),e.command&&t.push(`\n ${h.dim(`Help:`)} Run \`tailor ${e.command} --help\` for usage information.`),e.next&&t.push(`\n ${h.info(`Next:`)} Run ${formatCommandHint(e.next)}.`),t.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(`
11
- `):e instanceof Error?e.message:String(e)}function internalError(e,t){return Error(e,t)}function profileNotFoundError(e){return CLIError({code:`PROFILE_NOT_FOUND`,message:`Profile "${e}" not found`,suggestion:`Run ${formatCommandHint({command:`tailor`,args:[`profile`,`list`]})} to see the configured profiles.`})}function toError(e){return e instanceof Error?e:Error(String(e),{cause:e})}const j=/does not provide an export named '(?!default')([^']+)'/;function typeOnlyImportHint(e){if(!(e instanceof SyntaxError))return;let t=j.exec(e.message)?.[1];if(t)return`If '${t}' 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{setJsonDefaultAgent as _,isCLIError as a,parseBoolean as b,typeOnlyImportHint as c,interactiveTerminal as d,jsonDefaultAgent as f,renderRedacted as g,redactSecrets as h,internalError as i,CIPromptError as l,plainRedacted as m,errorSummary as n,profileNotFoundError as o,E as p,formatCommandHint as r,toError as s,CLIError as t,m as u,h as v,renderTable as x,g as y};
12
- //# sourceMappingURL=errors-Dmdnq0zi.mjs.map
12
+ `):e instanceof Error?e.message:String(e)}function internalError(e,t){return Error(e,t)}function profileNotFoundError(e){return CLIError({code:`PROFILE_NOT_FOUND`,message:`Profile "${e}" not found`,suggestion:`Run ${formatCommandHint({command:`tailor`,args:[`profile`,`list`]})} to see the configured profiles.`})}function toError(e){return e instanceof Error?e:Error(String(e),{cause:e})}const M=/does not provide an export named '(?!default')([^']+)'/;function typeOnlyImportHint(e){if(!(e instanceof SyntaxError))return;let t=M.exec(e.message)?.[1];if(t)return`If '${t}' 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{displayWidth as C,parseBoolean as S,sanitizeTerminalBlock as _,isCLIError as a,h as b,typeOnlyImportHint as c,interactiveTerminal as d,jsonDefaultAgent as f,renderRedacted as g,redactSecrets as h,internalError as i,CIPromptError as l,plainRedacted as m,errorSummary as n,profileNotFoundError as o,D as p,formatCommandHint as r,toError as s,CLIError as t,m as u,sanitizeTerminalText as v,renderTable as w,g as x,setJsonDefaultAgent as y};
13
+ //# sourceMappingURL=errors-9OOL3xOM.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors-9OOL3xOM.mjs","names":["styleText","name","text","color","forced","stream","stripVTControlCharacters","ANSI_ESCAPE_PATTERN","CARRIAGE_RETURN_PATTERN","graphemeSegmenter","values","value","max","fallback","codePoint","char","sgrSequences","chars","segment","result","i","cell","ZERO_WIDTH_CLUSTER_PATTERN","RGI_EMOJI_PATTERN","width","eastAsianWidth","cellLine","left","columnWidths","join","right","columnCount","rows","row","index","data","rowCount","rowsCellLines","col","line","config","lineIndex","lines","rowHeight","cellLines","columnLines","cells","rowIndex","TRUTHY_VALUES","FALSY_VALUES","normalized","JSON_OUTPUT_ENV_VAR","isCI","agent","_jsonDefaultAgent","source","reason","_jsonMode","_jsonModeSource","message","styles","symbols","_verbose","_secrets","REDACTED_PLACEHOLDER","root","secret","secrets","node","ch","next","queue","head","parent","child","fail","_automaton","spans","protectedSpans","from","start","end","pStart","pEnd","a","b","merged","span","last","cursor","rendered","render","plain","redactedPlain","styled","TERMINAL_CONTROL_CHARACTERS","TYPE_ICONS","TYPE_COLORS","opts","indentPrefix","indent","colorFn","type","mode","icon","coloredOutput","timestamp","inspectOpts","output","formatWithOptions","logger","sizeBefore","jsonEscaped","formEncoded","display","options","formatDistanceToNowStrict","pretty","key","transformer","item","headers","h","t","header","POSIX_BARE_ARG","CMD_BARE_ARG","WINDOWS_DOUBLE_QUOTE_UNSAFE","POWERSHELL_VERSION_SENSITIVE","quoted","backslashes","argv","cmd","commandLines","action","arg","parts","error","profile","MISSING_NAMED_EXPORT_PATTERN"],"sources":["../../shared/src/color.ts","../src/cli/shared/ascii-table.ts","../src/cli/shared/parse-boolean.ts","../src/cli/shared/logger.ts","../src/cli/shared/shell-quote.ts","../src/cli/shared/errors.ts"],"sourcesContent":["import { stripVTControlCharacters, styleText } from \"node:util\";\n\n/** Applies a style to text */\nexport type StyleFn = (text: string) => string;\n\ntype StyleName = Exclude<Parameters<typeof styleText>[0], readonly unknown[] | unknown[]>;\n\nconst style =\n (name: StyleName): StyleFn =>\n (text) =>\n styleText(name, text, { validateStream: false });\n\n/**\n * Style functions by name, so call sites read `color.bold(text)`. Styling is\n * always applied; `renderFor` drops it again when the destination stream has no\n * color support. Add a name here when a package needs one that is not listed.\n */\nexport const color = {\n bold: style(\"bold\"),\n dim: style(\"dim\"),\n italic: style(\"italic\"),\n gray: style(\"gray\"),\n white: style(\"white\"),\n red: style(\"red\"),\n green: style(\"green\"),\n yellow: style(\"yellow\"),\n cyan: style(\"cyan\"),\n magenta: style(\"magenta\"),\n redBright: style(\"redBright\"),\n greenBright: style(\"greenBright\"),\n cyanBright: style(\"cyanBright\"),\n};\n\n// Node's rules for whether a destination gets colors, applied by hand. Asking\n// styleText instead would be shorter but only correct on Node: Bun ignores both\n// the stream option and NO_COLOR (reproduced on 1.3.14), so it reports every\n// destination as color-capable and escapes end up in redirected output.\n//\n// FORCE_COLOR decides on its own when set, which is how CI keeps colors through\n// a pipe. NO_COLOR counts as set at any non-empty value, \"0\" included.\nconst supportsColor = (stream: NodeJS.WriteStream): boolean => {\n const forced = process.env.FORCE_COLOR;\n if (forced !== undefined) return forced !== \"0\" && forced !== \"false\";\n if (process.env.NODE_DISABLE_COLORS !== undefined) return false;\n if ((process.env.NO_COLOR ?? \"\") !== \"\") return false;\n if (process.env.TERM === \"dumb\") return false;\n return stream.isTTY === true;\n};\n\n/**\n * Prepares styled text for the stream it is written to.\n * @param stream - Stream the text is written to\n * @param text - Styled text\n * @returns Text with styling removed when the stream has no color support\n */\nexport function renderFor(stream: NodeJS.WriteStream, text: string): string {\n return supportsColor(stream) ? text : stripVTControlCharacters(text);\n}\n","import { eastAsianWidth } from \"get-east-asian-width\";\n\n// eslint-disable-next-line no-control-regex\nconst ANSI_ESCAPE_PATTERN = /\\x1b\\[[0-9;]*m/g;\nconst CARRIAGE_RETURN_PATTERN = /\\r\\n?/g;\n\nconst graphemeSegmenter = new Intl.Segmenter(undefined, { granularity: \"grapheme\" });\n\nexport interface AsciiTableConfig {\n /** Suppress horizontal lines between rows, keeping only the outer border. */\n singleLine?: boolean;\n /** Decide whether to draw the horizontal line at `lineIndex` (range `[0, rowCount]` inclusive). */\n drawHorizontalLine?: (lineIndex: number, rowCount: number) => boolean;\n}\n\ninterface CellLine {\n text: string;\n width: number;\n}\n\nfunction maxOf(values: number[], fallback = 0): number {\n return values.reduce((max, value) => (value > max ? value : max), fallback);\n}\n\nconst TAB_WIDTH = 8;\n\nfunction isStrippableControlCharacter(char: string): boolean {\n const codePoint = char.codePointAt(0) ?? 0;\n if (char === \"\\n\") {\n return false;\n }\n return codePoint <= 0x1f || codePoint === 0x7f;\n}\n\n// Only SGR (color/style) escape sequences are meant to survive; a bare ESC\n// that isn't part of a recognized SGR sequence (e.g. a screen-clear CSI\n// sequence, or a BEL-terminated OSC sequence) is treated like any other\n// control character below and stripped, rather than passed through to the\n// terminal or left with its terminator removed.\nfunction normalizeControlCharacters(value: string): string {\n const sgrSequences = value.match(ANSI_ESCAPE_PATTERN) ?? [];\n return value\n .split(ANSI_ESCAPE_PATTERN)\n .map((segment) => {\n const chars: string[] = [];\n for (const char of segment) {\n if (char === \"\\t\") {\n chars.push(\" \".repeat(TAB_WIDTH));\n } else if (!isStrippableControlCharacter(char)) {\n chars.push(char);\n }\n }\n return chars.join(\"\");\n })\n .reduce((result, segment, i) => result + segment + (sgrSequences[i] ?? \"\"), \"\");\n}\n\nfunction sanitizeCell(cell: unknown): string {\n return normalizeControlCharacters(String(cell ?? \"\").replace(CARRIAGE_RETURN_PATTERN, \"\\n\"));\n}\n\n// Clusters made up entirely of non-printing code points (lone joiners,\n// variation selectors, combining marks, etc.) render with no visible glyph.\nconst ZERO_WIDTH_CLUSTER_PATTERN =\n /^(?:\\p{Default_Ignorable_Code_Point}|\\p{Control}|\\p{Format}|\\p{Nonspacing_Mark}|\\p{Enclosing_Mark}|\\p{Surrogate})+$/v;\n// RGI_Emoji covers flags, keycaps, and VS16-forced presentation sequences,\n// which render as 2 columns in terminals even though their first code point\n// alone would measure as narrow/neutral.\nconst RGI_EMOJI_PATTERN = /^\\p{RGI_Emoji}$/v;\n\nexport function displayWidth(value: string): number {\n let width = 0;\n for (const { segment } of graphemeSegmenter.segment(value.replace(ANSI_ESCAPE_PATTERN, \"\"))) {\n if (ZERO_WIDTH_CLUSTER_PATTERN.test(segment)) {\n continue;\n }\n if (RGI_EMOJI_PATTERN.test(segment)) {\n width += 2;\n continue;\n }\n const codePoint = segment.codePointAt(0);\n width += codePoint === undefined ? 0 : eastAsianWidth(codePoint);\n }\n return width;\n}\n\nfunction toCellLines(cell: string): CellLine[] {\n return cell.split(\"\\n\").map((text) => ({ text, width: displayWidth(text) }));\n}\n\nfunction padCell(cellLine: CellLine, width: number): string {\n return cellLine.text + \" \".repeat(Math.max(0, width - cellLine.width));\n}\n\nfunction renderBorder(left: string, join: string, right: string, columnWidths: number[]): string {\n return left + columnWidths.map((width) => \"─\".repeat(width + 2)).join(join) + right;\n}\n\nfunction validateConsistentColumnCount(rows: string[][]): void {\n const columnCount = rows[0]?.length;\n if (columnCount === undefined) {\n return;\n }\n rows.forEach((row, index) => {\n if (row.length !== columnCount) {\n throw new Error(\n `renderTable: all rows must have the same number of columns (expected ${columnCount}, row ${index} has ${row.length}).`,\n );\n }\n });\n}\n\n/**\n * Renders a 2D array of values as a table using single-line Unicode box-drawing borders.\n * Column widths account for East Asian wide characters (measured per grapheme cluster,\n * so combining marks and ZWJ emoji sequences aren't overcounted, non-printing clusters\n * such as a lone joiner or combining mark measure as 0, and flags, keycaps, and\n * VS16-forced emoji presentation are measured as 2 columns) and strip ANSI SGR (color/style)\n * escape codes before measuring. Use this instead of importing a table-rendering package\n * directly.\n * @param data - Table rows; every row must have the same number of columns. Each cell is\n * stringified (`null`/`undefined` become an empty string rather than the literal text\n * \"null\"/\"undefined\"), may contain embedded newlines, has `\\r`/`\\r\\n` normalized to `\\n`,\n * has tabs expanded to spaces, and has other control characters stripped.\n * @param config - Rendering options\n * @returns The rendered table terminated with a trailing newline, or `\"\"` when there are no\n * rows or no columns to display\n */\nexport function renderTable(data: unknown[][], config: AsciiTableConfig = {}): string {\n const rows = data.map((row) => row.map(sanitizeCell));\n validateConsistentColumnCount(rows);\n\n const rowCount = rows.length;\n const columnCount = rows[0]?.length ?? 0;\n if (rowCount === 0 || columnCount === 0) {\n return \"\";\n }\n\n const rowsCellLines = rows.map((row) =>\n Array.from({ length: columnCount }, (_, col) => toCellLines(row[col] ?? \"\")),\n );\n const columnWidths = Array.from({ length: columnCount }, (_, col) =>\n maxOf(rowsCellLines.map((row) => maxOf((row[col] ?? []).map((line) => line.width)))),\n );\n\n const shouldDrawLine = (lineIndex: number): boolean =>\n config.singleLine\n ? lineIndex === 0 || lineIndex === rowCount\n : (config.drawHorizontalLine ?? (() => true))(lineIndex, rowCount);\n\n const lines: string[] = [];\n if (shouldDrawLine(0)) {\n lines.push(renderBorder(\"┌\", \"┬\", \"┐\", columnWidths));\n }\n\n rowsCellLines.forEach((cellLines, rowIndex) => {\n const rowHeight = maxOf(\n cellLines.map((columnLines) => columnLines.length),\n 1,\n );\n for (let line = 0; line < rowHeight; line++) {\n const cells = cellLines.map((columnLines, col) =>\n padCell(columnLines[line] ?? { text: \"\", width: 0 }, columnWidths[col] ?? 0),\n );\n lines.push(`│ ${cells.join(\" │ \")} │`);\n }\n if (rowIndex < rowCount - 1 && shouldDrawLine(rowIndex + 1)) {\n lines.push(renderBorder(\"├\", \"┼\", \"┤\", columnWidths));\n }\n });\n\n if (shouldDrawLine(rowCount)) {\n lines.push(renderBorder(\"└\", \"┴\", \"┘\", columnWidths));\n }\n\n return `${lines.join(\"\\n\")}\\n`;\n}\n","const TRUTHY_VALUES = new Set([\"true\", \"t\", \"yes\", \"y\", \"on\", \"1\"]);\nconst FALSY_VALUES = new Set([\"false\", \"f\", \"no\", \"n\", \"off\", \"0\"]);\n\n/**\n * Parse a string value as a boolean.\n *\n * Recognized values (case-insensitive, trimmed) follow Python's\n * `distutils.util.strtobool` convention:\n * - truthy: `true, t, yes, y, on, 1`\n * - falsy: `false, f, no, n, off, 0`\n *\n * Undefined, empty strings, and unrecognized values return `undefined` so\n * that callers can fall back to their own defaults.\n * @param value - The input string (e.g. an environment variable or CLI flag value)\n * @returns `true`, `false`, or `undefined` when the value is unset or unrecognized\n */\nexport function parseBoolean(value: string | undefined): boolean | undefined {\n if (value === undefined) return undefined;\n const normalized = value.trim().toLowerCase();\n if (normalized === \"\") return undefined;\n if (TRUTHY_VALUES.has(normalized)) return true;\n if (FALSY_VALUES.has(normalized)) return false;\n return undefined;\n}\n","import { formatWithOptions, stripVTControlCharacters, type InspectOptions } from \"node:util\";\nimport { color, renderFor } from \"@tailor-platform/shared/color\";\nimport { formatDistanceToNowStrict } from \"date-fns\";\nimport { isCI } from \"std-env\";\nimport { renderTable } from \"./ascii-table\";\nimport { parseBoolean } from \"./parse-boolean\";\n\n/** Environment variable selecting JSON as the default output for every command. */\nexport const JSON_OUTPUT_ENV_VAR = \"TAILOR_JSON_OUTPUT\";\n\n/**\n * Whether the process is attached to an interactive terminal outside CI.\n * @returns True when both stdin and stdout are TTYs and CI is not detected\n */\nexport function interactiveTerminal(): boolean {\n return !isCI && process.stdin.isTTY === true && process.stdout.isTTY === true;\n}\n\n/**\n * What selected JSON output: an explicit `--json`, the environment, both, or\n * the AI coding agent running the CLI.\n */\nexport type JsonModeSource = \"flag\" | \"env\" | \"both\" | \"agent\";\n\n/**\n * Explain what selected JSON output and how to turn it off. Under an AI coding\n * agent, dropping `--json` or unsetting the variable falls back to JSON again,\n * so the remedy names the explicit `false` values instead.\n * @param source - What selected JSON output\n * @returns Sentence appended to the prompt refusal\n */\nfunction jsonModeRemedy(source: JsonModeSource): string {\n const agent = _jsonDefaultAgent;\n switch (source) {\n case \"agent\":\n return ` JSON output is enabled because an AI coding agent${agent ? ` (${agent})` : \"\"} was detected; pass --json=false or set ${JSON_OUTPUT_ENV_VAR}=false to restore prompts.`;\n case \"flag\":\n return agent\n ? \" JSON output is enabled by --json; pass --json=false instead to restore prompts.\"\n : \" JSON output is enabled by --json; drop it to restore prompts.\";\n case \"env\":\n return agent\n ? ` JSON output is enabled by ${JSON_OUTPUT_ENV_VAR}; set it to false to restore prompts.`\n : ` JSON output is enabled by ${JSON_OUTPUT_ENV_VAR}; unset it to restore prompts.`;\n case \"both\":\n return agent\n ? ` JSON output is enabled by --json and ${JSON_OUTPUT_ENV_VAR}; pass --json=false instead of the flag to restore prompts.`\n : ` JSON output is enabled by --json and ${JSON_OUTPUT_ENV_VAR}; drop the flag and unset the variable to restore prompts.`;\n }\n}\n\n/**\n * Error thrown when a prompt is attempted in a non-interactive environment.\n *\n * JSON mode suppresses prompts, so name whatever selected it: an explicit\n * `--json` stays enabled however the environment is set, while\n * `TAILOR_JSON_OUTPUT` or a detected AI coding agent leaves nothing in the\n * command line to explain the refusal.\n */\nexport class CIPromptError extends Error {\n constructor(message?: string) {\n const reason =\n _jsonMode && _jsonModeSource !== undefined && interactiveTerminal()\n ? jsonModeRemedy(_jsonModeSource)\n : \"\";\n super(\n (message ??\n \"Interactive prompts are not available in this environment. Provide the required options explicitly.\") +\n reason,\n );\n this.name = \"CIPromptError\";\n }\n}\n\n/**\n * Semantic style functions for inline text styling\n */\nexport const styles = {\n // Status colors\n success: color.green,\n error: color.red,\n warning: color.yellow,\n info: color.cyan,\n\n // Action colors (for change sets)\n create: color.green,\n update: color.yellow,\n delete: color.red,\n replace: color.magenta,\n unchanged: color.gray,\n\n // Emphasis\n bold: color.bold,\n dim: color.gray,\n highlight: color.cyanBright,\n successBright: color.greenBright,\n errorBright: color.redBright,\n\n // Resource types\n resourceType: color.bold,\n resourceName: color.cyan,\n\n // File paths\n path: color.cyan,\n\n // Values\n value: color.white,\n placeholder: (text: string) => color.italic(color.gray(text)),\n};\n\n/**\n * Standardized symbols for CLI output\n */\nexport const symbols = {\n success: styles.success(\"\\u2713\"),\n error: styles.error(\"\\u2716\"),\n warning: styles.warning(\"\\u26a0\"),\n info: styles.info(\"i\"),\n create: styles.create(\"+\"),\n update: styles.update(\"~\"),\n delete: styles.delete(\"-\"),\n replace: styles.replace(\"\\u00b1\"),\n bullet: styles.dim(\"\\u2022\"),\n arrow: styles.dim(\"\\u2192\"),\n};\n\n/**\n * Log output modes\n */\nexport type LogMode = \"default\" | \"stream\" | \"plain\";\n\nexport interface LogOptions {\n /** Output mode (default: \"default\") */\n mode?: LogMode;\n /** Number of spaces to indent the entire line (default: 0) */\n indent?: number;\n}\n\n/** Field transformer function. null excludes the field from table output. */\nexport type FieldTransformer = ((value: unknown, item: object) => string) | null;\n\nexport interface OutOptions {\n /** Table display field transform/exclude settings. Only applied in table mode (not JSON). */\n display?: Record<string, FieldTransformer>;\n\n /** Show null values in table output (default: false) */\n showNull?: boolean;\n}\n\n// In JSON mode, all logs go to stderr to keep stdout clean for JSON data\nlet _jsonMode = false;\nlet _jsonModeSource: JsonModeSource | undefined;\nlet _jsonDefaultAgent: string | undefined;\nlet _verbose: boolean | undefined;\n\n// Values registered via `logger.registerSecret()`, redacted from diagnostic log output\nconst _secrets = new Set<string>();\nconst REDACTED_PLACEHOLDER = \"<redacted>\";\n// Below this length, a registered value is too likely to match unrelated text.\nconst MIN_SECRET_LENGTH = 4;\n\n/**\n * Aho-Corasick trie node. Indexed by individual UTF-16 code units (not Unicode code\n * points), matching how `string.indexOf`/`.slice` already index this file's strings — a\n * surrogate-pair character occupies two nodes, same as it occupies two `string` indices.\n */\ninterface TrieNode {\n children: Map<string, TrieNode>;\n fail: TrieNode;\n /** Secrets ending at this node, including those reached via `fail` links (precomputed). */\n outputs: string[];\n}\n\n/**\n * Builds a multi-pattern matcher for every registered secret, so `findSecretSpans` below\n * can find all of their occurrences in one pass over the text (`O(text.length + matches)`)\n * instead of scanning the full text once per registered secret. Rebuilt only when\n * `registerSecret` adds a genuinely new value (see `_automaton` below), so its\n * `O(total secret length)` construction cost is amortized across every log line redacted\n * while the secret set doesn't change.\n * @param secrets - Currently registered secrets\n * @returns Root of the built trie\n */\nfunction buildAutomaton(secrets: ReadonlySet<string>): TrieNode {\n const root: TrieNode = {\n children: new Map(),\n fail: undefined as unknown as TrieNode,\n outputs: [],\n };\n root.fail = root;\n\n for (const secret of secrets) {\n let node = root;\n for (let i = 0; i < secret.length; i++) {\n const ch = secret[i] as string;\n let next = node.children.get(ch);\n if (!next) {\n next = { children: new Map(), fail: root, outputs: [] };\n node.children.set(ch, next);\n }\n node = next;\n }\n node.outputs.push(secret);\n }\n\n // A head index instead of Array#shift(): shift() re-indexes every remaining element on\n // each call, which would make this loop quadratic in the number of trie nodes rather than\n // the linear BFS this is meant to be.\n const queue: TrieNode[] = [...root.children.values()];\n for (let head = 0; head < queue.length; head++) {\n const parent = queue[head] as TrieNode;\n for (const [ch, child] of parent.children) {\n let fail = parent.fail;\n while (fail !== root && !fail.children.has(ch)) fail = fail.fail;\n child.fail = fail.children.get(ch) ?? root;\n child.outputs = child.outputs.concat(child.fail.outputs);\n queue.push(child);\n }\n }\n return root;\n}\n\n// Cached automaton for the current `_secrets` contents; `null` means rebuild on next use.\n// Invalidated only when `registerSecret` actually grows `_secrets` (Set#add on an existing\n// value is a no-op), so re-registering an already-known secret never triggers a rebuild.\nlet _automaton: TrieNode | null = null;\n\nfunction getAutomaton(): TrieNode {\n _automaton ??= buildAutomaton(_secrets);\n return _automaton;\n}\n\n/**\n * Finds every occurrence of every registered secret in `text`, including overlapping ones,\n * in a single pass over `text` via the Aho-Corasick automaton.\n * @param text - Text to search\n * @returns Match spans as `[start, end)` pairs, in the order found\n */\nfunction findSecretSpans(text: string): Array<[start: number, end: number]> {\n const spans: Array<[start: number, end: number]> = [];\n const root = getAutomaton();\n let node = root;\n for (let i = 0; i < text.length; i++) {\n const ch = text[i] as string;\n while (node !== root && !node.children.has(ch)) node = node.fail;\n node = node.children.get(ch) ?? root;\n for (const secret of node.outputs) {\n spans.push([i + 1 - secret.length, i + 1]);\n }\n }\n return spans;\n}\n\n/**\n * Redacts every registered secret from `text` in a single pass over the original text.\n *\n * Matches are found against the original text only - never against text a previous\n * replacement produced - and overlapping/adjacent matches (whether one secret contains\n * another, or two secrets merely cross, e.g. registering \"abcde\" and \"defghi\" against\n * \"abcdefghi\") are merged into one contiguous span before any substitution happens. This\n * avoids two failure modes an iterative \"replace one secret, then the next\" approach has:\n * a later secret re-matching inside a placeholder a previous replacement already inserted,\n * and a crossing (non-nested) overlap leaving a fragment of one secret unredacted.\n *\n * Idempotent: a match that falls inside an occurrence of `<redacted>` already present in\n * `text` is discarded rather than substituted again. Without this, calling this function\n * twice on the same text (which happens whenever something already redacted, such as a\n * `--json` error envelope, is later passed to a diagnostic log call) could corrupt the\n * placeholder itself if a registered secret happens to be one of its substrings (e.g. a\n * secret literally containing \"redact\").\n * @param text - Text to redact\n * @returns `text` with every registered secret occurrence replaced by `<redacted>`\n */\nexport function redactSecrets(text: string): string {\n if (_secrets.size === 0) return text;\n\n const protectedSpans: Array<[start: number, end: number]> = [];\n for (let from = 0, index: number; (index = text.indexOf(REDACTED_PLACEHOLDER, from)) !== -1;) {\n protectedSpans.push([index, index + REDACTED_PLACEHOLDER.length]);\n from = index + REDACTED_PLACEHOLDER.length;\n }\n\n // Only a match wholly inside a protected placeholder is discarded (it can only be the\n // placeholder's own text, e.g. a registered secret that is a substring of \"redacted\").\n // A match that merely overlaps one — extending outside it, e.g. a registered secret that\n // happens to be \"leak<redacted>\" — still has real secret content outside the placeholder\n // and must still be replaced.\n //\n // A registered secret wholly contained in the placeholder (up to and including a secret\n // equal to \"<redacted>\" itself) is indistinguishable from the placeholder in rendered\n // output either way: substituting REDACTED_PLACEHOLDER for text that already reads\n // REDACTED_PLACEHOLDER is a no-op. Discarding the match here (rather than \"fixing\" it to\n // substitute anyway) isn't a redaction gap — it just skips redundant work on text that's\n // already the safe, masked form.\n const spans = findSecretSpans(text).filter(\n ([start, end]) => !protectedSpans.some(([pStart, pEnd]) => start >= pStart && end <= pEnd),\n );\n if (spans.length === 0) return text;\n spans.sort(([a], [b]) => a - b);\n\n const merged: Array<[start: number, end: number]> = [];\n for (const span of spans) {\n const last = merged.at(-1);\n if (last && span[0] <= last[1]) {\n last[1] = Math.max(last[1], span[1]);\n } else {\n merged.push(span);\n }\n }\n\n let result = \"\";\n let cursor = 0;\n for (const [start, end] of merged) {\n result += text.slice(cursor, start) + REDACTED_PLACEHOLDER;\n cursor = end;\n }\n return result + text.slice(cursor);\n}\n\n/**\n * Renders styled text with registered secrets redacted.\n *\n * Redacts the styled text first, so a secret that itself contains a control sequence\n * matches its raw form, then checks the text again without colors, so inline colors\n * cannot split a secret out of a match. When they do, the text is returned without\n * colors, since redacting around the escapes would leave fragments of the secret visible.\n * @param text - Styled text\n * @param render - Removes styling from `text`, or keeps it\n * @returns Rendered text with registered secrets redacted\n */\nfunction renderWithRedaction(text: string, render: (text: string) => string): string {\n const rendered = render(redactSecrets(text));\n const plain = stripVTControlCharacters(rendered);\n const redactedPlain = redactSecrets(plain);\n return redactedPlain === plain ? rendered : redactedPlain;\n}\n\n/**\n * Prepares styled diagnostic text for the stream it is written to, with registered\n * secrets redacted.\n * @param stream - Stream the text is written to\n * @param text - Styled text\n * @returns Text with styling removed when the stream has no color support, and registered secrets redacted\n */\nexport function renderRedacted(stream: NodeJS.WriteStream, text: string): string {\n return renderWithRedaction(text, (styled) => renderFor(stream, styled));\n}\n\n/**\n * Removes styling from text, with registered secrets redacted.\n * @param text - Styled text\n * @returns Plain text with registered secrets redacted\n */\nexport function plainRedacted(text: string): string {\n return renderWithRedaction(text, stripVTControlCharacters);\n}\n\n// C0 controls other than tab and newline, DEL, C1 controls, and the Unicode line and paragraph\n// separators. Tab and newline are handled as whitespace below so they become a single space.\n// The control characters are the point of this expression.\n// oxlint-disable-next-line no-control-regex\nconst TERMINAL_CONTROL_CHARACTERS = /[\\u0000-\\u0008\\u000b-\\u001f\\u007f-\\u009f\\u2028\\u2029]/g;\n\n/**\n * Makes text that came from a remote source safe to print on a terminal: strips ANSI escape and\n * OSC sequences and every control character, and collapses whitespace runs into one space.\n * Use it on server-provided free text (titles, bodies) before it reaches `logger`.\n * @param text - Text received from a remote source\n * @returns Single-line text with no terminal escapes or control characters\n */\nexport function sanitizeTerminalText(text: string): string {\n return stripVTControlCharacters(text)\n .replace(TERMINAL_CONTROL_CHARACTERS, \"\")\n .replace(/\\s+/g, \" \")\n .trim();\n}\n\n/**\n * Makes multi-line text that came from a remote source safe to print on a terminal: strips ANSI\n * escape and OSC sequences and every control character except tab and newline, and normalizes\n * CRLF to LF. Line structure and indentation are kept, so Markdown bodies stay readable.\n * @param text - Text received from a remote source\n * @returns The text with no terminal escapes or control characters, newlines kept\n */\nexport function sanitizeTerminalBlock(text: string): string {\n return stripVTControlCharacters(text)\n .replace(/\\r\\n?/g, \"\\n\")\n .replace(TERMINAL_CONTROL_CHARACTERS, \"\");\n}\n\n/**\n * Reset the registered-secret redaction state. Used for testing.\n *\n * `_secrets` is process-lifetime, module-level state with no production unregister API\n * (a real process should never stop hiding a secret it once saw). Test files that call\n * `logger.registerSecret()` and run in a Vitest project with `isolate: false` share this\n * state across files, so a value registered in one file's test can still be redacted in an\n * unrelated later file's assertions unless cleared between tests.\n */\nexport function resetSecretRegistry(): void {\n _secrets.clear();\n _automaton = null;\n}\n\n// Type icons for log output\nconst TYPE_ICONS: Record<string, string> = {\n info: \"ℹ\",\n success: \"✔\",\n warn: \"⚠\",\n error: \"✖\",\n debug: \"⚙\",\n trace: \"→\",\n log: \"\",\n};\n\n// Color functions for icon and message text\nconst TYPE_COLORS: Record<string, (text: string) => string> = {\n info: styles.info,\n success: styles.success,\n warn: styles.warning,\n error: styles.error,\n debug: styles.dim,\n trace: styles.dim,\n log: (text) => text,\n};\n\ninterface FormatLogLineOptions {\n mode: string;\n indent: number;\n type: string;\n message: string;\n timestamp?: string;\n}\n\n/**\n * Formats a log line with the appropriate prefix and indentation\n * @param opts - Formatting options\n * @returns Formatted log line\n */\nexport function formatLogLine(opts: FormatLogLineOptions): string {\n const { mode, indent, type, message, timestamp } = opts;\n const indentPrefix = indent > 0 ? \" \".repeat(indent) : \"\";\n const colorFn = TYPE_COLORS[type] || ((text: string) => text);\n\n // Plain mode: color only, no icon, no timestamp\n if (mode === \"plain\") {\n return `${indentPrefix}${colorFn(message)}\\n`;\n }\n\n // Default/Stream mode: with icon and color\n const icon = TYPE_ICONS[type] || \"\";\n const prefix = icon ? `${icon} ` : \"\";\n const coloredOutput = colorFn(`${prefix}${message}`);\n const timestampPrefix = timestamp ?? \"\";\n\n return `${indentPrefix}${timestampPrefix}${coloredOutput}\\n`;\n}\n\n/**\n * Writes a formatted log line to stderr.\n * @param type - Log type (info, success, warn, error, log)\n * @param message - Log message\n * @param opts - Log options (mode and indent)\n */\nfunction writeLog(type: string, message: string, opts?: LogOptions): void {\n const mode = opts?.mode ?? \"default\";\n const indent = opts?.indent ?? 0;\n const inspectOpts: InspectOptions = {\n breakLength: process.stdout.columns || 80,\n };\n const formattedMessage = formatWithOptions(inspectOpts, message);\n const timestamp = mode === \"stream\" ? `${new Date().toLocaleTimeString()} ` : \"\";\n const output = formatLogLine({ mode, indent, type, message: formattedMessage, timestamp });\n process.stderr.write(renderRedacted(process.stderr, output));\n}\n\n/**\n * Record the AI coding agent running the Tailor CLI, which makes JSON the\n * default output. CLI plugins never record one, so they keep table output.\n * @param agent - Detected agent id (e.g. `\"claude_code\"`), or undefined when none runs the CLI\n */\nexport function setJsonDefaultAgent(agent: string | undefined): void {\n _jsonDefaultAgent = agent;\n}\n\n/**\n * The AI coding agent recorded by {@link setJsonDefaultAgent}.\n * @returns Detected agent id, or undefined when none was recorded\n */\nexport function jsonDefaultAgent(): string | undefined {\n return _jsonDefaultAgent;\n}\n\n/**\n * The CLI logger. Diagnostics go to stderr; `out()` writes primary output to\n * stdout as a table, or as JSON when `jsonMode` is on. `--json` and\n * `--verbose` feed the `jsonMode` / `verbose` state, which CLI plugins share\n * with the SDK code paths they call.\n */\nexport const logger = {\n get jsonMode(): boolean {\n return _jsonMode;\n },\n set jsonMode(value: boolean) {\n _jsonMode = value;\n if (!value) _jsonModeSource = undefined;\n },\n\n /**\n * Enable or disable JSON mode, recording what selected it so a suppressed\n * prompt can name the right remedy.\n * @param value - Whether JSON output is on\n * @param source - What turned it on; omit when turning it off\n */\n setJsonMode(value: boolean, source?: JsonModeSource): void {\n _jsonMode = value;\n _jsonModeSource = value ? source : undefined;\n },\n\n get verbose(): boolean {\n return (\n _verbose ?? (parseBoolean(process.env.DEBUG) === true || process.env.RUNNER_DEBUG === \"1\")\n );\n },\n /**\n * Turn verbose output on or off, overriding `DEBUG` and `RUNNER_DEBUG`.\n * @param value - Whether verbose output is on, or undefined to defer to `DEBUG` and `RUNNER_DEBUG`\n */\n set verbose(value: boolean | undefined) {\n _verbose = value;\n },\n\n info(message: string, opts?: LogOptions): void {\n writeLog(\"info\", message, opts);\n },\n\n success(message: string, opts?: LogOptions): void {\n writeLog(\"success\", message, opts);\n },\n\n warn(message: string, opts?: LogOptions): void {\n writeLog(\"warn\", message, opts);\n },\n\n error(message: string, opts?: LogOptions): void {\n writeLog(\"error\", message, opts);\n },\n\n log(message: string): void {\n writeLog(\"log\", message, { mode: \"plain\" });\n },\n\n newline(): void {\n process.stderr.write(\"\\n\");\n },\n\n debug(message: string): void {\n if (logger.verbose) {\n writeLog(\"log\", styles.dim(message), { mode: \"plain\" });\n }\n },\n\n /**\n * Registers a value to be redacted from diagnostic log output (`info`/`success`/`warn`/\n * `error`/`log`/`debug`). Any occurrence of `value` — or of its JSON-string-escaped form\n * (so a value embedded in `JSON.stringify`d output, e.g. `--json` mode error envelopes, is\n * also caught) or its `application/x-www-form-urlencoded` form (so a value that reached the\n * process via a URL query string, e.g. an OAuth authorization code decoded from a callback\n * URL via `URLSearchParams`, is still caught if that same URL — still encoded — is later\n * echoed into a diagnostic message) — is replaced with `<redacted>` before it reaches\n * stderr. Does not affect `out()`, since some commands intentionally print secret values as\n * their primary result.\n *\n * Values shorter than 4 characters are ignored, since they are too likely to match\n * unrelated text. A non-string value (e.g. `undefined` from an unvalidated external\n * payload cast to a typed shape) is ignored the same way, rather than throwing, since a\n * logging call must never be what crashes the process.\n * @param value - The secret value to redact from future log output\n */\n registerSecret(value: string): void {\n // Counts Unicode code points, not UTF-16 code units, so a value made of surrogate-pair\n // characters (e.g. emoji) isn't undercounted as longer than it actually is.\n if (typeof value !== \"string\" || [...value].length < MIN_SECRET_LENGTH) return;\n const sizeBefore = _secrets.size;\n _secrets.add(value);\n const jsonEscaped = JSON.stringify(value).slice(1, -1);\n if (jsonEscaped !== value) _secrets.add(jsonEscaped);\n // Uses URLSearchParams rather than encodeURIComponent: form-urlencoding (what\n // URLSearchParams produces, and what a URL query string actually contains) encodes a\n // space as \"+\", not \"%20\", and unlike encodeURIComponent it never throws on a lone\n // surrogate (invalid UTF-16) — it substitutes U+FFFD instead, matching how the URL\n // itself would already have encoded that same malformed input.\n const formEncoded = new URLSearchParams([[\"v\", value]]).toString().slice(2);\n if (formEncoded !== value) _secrets.add(formEncoded);\n // Set#add on an already-registered value is a no-op, so this only invalidates the\n // cached automaton (see findSecretSpans) when a genuinely new secret was added.\n if (_secrets.size !== sizeBefore) _automaton = null;\n },\n\n out(data: string | object | object[], options?: OutOptions): void {\n if (typeof data === \"string\") {\n process.stdout.write(renderFor(process.stdout, data.endsWith(\"\\n\") ? data : data + \"\\n\"));\n return;\n }\n\n if (this.jsonMode) {\n // eslint-disable-next-line no-restricted-syntax\n console.log(JSON.stringify(data));\n return;\n }\n\n const display = options?.display;\n\n // Helper to format a value for table display\n const formatValue = (value: unknown, pretty = false): string => {\n if (options?.showNull && value === null) return \"NULL\";\n if (value === null || value === undefined) return \"N/A\";\n if (value instanceof Date) {\n return formatDistanceToNowStrict(value, { addSuffix: true });\n }\n if (typeof value === \"object\") {\n return pretty ? JSON.stringify(value, null, 2) : JSON.stringify(value);\n }\n return String(value);\n };\n\n // Helper to check if field should be excluded\n const isExcluded = (key: string): boolean => {\n return display !== undefined && key in display && display[key] === null;\n };\n\n // Helper to apply transformer or default formatting\n const transformValue = (key: string, value: unknown, item: object, pretty = false): string => {\n if (display && key in display) {\n const transformer = display[key];\n if (transformer) {\n return transformer(value, item);\n }\n }\n return formatValue(value, pretty);\n };\n\n if (!Array.isArray(data)) {\n const entries = Object.entries(data).filter(([key]) => !isExcluded(key));\n const formattedEntries = entries.map(([key, value]) => [\n key,\n transformValue(key, value, data, true),\n ]);\n const t = renderTable(formattedEntries, { singleLine: false });\n process.stdout.write(renderFor(process.stdout, t));\n return;\n }\n\n if (data.length === 0) {\n return;\n }\n\n const allHeaders = Array.from(new Set(data.flatMap((item) => Object.keys(item))));\n const headers = allHeaders.filter((h) => !isExcluded(h));\n if (headers.length === 0) {\n return;\n }\n const rows = data.map((item) =>\n headers.map((header) =>\n transformValue(header, (item as Record<string, unknown>)[header], item),\n ),\n );\n\n const t = renderTable([headers, ...rows], {\n drawHorizontalLine: (lineIndex, rowCount) => {\n return lineIndex === 0 || lineIndex === 1 || lineIndex === rowCount;\n },\n });\n process.stdout.write(renderFor(process.stdout, t));\n },\n};\n","/**\n * Command lines for a suggested command: one line when every supported shell reads it the same\n * way, otherwise one line per Windows shell.\n */\nexport type ShellCommandLines =\n | { kind: \"shared\"; commandLine: string }\n | { kind: \"perShell\"; powershell: string; cmd: string };\n\nconst POSIX_BARE_ARG = /^[A-Za-z0-9_./:=@+-]+$/;\nconst CMD_BARE_ARG = /^[A-Za-z0-9_./:=@+\\\\-]+$/;\n// PowerShell expands `$` and backtick escapes inside double quotes and reads `“ ” „` as `\"`,\n// cmd.exe expands `%` even inside quotes, a `\"` or a trailing backslash changes where the\n// quoted argument ends, and a leading `~` is version-sensitive (below).\nconst WINDOWS_DOUBLE_QUOTE_UNSAFE = /[%$\"`“”„\\p{Cc}]|\\\\$|^~(?:[\\\\/]|$)/u;\n// PowerShell versions pass these to programs differently: Windows PowerShell 5.1 and 7.3+\n// disagree on quotes and trailing backslashes, and 7.6+ expands a leading `~` inside the `.ps1`\n// shim however it was quoted.\nconst POWERSHELL_VERSION_SENSITIVE = /\"|\\s.*\\\\$|^~(?:[\\\\/]|$)/;\n\nfunction quotePosixArg(value: string): string {\n if (POSIX_BARE_ARG.test(value)) return value;\n return `'${value.replaceAll(\"'\", `'\"'\"'`)}'`;\n}\n\nfunction isPowerShellBare(value: string): boolean {\n // A leading `@` splats, a lone `--` ends parameters, a leading digit reads as a number, and a\n // single-dash token with `.` or `:` reads as parameter syntax.\n return (\n CMD_BARE_ARG.test(value) &&\n !/^(@|[+-]?\\.?\\d)/.test(value) &&\n value !== \"--\" &&\n !/^-[^-].*[.:]/.test(value)\n );\n}\n\nfunction quotePowerShellArg(value: string): string {\n if (isPowerShellBare(value)) return value;\n return `'${value.replace(/['‘’‚‛]/g, \"$&$&\")}'`;\n}\n\nfunction quoteCmdArg(value: string): string {\n // Quoting a trailing backslash keeps a command routed through `cmd /c` from ending in one,\n // which PowerShell 7 doubles when it quotes the line.\n if (CMD_BARE_ARG.test(value) && !value.endsWith(\"\\\\\")) return value;\n let quoted = '\"';\n let backslashes = 0;\n for (const char of value) {\n if (char === \"\\\\\") {\n backslashes++;\n continue;\n }\n if (char === '\"') {\n quoted += `${\"\\\\\".repeat(backslashes * 2)}\"\"`;\n } else {\n // `%%cd:~,%` reads back as a literal `%` without cmd.exe expanding a `%NAME%` around it.\n quoted += `${\"\\\\\".repeat(backslashes)}${char === \"%\" ? \"%%cd:~,%\" : char}`;\n }\n backslashes = 0;\n }\n return `${quoted}${\"\\\\\".repeat(backslashes * 2)}\"`;\n}\n\nfunction formatWindowsCommandLines(argv: readonly string[]): ShellCommandLines {\n if (\n argv.every(\n (value) =>\n isPowerShellBare(value) || (value !== \"\" && !WINDOWS_DOUBLE_QUOTE_UNSAFE.test(value)),\n )\n ) {\n return {\n kind: \"shared\",\n commandLine: argv.map((value) => (isPowerShellBare(value) ? value : `\"${value}\"`)).join(\" \"),\n };\n }\n const cmd = argv.map(quoteCmdArg).join(\" \");\n // Both PowerShell versions pass a `cmd` argument the same legacy way, so routing the cmd.exe\n // line through `cmd /c` keeps the arguments identical where their native quoting differs.\n const powershell = argv.some((value) => value === \"\" || POWERSHELL_VERSION_SENSITIVE.test(value))\n ? `cmd /d /s /c ${quotePowerShellArg(cmd)}`\n : argv.map(quotePowerShellArg).join(\" \");\n return { kind: \"perShell\", powershell, cmd };\n}\n\n/**\n * Render an argv array as command lines that the current platform's shells run with every\n * argument delivered unchanged\n * @param {readonly string[]} argv - Executable name followed by its arguments\n * @returns {ShellCommandLines} One shared command line, or one per Windows shell\n */\nexport function formatShellCommandLines(argv: readonly string[]): ShellCommandLines {\n if (process.platform === \"win32\") return formatWindowsCommandLines(argv);\n return { kind: \"shared\", commandLine: argv.map(quotePosixArg).join(\" \") };\n}\n","import { redactSecrets, styles } from \"./logger\";\nimport { formatShellCommandLines } from \"./shell-quote\";\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\n/**\n * Render a command as a user-facing hint that can be copied into the current platform's shells:\n * one backticked command line, or on Windows, when no single quoting suits both shells, a\n * PowerShell and a cmd.exe line (`` `…` in PowerShell or `…` in cmd.exe ``).\n * Registered secrets are redacted before quoting, which could otherwise split them.\n * @param {CLIErrorNextAction} action - Executable and arguments to suggest\n * @returns {string} The command part of the hint, to follow a verb such as \"Run\"\n */\nexport function formatCommandHint(action: CLIErrorNextAction): string {\n const commandLines = formatShellCommandLines(\n [action.command, ...action.args].map((arg) => redactSecrets(arg)),\n );\n if (commandLines.kind === \"shared\") {\n return `\\`${commandLines.commandLine}\\``;\n }\n return `\\`${commandLines.powershell}\\` in PowerShell or \\`${commandLines.cmd}\\` in cmd.exe`;\n}\n\n/**\n * Redact registered secrets, then indent every line after the first.\n * Redacting first keeps the indent from splitting a multi-line secret.\n * @param text - Details or suggestion text\n * @returns Redacted text with its continuation lines indented\n */\nfunction redactAndIndent(text: string): string {\n return redactSecrets(text).split(\"\\n\").join(\"\\n \");\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:\")} ${redactAndIndent(error.details)}`);\n }\n\n if (error.suggestion) {\n parts.push(`\\n ${styles.info(\"Suggestion:\")} ${redactAndIndent(error.suggestion)}`);\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 ${formatCommandHint(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 * Create the error for a profile name that the platform config does not define.\n * @param profile - Requested profile name\n * @returns CLIError with code `PROFILE_NOT_FOUND`\n */\nexport function profileNotFoundError(profile: string): CLIError {\n return CLIError({\n code: \"PROFILE_NOT_FOUND\",\n message: `Profile \"${profile}\" not found`,\n suggestion: `Run ${formatCommandHint({ command: \"tailor\", args: [\"profile\", \"list\"] })} to see the configured profiles.`,\n });\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":"A,qOAOA,MAAM,MACH,GACA,GACCA,EAAUC,EAAMC,EAAM,CAAE,eAAgB,EAAM,CAAC,EAOtCC,EAAQ,CACnB,KAAM,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b2dsZS5hcGkuRmllbGRCZWhhdmlvckICEABSDWZpZWxkQmVoYXZpb3JCcAoOY29tLmdvb2dsZS5hcGlCEkZpZWxkQmVoYXZpb3JQcm90b1ABWkFnb29nbGUuZ29sYW5nLm9yZy9nZW5wcm90by9nb29nbGVhcGlzL2FwaS9hbm5vdGF0aW9uczthbm5vdGF0aW9uc6ICBEdBUEliBnByb3RvMw`,[t]);export{n as t};
2
+ //# sourceMappingURL=field_behavior_pb-B196sUx6.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"field_behavior_pb-B196sUx6.mjs","names":["file_google_api_field_behavior","file_google_protobuf_descriptor"],"sources":["../../tailor-proto/src/google/api/field_behavior_pb.js"],"sourcesContent":["// Copyright 2025 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n// @generated by protoc-gen-es v2.6.3\n// @generated from file google/api/field_behavior.proto (package google.api, syntax proto3)\n/* eslint-disable */\n\nimport { enumDesc, extDesc, fileDesc, tsEnum } from \"@bufbuild/protobuf/codegenv2\";\nimport { file_google_protobuf_descriptor } from \"@bufbuild/protobuf/wkt\";\n\n/**\n * Describes the file google/api/field_behavior.proto.\n */\nexport const file_google_api_field_behavior = /*@__PURE__*/\n fileDesc(\"Ch9nb29nbGUvYXBpL2ZpZWxkX2JlaGF2aW9yLnByb3RvEgpnb29nbGUuYXBpKrYBCg1GaWVsZEJlaGF2aW9yEh4KGkZJRUxEX0JFSEFWSU9SX1VOU1BFQ0lGSUVEEAASDAoIT1BUSU9OQUwQARIMCghSRVFVSVJFRBACEg8KC09VVFBVVF9PTkxZEAMSDgoKSU5QVVRfT05MWRAEEg0KCUlNTVVUQUJMRRAFEhIKDlVOT1JERVJFRF9MSVNUEAYSFQoRTk9OX0VNUFRZX0RFRkFVTFQQBxIOCgpJREVOVElGSUVSEAg6ZAoOZmllbGRfYmVoYXZpb3ISHS5nb29nbGUucHJvdG9idWYuRmllbGRPcHRpb25zGJwIIAMoDjIZLmdvb2dsZS5hcGkuRmllbGRCZWhhdmlvckICEABSDWZpZWxkQmVoYXZpb3JCcAoOY29tLmdvb2dsZS5hcGlCEkZpZWxkQmVoYXZpb3JQcm90b1ABWkFnb29nbGUuZ29sYW5nLm9yZy9nZW5wcm90by9nb29nbGVhcGlzL2FwaS9hbm5vdGF0aW9uczthbm5vdGF0aW9uc6ICBEdBUEliBnByb3RvMw\", [file_google_protobuf_descriptor]);\n\n/**\n * Describes the enum google.api.FieldBehavior.\n */\nexport const FieldBehaviorSchema = /*@__PURE__*/\n enumDesc(file_google_api_field_behavior, 0);\n\n/**\n * An indicator of the behavior of a given field (for example, that a field\n * is required in requests, or given as output but ignored as input).\n * This **does not** change the behavior in protocol buffers itself; it only\n * denotes the behavior and may affect how API tooling handles the field.\n *\n * Note: This enum **may** receive new values in the future.\n *\n * @generated from enum google.api.FieldBehavior\n */\nexport const FieldBehavior = /*@__PURE__*/\n tsEnum(FieldBehaviorSchema);\n\n/**\n * A designation of a specific field behavior (required, output only, etc.)\n * in protobuf messages.\n *\n * Examples:\n *\n * string name = 1 [(google.api.field_behavior) = REQUIRED];\n * State state = 1 [(google.api.field_behavior) = OUTPUT_ONLY];\n * google.protobuf.Duration ttl = 1\n * [(google.api.field_behavior) = INPUT_ONLY];\n * google.protobuf.Timestamp expire_time = 1\n * [(google.api.field_behavior) = OUTPUT_ONLY,\n * (google.api.field_behavior) = IMMUTABLE];\n *\n * @generated from extension: repeated google.api.FieldBehavior field_behavior = 1052 [packed = false];\n */\nexport const field_behavior = /*@__PURE__*/\n extDesc(file_google_api_field_behavior, 0);\n\n"],"mappings":"A,iIAwBA,MAAaA,EACX,gBAAS,imBAAkmB,CAACC,CAA+B,CAAC,E"}
@@ -1,15 +1,19 @@
1
- import{t as e}from"./multiline-EyzjEwn9.mjs";import{resolve as t}from"pathe";const n=new TextEncoder;function mapFieldTypeToPostgresType(e){switch(e){case`uuid`:return`uuid`;case`string`:case`enum`:return`text`;case`boolean`:case`bool`:return`boolean`;case`integer`:return`integer`;case`float`:return`double precision`;case`decimal`:return`numeric`;case`date`:return`date`;case`datetime`:return`timestamptz`;case`time`:return`time`;case`nested`:return`jsonb`;default:throw Error(`Field type "${e}" has no PostgreSQL column type.`)}}function identifier(e){return`"${e.replaceAll(`"`,`""`)}"`}function fnv1aHex(e){let t=2166136261;for(let r of n.encode(e))t=Math.imul(t^r,16777619)>>>0;return t.toString(16).padStart(8,`0`)}function derivedName(e,t,r){let i=`_${fnv1aHex(JSON.stringify([e,t,r]))}_${r}`,a=`${e}_${t}`;for(;n.encode(a+i).length>63;)a=a.slice(0,-1);return a+i}function derivedIdentifier(e,t,n){return identifier(derivedName(e,t,n))}function dollarQuoted(e){let t=`$fk$`;for(;e.includes(t);)t=`${t.slice(0,-1)}_$`;return`${t}\n${e}\n${t}`}function stringLiteral(e){return`'${e.replaceAll(`'`,`''`)}'`}function columnType(e){let t=e.type===`decimal`?`numeric(1000, ${e.scale??6})`:mapFieldTypeToPostgresType(e.type);return e.array&&e.type!==`nested`?`${t}[]`:t}function scalarLiteral(e,t,n){let r=mapFieldTypeToPostgresType(t.type);if(e instanceof Date){if(Number.isNaN(e.getTime()))throw Error(`Default of field ${n} is an invalid Date.`);return`${stringLiteral(e.toISOString())}::${r}`}switch(typeof e){case`string`:return r===`text`?stringLiteral(e):`${stringLiteral(e)}::${r}`;case`number`:if(!Number.isFinite(e))throw Error(`Default of field ${n} is not a finite number.`);return String(e);case`boolean`:return e?`TRUE`:`FALSE`;default:throw Error(`Default of field ${n} cannot be rendered as a SQL literal.`)}}const r=/* @__PURE__ */ new Map([[`datetime`,`now()`],[`date`,`CURRENT_DATE`],[`time`,`LOCALTIME`]]);function defaultExpression(e,t){let n=e.default,i=r.get(e.type);if(n===`now`&&i!==void 0)return i;if(e.array){if(!Array.isArray(n))throw Error(`Default of array field ${t} must be an array.`);let r=columnType(e);return n.length===0?`'{}'::${r}`:`ARRAY[${n.map(n=>scalarLiteral(n,e,t)).join(`, `)}]::${r}`}return scalarLiteral(n,e,t)}function parseSerialFormat(e,t){let n=/^(?<prefix>[^%]*)%(?<zero>0?)(?<width>\d*)(?<conversion>[a-zA-Z])(?<suffix>[^%]*)$/.exec(e)?.groups,r=n?.conversion;if(!n||r!==`d`&&r!==`x`&&r!==`X`)throw Error(`Serial format "${e}" of field ${t} is not supported; use a single %d, %x, or %X specifier with an optional width (e.g. "INV-%05d").`);return{prefix:n.prefix??``,zeroPad:n.zero===`0`,width:n.width?Number(n.width):0,conversion:r,suffix:n.suffix??``}}function sequenceName(e,t){return derivedIdentifier(e,t,`seq`)}function sequenceRange(e){let t=[`START WITH ${e.start}`,`MINVALUE ${e.start}`];return e.maxValue!==void 0&&t.push(`MAXVALUE ${e.maxValue}`),t.join(` `)}const i={d:e=>e,x:e=>`to_hex(${e})`,X:e=>`upper(to_hex(${e}))`};function serialStringDefault(e,t,n){let r=`nextval(${stringLiteral(e)})`;if(t===void 0)return`(${r}::text)`;let{prefix:a,width:o,zeroPad:s,conversion:c,suffix:l}=parseSerialFormat(t,n),u=i[c](r),d=c===`d`?`${u}::text`:u;return o>0&&(d=`format('%${o}s', ${u})`,s&&(d=`translate(${d}, ' ', '0')`)),`(${[...a?[stringLiteral(a)]:[],d,...l?[stringLiteral(l)]:[]].join(` || `)})`}function columnDefinition(e,t,n){let r=identifier(t),i=`${identifier(e)}.${r}`,a=[r,columnType(n)];if(n.serial)return n.type===`integer`?(a.push(`GENERATED BY DEFAULT AS IDENTITY (${sequenceRange(n.serial)})`),n.unique&&a.push(`UNIQUE`),a.join(` `)):(n.required&&a.push(`NOT NULL`),n.unique&&a.push(`UNIQUE`),a.push(`DEFAULT ${serialStringDefault(sequenceName(e,t),n.serial.format,i)}`),a.join(` `));let o=n.default!==void 0,s=n.hooks?.create!==void 0||n.optionalOnCreate===!0;return n.required&&(o||!s)&&a.push(`NOT NULL`),n.unique&&a.push(`UNIQUE`),o&&a.push(`DEFAULT ${defaultExpression(n,i)}`),a.join(` `)}function jsonPathKey(e){return`"${e.replaceAll(`\\`,`\\\\`).replaceAll(`"`,`\\"`)}"`}function referencesWithin(e,t,n){let r=t.array?`${n}[*]`:n;return t.type===`nested`?Object.entries(t.fields??{}).flatMap(([t,n])=>referencesWithin(e,n,`${r}.${jsonPathKey(t)}`)):!t.foreignKey||t.foreignKeyType===void 0?[]:[{column:e,path:r,table:t.foreignKeyType,field:t.foreignKeyField??`id`,type:t.type}]}const a=/* @__PURE__ */ new Set([`integer`,`float`,`decimal`,`boolean`,`bool`,`uuid`]);function nestedUniqueMembers(e,t,n){return t.array?[]:t.type===`nested`?Object.entries(t.fields??{}).flatMap(([t,r])=>nestedUniqueMembers(e,r,[...n,t])):t.unique&&n.length>0?[{column:e,path:n,field:t}]:[]}function nestedUniqueIndex(e,t){let n=t.path.map(stringLiteral).join(`, `),r=`${identifier(t.column)} #>> ARRAY[${n}]`,i=a.has(t.field.type)?`CAST(${r} AS ${mapFieldTypeToPostgresType(t.field.type)})`:r;return`CREATE UNIQUE INDEX IF NOT EXISTS ${derivedIdentifier(e,`${t.column}.${t.path.join(`.`)}`,`nested_idx`)} ON ${identifier(e)} ((${i}))`}function tableReferences(e){return Object.entries(e.fields).filter(([e])=>e!==`id`).flatMap(([e,t])=>referencesWithin(e,t,`$`))}function isConstraintReference(e){return e.path===`$`}function referenceClause(e){return`REFERENCES ${identifier(e.table)} (${identifier(e.field)})`}function declaredType(e){return e===`bool`?`boolean`:e}function checkReference(e,t){let n=t.get(e.table);if(!n)return{problem:`references unknown table "${e.table}".`};let r=e.field===`id`?{type:`uuid`,unique:!0}:n.fields[e.field];return r?!r.unique||declaredType(r.type)!==declaredType(e.type)?{problem:`references "${e.table}"."${e.field}", which must be unique and of the same type as the referencing field.`}:{pgType:mapFieldTypeToPostgresType(r.type)}:{problem:`references unknown field "${e.field}" of table "${e.table}".`}}function referencedColumnType(e,t,n){let r=checkReference(e,t);if(`problem`in r)throw Error(`Field ${n} ${r.problem}`);return r.pgType}function withoutReference(e){let{foreignKey:t,foreignKeyType:n,foreignKeyField:r,...i}=e;return i}function withoutUnresolvableReference(e,t){return e.fields?{...e,fields:Object.fromEntries(Object.entries(e.fields).map(([e,n])=>[e,withoutUnresolvableReference(n,t)]))}:!e.foreignKey||e.foreignKeyType===void 0?e:`problem`in checkReference({column:``,path:`$`,table:e.foreignKeyType,field:e.foreignKeyField??`id`,type:e.type},t)?withoutReference(e):e}function dropUnresolvableReferences(e){let t=new Map(e.map(e=>[e.name,e]));return e.map(e=>({...e,fields:Object.fromEntries(Object.entries(e.fields).map(([e,n])=>[e,withoutUnresolvableReference(n,t)]))}))}function referenceCheck(e,t,n){let r=referencedColumnType(e,t,n),i=`violates foreign key constraints: % not found in ${`${identifier(e.table)}.${identifier(e.field)}`.replaceAll(`%`,`%%`)}`;return[` FOR v IN SELECT jsonb_path_query(to_jsonb(NEW.${identifier(e.column)}), ${stringLiteral(e.path)}) LOOP`,` IF jsonb_typeof(fk_check.v) <> 'null' AND NOT EXISTS (SELECT 1 FROM ${identifier(e.table)} AS parent WHERE parent.${identifier(e.field)} = (fk_check.v #>> '{}')::${r}) THEN`,` RAISE EXCEPTION ${stringLiteral(i)}, fk_check.v #>> '{}' USING ERRCODE = 'foreign_key_violation';`,` END IF;`,` END LOOP;`].join(`
1
+ import{t as e}from"./multiline-EyzjEwn9.mjs";import{resolve as t}from"pathe";const n=new TextEncoder;function mapFieldTypeToPostgresType(e){switch(e){case`uuid`:return`uuid`;case`string`:case`enum`:return`text`;case`boolean`:case`bool`:return`boolean`;case`integer`:return`integer`;case`float`:return`double precision`;case`decimal`:return`numeric`;case`date`:return`date`;case`datetime`:return`timestamptz`;case`time`:return`time`;case`nested`:return`jsonb`;default:throw Error(`Field type "${e}" has no PostgreSQL column type.`)}}function identifier(e){return`"${e.replaceAll(`"`,`""`)}"`}function fnv1aHex(e){let t=2166136261;for(let r of n.encode(e))t=Math.imul(t^r,16777619)>>>0;return t.toString(16).padStart(8,`0`)}function derivedName(e,t,r){let i=`_${fnv1aHex(JSON.stringify([e,t,r]))}_${r}`,a=`${e}_${t}`;for(;n.encode(a+i).length>63;)a=a.slice(0,-1);return a+i}function derivedIdentifier(e,t,n){return identifier(derivedName(e,t,n))}function dollarQuoted(e){let t=`$fk$`;for(;e.includes(t);)t=`${t.slice(0,-1)}_$`;return`${t}\n${e}\n${t}`}function stringLiteral(e){return`'${e.replaceAll(`'`,`''`)}'`}function columnType(e){let t=e.type===`decimal`?`numeric(1000, ${e.scale??6})`:mapFieldTypeToPostgresType(e.type);return e.array&&e.type!==`nested`?`${t}[]`:t}function scalarLiteral(e,t,n){let r=mapFieldTypeToPostgresType(t.type);if(e instanceof Date){if(Number.isNaN(e.getTime()))throw Error(`Default of field ${n} is an invalid Date.`);return`${stringLiteral(e.toISOString())}::${r}`}switch(typeof e){case`string`:return r===`text`?stringLiteral(e):`${stringLiteral(e)}::${r}`;case`number`:if(!Number.isFinite(e))throw Error(`Default of field ${n} is not a finite number.`);return String(e);case`boolean`:return e?`TRUE`:`FALSE`;default:throw Error(`Default of field ${n} cannot be rendered as a SQL literal.`)}}const r=/* @__PURE__ */ new Map([[`datetime`,`now()`],[`date`,`CURRENT_DATE`],[`time`,`LOCALTIME`]]);function defaultExpression(e,t){let n=e.default,i=r.get(e.type);if(n===`now`&&i!==void 0)return i;if(e.array){if(!Array.isArray(n))throw Error(`Default of array field ${t} must be an array.`);let r=columnType(e);return n.length===0?`'{}'::${r}`:`ARRAY[${n.map(n=>scalarLiteral(n,e,t)).join(`, `)}]::${r}`}return scalarLiteral(n,e,t)}const i=`tailor_to_oct`,a={d:{render:e=>e,functions:[]},o:{render:e=>`${i}(${e})`,functions:[`CREATE OR REPLACE FUNCTION ${i}(n bigint) RETURNS text LANGUAGE sql IMMUTABLE AS ${dollarQuoted(`WITH RECURSIVE o(q, s) AS (
2
+ SELECT n / 8, (n % 8)::text
3
+ UNION ALL SELECT q / 8, (q % 8)::text || s FROM o WHERE q > 0
4
+ )
5
+ SELECT s FROM o WHERE q = 0`)}`]},x:{render:e=>`to_hex(${e})`,functions:[]},X:{render:e=>`upper(to_hex(${e}))`,functions:[]}};function isSerialConversion(e){return Object.hasOwn(a,e)}function parseSerialFormat(e,t){let n=/^(?<prefix>(?:%%|[^%])*)%(?<zero>0?)(?<width>\d*)(?<conversion>[a-zA-Z])(?<suffix>(?:%%|[^%])*)$/.exec(e)?.groups,r=n?.conversion;if(!n||r===void 0||!isSerialConversion(r))throw Error(`Serial format "${e}" of field ${t} is not supported; use a single %d, %o, %x, or %X specifier with an optional width (e.g. "INV-%05d"), and %% for a literal %.`);return{prefix:(n.prefix??``).replaceAll(`%%`,`%`),zeroPad:n.zero===`0`,width:n.width?Number(n.width):0,conversion:r,suffix:(n.suffix??``).replaceAll(`%%`,`%`)}}function sequenceName(e,t){return derivedIdentifier(e,t,`seq`)}function sequenceRange(e){let t=[`START WITH ${e.start}`,`MINVALUE ${e.start}`];return e.maxValue!==void 0&&t.push(`MAXVALUE ${e.maxValue}`),t.join(` `)}function serialStringDefault(e,t,n){let r=`nextval(${stringLiteral(e)})`;if(t===void 0)return{sql:`(${r}::text)`,functions:[]};let{prefix:i,width:o,zeroPad:s,conversion:c,suffix:l}=parseSerialFormat(t,n),{render:u,functions:d}=a[c],f=u(r),p=c===`d`?`${f}::text`:f;return o>0&&(p=`format('%${o}s', ${f})`,s&&(p=`translate(${p}, ' ', '0')`)),{sql:`(${[...i?[stringLiteral(i)]:[],p,...l?[stringLiteral(l)]:[]].join(` || `)})`,functions:d}}function columnDefinition(e,t,n){let r=identifier(t),i=`${identifier(e)}.${r}`,a=[r,columnType(n)];if(n.serial){if(n.type===`integer`)return a.push(`GENERATED BY DEFAULT AS IDENTITY (${sequenceRange(n.serial)})`),n.unique&&a.push(`UNIQUE`),{sql:a.join(` `),functions:[]};n.required&&a.push(`NOT NULL`),n.unique&&a.push(`UNIQUE`);let r=serialStringDefault(sequenceName(e,t),n.serial.format,i);return a.push(`DEFAULT ${r.sql}`),{sql:a.join(` `),functions:r.functions}}let o=n.default!==void 0,s=n.hooks?.create!==void 0||n.optionalOnCreate===!0;return n.required&&(o||!s)&&a.push(`NOT NULL`),n.unique&&a.push(`UNIQUE`),o&&a.push(`DEFAULT ${defaultExpression(n,i)}`),{sql:a.join(` `),functions:[]}}function jsonPathKey(e){return`"${e.replaceAll(`\\`,`\\\\`).replaceAll(`"`,`\\"`)}"`}function referencesWithin(e,t,n){let r=t.array?`${n}[*]`:n;return t.type===`nested`?Object.entries(t.fields??{}).flatMap(([t,n])=>referencesWithin(e,n,`${r}.${jsonPathKey(t)}`)):!t.foreignKey||t.foreignKeyType===void 0?[]:[{column:e,path:r,table:t.foreignKeyType,field:t.foreignKeyField??`id`,type:t.type}]}const o=/* @__PURE__ */ new Set([`integer`,`float`,`decimal`,`boolean`,`bool`,`uuid`]);function nestedUniqueMembers(e,t,n){return t.array?[]:t.type===`nested`?Object.entries(t.fields??{}).flatMap(([t,r])=>nestedUniqueMembers(e,r,[...n,t])):t.unique&&n.length>0?[{column:e,path:n,field:t}]:[]}function nestedUniqueIndex(e,t){let n=t.path.map(stringLiteral).join(`, `),r=`${identifier(t.column)} #>> ARRAY[${n}]`,i=o.has(t.field.type)?`CAST(${r} AS ${mapFieldTypeToPostgresType(t.field.type)})`:r;return`CREATE UNIQUE INDEX IF NOT EXISTS ${derivedIdentifier(e,`${t.column}.${t.path.join(`.`)}`,`nested_idx`)} ON ${identifier(e)} ((${i}))`}function tableReferences(e){return Object.entries(e.fields).filter(([e])=>e!==`id`).flatMap(([e,t])=>referencesWithin(e,t,`$`))}function isConstraintReference(e){return e.path===`$`}function referenceClause(e){return`REFERENCES ${identifier(e.table)} (${identifier(e.field)})`}function declaredType(e){return e===`bool`?`boolean`:e}function checkReference(e,t){let n=t.get(e.table);if(!n)return{problem:`references unknown table "${e.table}".`};let r=e.field===`id`?{type:`uuid`,unique:!0}:n.fields[e.field];return r?!r.unique||declaredType(r.type)!==declaredType(e.type)?{problem:`references "${e.table}"."${e.field}", which must be unique and of the same type as the referencing field.`}:{pgType:mapFieldTypeToPostgresType(r.type)}:{problem:`references unknown field "${e.field}" of table "${e.table}".`}}function referencedColumnType(e,t,n){let r=checkReference(e,t);if(`problem`in r)throw Error(`Field ${n} ${r.problem}`);return r.pgType}function withoutReference(e){let{foreignKey:t,foreignKeyType:n,foreignKeyField:r,...i}=e;return i}function withoutUnresolvableReference(e,t){return e.fields?{...e,fields:Object.fromEntries(Object.entries(e.fields).map(([e,n])=>[e,withoutUnresolvableReference(n,t)]))}:!e.foreignKey||e.foreignKeyType===void 0?e:`problem`in checkReference({column:``,path:`$`,table:e.foreignKeyType,field:e.foreignKeyField??`id`,type:e.type},t)?withoutReference(e):e}function dropUnresolvableReferences(e){let t=new Map(e.map(e=>[e.name,e]));return e.map(e=>({...e,fields:Object.fromEntries(Object.entries(e.fields).map(([e,n])=>[e,withoutUnresolvableReference(n,t)]))}))}function referenceCheck(e,t,n){let r=referencedColumnType(e,t,n),i=`violates foreign key constraints: % not found in ${`${identifier(e.table)}.${identifier(e.field)}`.replaceAll(`%`,`%%`)}`;return[` FOR v IN SELECT jsonb_path_query(to_jsonb(NEW.${identifier(e.column)}), ${stringLiteral(e.path)}) LOOP`,` IF jsonb_typeof(fk_check.v) <> 'null' AND NOT EXISTS (SELECT 1 FROM ${identifier(e.table)} AS parent WHERE parent.${identifier(e.field)} = (fk_check.v #>> '{}')::${r}) THEN`,` RAISE EXCEPTION ${stringLiteral(i)}, fk_check.v #>> '{}' USING ERRCODE = 'foreign_key_violation';`,` END IF;`,` END LOOP;`].join(`
2
6
  `)}function referenceTrigger(e,t,n){if(t.length===0)return[];let r=derivedIdentifier(e.name,`references`,`fk`);return[`CREATE OR REPLACE FUNCTION ${r}() RETURNS trigger LANGUAGE plpgsql AS ${dollarQuoted([`<<fk_check>>`,`DECLARE v jsonb;`,`BEGIN`,...t.map(t=>referenceCheck(t,n,`${e.name}.${t.column}`)),` RETURN NULL;`,`END`].join(`
3
- `))}`,`CREATE OR REPLACE TRIGGER ${r} AFTER INSERT OR UPDATE ON ${identifier(e.name)} FOR EACH ROW EXECUTE FUNCTION ${r}()`]}function incomingReferences(e,t){return[...t.values()].flatMap(n=>tableReferences(n).filter(t=>!isConstraintReference(t)&&t.table===e.name).flatMap(e=>{let r=checkReference(e,t);return`pgType`in r?[{...e,child:n.name,pgType:r.pgType}]:[]}))}function holdsParent(e){let t=`child.${identifier(e.column)}`,n=`OLD.${identifier(e.field)}`;return e.path===`$[*]`?`${n} = ANY(${t})`:`EXISTS (SELECT 1 FROM jsonb_path_query(to_jsonb(${t}), ${stringLiteral(e.path)}) AS held(v) WHERE CASE WHEN jsonb_typeof(held.v) = 'null' THEN false WHEN NOT pg_input_is_valid(held.v #>> '{}', ${stringLiteral(e.pgType)}) THEN false ELSE (held.v #>> '{}')::${e.pgType} = ${n} END)`}const o=`old_rows`;function holds(e,t){return`EXISTS (SELECT 1 FROM ${t} AS child WHERE ${holdsParent(e)})`}function refuseWhen(e,t,n){let r=`update or delete on table \`${e.name}\` violates foreign key constraint: some record is still referenced from table \`${t.child}\``;return[` IF ${n} THEN`,` RAISE EXCEPTION ${stringLiteral(r.replaceAll(`%`,`%%`))} USING ERRCODE = 'foreign_key_violation';`,` END IF;`].join(`
4
- `)}function referencedDeleteCheck(e,t){let n=holds(t,identifier(t.child));return refuseWhen(e,t,t.child===e.name?`${n} OR ${holds(t,o)}`:n)}function referencedUpdateCheck(e,t){let n=identifier(t.field);return refuseWhen(e,t,`NEW.${n} IS DISTINCT FROM OLD.${n} AND ${holds(t,identifier(t.child))}`)}function referencedTrigger(e,t){let n=incomingReferences(e,t);return n.length===0?[]:[[`referenced_delete`,`DELETE`,n.some(t=>t.child===e.name)?` REFERENCING OLD TABLE AS ${o}`:``,referencedDeleteCheck],[`referenced_update`,`UPDATE`,``,referencedUpdateCheck]].flatMap(([t,r,i,a])=>{let o=derivedIdentifier(e.name,t,`fk`);return[`CREATE OR REPLACE FUNCTION ${o}() RETURNS trigger LANGUAGE plpgsql AS ${dollarQuoted([`BEGIN`,...n.map(t=>a(e,t)),` RETURN NULL;`,`END`].join(`
5
- `))}`,`CREATE OR REPLACE TRIGGER ${o} AFTER ${r} ON ${identifier(e.name)}${i} FOR EACH ROW EXECUTE FUNCTION ${o}()`]})}function generateTableDDL(e,t={}){let n=identifier(e.name),r=new Map((t.tables??[e]).map(e=>[e.name,e])),i=[],a=[],o=[` "id" uuid PRIMARY KEY DEFAULT gen_random_uuid()`],s=tableReferences(e),c=new Map(s.filter(isConstraintReference).map(e=>[e.column,e]));for(let[r,s]of Object.entries(e.fields)){if(r===`id`)continue;if(s.serial&&s.type!==`integer`){let t=sequenceName(e.name,r);i.push(`CREATE SEQUENCE IF NOT EXISTS ${t} ${sequenceRange(s.serial)}`),a.push(`ALTER SEQUENCE ${t} OWNED BY ${n}.${identifier(r)}`)}let l=c.get(r),u=l&&!t.deferredReferences?.has(r)?` ${referenceClause(l)}`:``;o.push(` ${columnDefinition(e.name,r,s)}${u}`)}let l=[...Object.entries(e.indexes??{}).filter(([,e])=>e.unique).map(([t,r])=>`CREATE UNIQUE INDEX IF NOT EXISTS ${derivedIdentifier(e.name,t,`idx`)} ON ${n} (${r.fields.map(identifier).join(`, `)})`),...Object.entries(e.fields).filter(([e])=>e!==`id`).flatMap(([e,t])=>nestedUniqueMembers(e,t,[])).map(t=>nestedUniqueIndex(e.name,t))];for(let t of c.values())referencedColumnType(t,r,`${e.name}.${t.column}`);return[...i,`CREATE TABLE IF NOT EXISTS ${n} (\n${o.join(`,
6
- `)}\n)`,...a,...l,...referenceTrigger(e,s.filter(e=>!isConstraintReference(e)),r),...referencedTrigger(e,r)]}function addForeignKey(e,t){let n=derivedName(e.name,t.column,`fk`),r=identifier(e.name);return`DO ${dollarQuoted([`BEGIN`,`IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = ${stringLiteral(n)} AND conrelid = ${stringLiteral(r)}::regclass) THEN`,`ALTER TABLE ${r} ADD CONSTRAINT ${identifier(n)} FOREIGN KEY (${identifier(t.column)}) ${referenceClause(t)};`,`END IF;`,`END`].join(`
7
- `))}`}function planCreation(e){let t=new Set(e.map(e=>e.name)),n=/* @__PURE__ */ new Set,r=[...e],i=[],a=/* @__PURE__ */ new Map,pendingOf=e=>tableReferences(e).filter(isConstraintReference).filter(r=>t.has(r.table)&&r.table!==e.name&&!n.has(r.table));for(;r.length>0;){let e=r.findIndex(e=>pendingOf(e).length===0),[t]=r.splice(Math.max(e,0),1),o=pendingOf(t);o.length>0&&a.set(t,o),n.add(t.name),i.push(t)}return{ordered:i,deferred:a}}function generateSchemaDDL(e){let{ordered:t,deferred:n}=planCreation(e),r=t.map(t=>generateTableDDL(t,{tables:e,deferredReferences:new Set(n.get(t)?.map(e=>e.column))})),i=t.flatMap(e=>(n.get(e)??[]).map(t=>addForeignKey(e,t)));return[...r,i].filter(e=>e.length>0).map(e=>e.map(e=>`${e};`).join(`
7
+ `))}`,`CREATE OR REPLACE TRIGGER ${r} AFTER INSERT OR UPDATE ON ${identifier(e.name)} FOR EACH ROW EXECUTE FUNCTION ${r}()`]}function incomingReferences(e,t){return[...t.values()].flatMap(n=>tableReferences(n).filter(t=>!isConstraintReference(t)&&t.table===e.name).flatMap(e=>{let r=checkReference(e,t);return`pgType`in r?[{...e,child:n.name,pgType:r.pgType}]:[]}))}function holdsParent(e){let t=`child.${identifier(e.column)}`,n=`OLD.${identifier(e.field)}`;return e.path===`$[*]`?`${n} = ANY(${t})`:`EXISTS (SELECT 1 FROM jsonb_path_query(to_jsonb(${t}), ${stringLiteral(e.path)}) AS held(v) WHERE CASE WHEN jsonb_typeof(held.v) = 'null' THEN false WHEN NOT pg_input_is_valid(held.v #>> '{}', ${stringLiteral(e.pgType)}) THEN false ELSE (held.v #>> '{}')::${e.pgType} = ${n} END)`}const s=`old_rows`;function holds(e,t){return`EXISTS (SELECT 1 FROM ${t} AS child WHERE ${holdsParent(e)})`}function refuseWhen(e,t,n){let r=`update or delete on table \`${e.name}\` violates foreign key constraint: some record is still referenced from table \`${t.child}\``;return[` IF ${n} THEN`,` RAISE EXCEPTION ${stringLiteral(r.replaceAll(`%`,`%%`))} USING ERRCODE = 'foreign_key_violation';`,` END IF;`].join(`
8
+ `)}function referencedDeleteCheck(e,t){let n=holds(t,identifier(t.child));return refuseWhen(e,t,t.child===e.name?`${n} OR ${holds(t,s)}`:n)}function referencedUpdateCheck(e,t){let n=identifier(t.field);return refuseWhen(e,t,`NEW.${n} IS DISTINCT FROM OLD.${n} AND ${holds(t,identifier(t.child))}`)}function referencedTrigger(e,t){let n=incomingReferences(e,t);return n.length===0?[]:[[`referenced_delete`,`DELETE`,n.some(t=>t.child===e.name)?` REFERENCING OLD TABLE AS ${s}`:``,referencedDeleteCheck],[`referenced_update`,`UPDATE`,``,referencedUpdateCheck]].flatMap(([t,r,i,a])=>{let o=derivedIdentifier(e.name,t,`fk`);return[`CREATE OR REPLACE FUNCTION ${o}() RETURNS trigger LANGUAGE plpgsql AS ${dollarQuoted([`BEGIN`,...n.map(t=>a(e,t)),` RETURN NULL;`,`END`].join(`
9
+ `))}`,`CREATE OR REPLACE TRIGGER ${o} AFTER ${r} ON ${identifier(e.name)}${i} FOR EACH ROW EXECUTE FUNCTION ${o}()`]})}function generateTableDDL(e,t={}){let n=identifier(e.name),r=new Map((t.tables??[e]).map(e=>[e.name,e])),i=/* @__PURE__ */ new Set,a=[],o=[],s=[` "id" uuid PRIMARY KEY DEFAULT gen_random_uuid()`],c=tableReferences(e),l=new Map(c.filter(isConstraintReference).map(e=>[e.column,e]));for(let[r,c]of Object.entries(e.fields)){if(r===`id`)continue;if(c.serial&&c.type!==`integer`){let t=sequenceName(e.name,r);a.push(`CREATE SEQUENCE IF NOT EXISTS ${t} ${sequenceRange(c.serial)}`),o.push(`ALTER SEQUENCE ${t} OWNED BY ${n}.${identifier(r)}`)}let u=l.get(r),d=u&&!t.deferredReferences?.has(r)?` ${referenceClause(u)}`:``,f=columnDefinition(e.name,r,c);for(let e of f.functions)i.add(e);s.push(` ${f.sql}${d}`)}let u=[...Object.entries(e.indexes??{}).filter(([,e])=>e.unique).map(([t,r])=>`CREATE UNIQUE INDEX IF NOT EXISTS ${derivedIdentifier(e.name,t,`idx`)} ON ${n} (${r.fields.map(identifier).join(`, `)})`),...Object.entries(e.fields).filter(([e])=>e!==`id`).flatMap(([e,t])=>nestedUniqueMembers(e,t,[])).map(t=>nestedUniqueIndex(e.name,t))];for(let t of l.values())referencedColumnType(t,r,`${e.name}.${t.column}`);return{functions:[...i],statements:[...a,`CREATE TABLE IF NOT EXISTS ${n} (\n${s.join(`,
10
+ `)}\n)`,...o,...u,...referenceTrigger(e,c.filter(e=>!isConstraintReference(e)),r),...referencedTrigger(e,r)]}}function addForeignKey(e,t){let n=derivedName(e.name,t.column,`fk`),r=identifier(e.name);return`DO ${dollarQuoted([`BEGIN`,`IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = ${stringLiteral(n)} AND conrelid = ${stringLiteral(r)}::regclass) THEN`,`ALTER TABLE ${r} ADD CONSTRAINT ${identifier(n)} FOREIGN KEY (${identifier(t.column)}) ${referenceClause(t)};`,`END IF;`,`END`].join(`
11
+ `))}`}function planCreation(e){let t=new Set(e.map(e=>e.name)),n=/* @__PURE__ */ new Set,r=[...e],i=[],a=/* @__PURE__ */ new Map,pendingOf=e=>tableReferences(e).filter(isConstraintReference).filter(r=>t.has(r.table)&&r.table!==e.name&&!n.has(r.table));for(;r.length>0;){let e=r.findIndex(e=>pendingOf(e).length===0),[t]=r.splice(Math.max(e,0),1),o=pendingOf(t);o.length>0&&a.set(t,o),n.add(t.name),i.push(t)}return{ordered:i,deferred:a}}function generateSchemaDDL(e){let{ordered:t,deferred:n}=planCreation(e),r=t.map(t=>generateTableDDL(t,{tables:e,deferredReferences:new Set(n.get(t)?.map(e=>e.column))})),i=[...new Set(r.flatMap(e=>e.functions))],a=t.flatMap(e=>(n.get(e)??[]).map(t=>addForeignKey(e,t)));return[i,...r.map(e=>e.statements),a].filter(e=>e.length>0).map(e=>e.map(e=>`${e};`).join(`
8
12
  `)).join(`
9
13
 
10
14
  `)}function templateLiteral(e){return`\`${e.replaceAll(`\\`,`\\\\`).replaceAll("`","\\`").replaceAll("${","\\${").replaceAll(`\r`,`\\r`)}\``}function generatePgliteSchemaModule(e,t){let n=e.map(({namespace:e,tables:t})=>` ${JSON.stringify(e)}: ${templateLiteral(generateSchemaDDL(t))},`);return[`/**`,` * Auto-generated PGlite schema for TailorDB tables.`," * Create a namespace's tables in a test with `pglite.exec(pgliteSchema[namespace])`.",` *`,` * DO NOT EDIT - This file is auto-generated by ${t.generatedBy}.`,` */`,``,`export const pgliteSchema = {`,...n,`} as const;`,``].join(`
11
- `)}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 generatePgliteSchemaModule(e.map(({namespace:e,tables:t})=>({namespace:e,tables:toDDLTables(t)})),{generatedBy:`the kysely-type plugin`})}function mapFieldTypeToColumnType(e,t=!1){switch(e){case`uuid`:case`string`:case`decimal`:return`string`;case`integer`:case`float`:return`number`;case`date`:return t?`TemporalDate`:`Timestamp`;case`datetime`:return t?`TemporalInstant`:`Timestamp`;case`time`:return t?`TemporalTime`:`string`;case`bool`:case`boolean`:return`boolean`;case`enum`:case`nested`:throw Error(`Field type "${e}" has no scalar column type; resolve it before mapping.`);default:return`string`}}const s=/* @__PURE__ */ new Map([[`Timestamp`,{select:`Date`,write:`Date | string`}],[`TemporalDate`,{select:`Temporal.PlainDate`,write:`Temporal.PlainDate | string`}],[`TemporalInstant`,{select:`Temporal.Instant`,write:`Temporal.Instant | string`}],[`TemporalTime`,{select:`Temporal.PlainTime`,write:`Temporal.PlainTime | string`}]]);function emptyUsedUtilityTypes(){return{Timestamp:!1,TemporalDate:!1,TemporalInstant:!1,TemporalTime:!1,Serial:!1,ObjectColumnType:!1,ArrayColumnType:!1}}function mergeUsedUtilityTypes(e,t){return{Timestamp:e.Timestamp||t.Timestamp,TemporalDate:e.TemporalDate||t.TemporalDate,TemporalInstant:e.TemporalInstant||t.TemporalInstant,TemporalTime:e.TemporalTime||t.TemporalTime,Serial:e.Serial||t.Serial,ObjectColumnType:e.ObjectColumnType||t.ObjectColumnType,ArrayColumnType:e.ArrayColumnType||t.ArrayColumnType}}function usesColumnTypeAlias(e){return e.Timestamp||e.TemporalDate||e.TemporalInstant||e.TemporalTime}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,t){let n=e.fields;if(!n||typeof n!=`object`)return{type:`string`,usedUtilityTypes:emptyUsedUtilityTypes()};let r=Object.entries(n).map(([e,n])=>{let r=generateFieldType(n,t,!0);return{fieldType:`${e}${n.required===!0?``:`?`}: ${r.type}`,usedUtilityTypes:r.usedUtilityTypes}}),i=r.reduce((e,t)=>mergeUsedUtilityTypes(e,t.usedUtilityTypes),emptyUsedUtilityTypes()),a=r.map(e=>e.fieldType),o=`{\n ${a.join(`;
12
- `)}${a.length>0?`;`:``}\n}`,s=Object.values(n).some(e=>e.required!==!0),c=Object.values(n).some(e=>e.hooks?.create||e.default!==void 0||e.optionalOnCreate===!0);return usesColumnTypeAlias(i)||s||c?{type:`ObjectColumnType<${o}>`,usedUtilityTypes:{...i,ObjectColumnType:!0}}:{type:o,usedUtilityTypes:i}}function getBaseType(e,t,n){let r=e.type,i=emptyUsedUtilityTypes();if(r===`enum`)return{type:getEnumType(e),usedUtilityTypes:i};if(r===`nested`)return getNestedType(e,t);let a=mapFieldTypeToColumnType(r,t&&!(n&&r===`time`));switch(a){case`Timestamp`:i.Timestamp=!0;break;case`TemporalDate`:i.TemporalDate=!0;break;case`TemporalInstant`:i.TemporalInstant=!0;break;case`TemporalTime`:i.TemporalTime=!0}return{type:a,usedUtilityTypes:i}}function generateFieldType(e,t,n=!1){let r=getBaseType(e,t,n),i={...r.usedUtilityTypes},a=e.array===!0,o=e.required!==!0,c=s.has(r.type),l=r.type;return a&&(c||l.startsWith(`ObjectColumnType<`)?(l=`ArrayColumnType<${r.type}>`,i.ArrayColumnType=!0):l=e.type===`enum`?`(${r.type})[]`:`${r.type}[]`),o&&(l=`${l} | null`),e.serial&&(i.Serial=!0,l=`Serial<${l}>`),(e.hooks?.create||e.default!==void 0||e.optionalOnCreate===!0)&&(l=`Generated<${l}>`),{type:l,usedUtilityTypes:i}}function generateTableInterface(t,n,r){let i=Object.entries(n).filter(([e])=>e!==`id`).map(([e,t])=>({fieldName:e,...generateFieldType(t,r)})),a=[`id: Generated<string>;`,...i.map(e=>`${e.fieldName}: ${e.type};`)],o=i.reduce((e,t)=>mergeUsedUtilityTypes(e,t.usedUtilityTypes),emptyUsedUtilityTypes());return{typeDef:e`
15
+ `)}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 generatePgliteSchemaModule(e.map(({namespace:e,tables:t})=>({namespace:e,tables:toDDLTables(t)})),{generatedBy:`the kysely-type plugin`})}function mapFieldTypeToColumnType(e,t=!1){switch(e){case`uuid`:case`string`:case`decimal`:return`string`;case`integer`:case`float`:return`number`;case`date`:return t?`TemporalDate`:`Timestamp`;case`datetime`:return t?`TemporalInstant`:`Timestamp`;case`time`:return t?`TemporalTime`:`string`;case`bool`:case`boolean`:return`boolean`;case`enum`:case`nested`:throw Error(`Field type "${e}" has no scalar column type; resolve it before mapping.`);default:return`string`}}const c=/* @__PURE__ */ new Map([[`Timestamp`,{select:`Date`,write:`Date | string`}],[`TemporalDate`,{select:`Temporal.PlainDate`,write:`Temporal.PlainDate | string`}],[`TemporalInstant`,{select:`Temporal.Instant`,write:`Temporal.Instant | string`}],[`TemporalTime`,{select:`Temporal.PlainTime`,write:`Temporal.PlainTime | string`}]]);function emptyUsedUtilityTypes(){return{Timestamp:!1,TemporalDate:!1,TemporalInstant:!1,TemporalTime:!1,Serial:!1,ObjectColumnType:!1,ArrayColumnType:!1}}function mergeUsedUtilityTypes(e,t){return{Timestamp:e.Timestamp||t.Timestamp,TemporalDate:e.TemporalDate||t.TemporalDate,TemporalInstant:e.TemporalInstant||t.TemporalInstant,TemporalTime:e.TemporalTime||t.TemporalTime,Serial:e.Serial||t.Serial,ObjectColumnType:e.ObjectColumnType||t.ObjectColumnType,ArrayColumnType:e.ArrayColumnType||t.ArrayColumnType}}function usesColumnTypeAlias(e){return e.Timestamp||e.TemporalDate||e.TemporalInstant||e.TemporalTime}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,t){let n=e.fields;if(!n||typeof n!=`object`)return{type:`string`,usedUtilityTypes:emptyUsedUtilityTypes()};let r=Object.entries(n).map(([e,n])=>{let r=generateFieldType(n,t,!0);return{fieldType:`${e}${n.required===!0?``:`?`}: ${r.type}`,usedUtilityTypes:r.usedUtilityTypes}}),i=r.reduce((e,t)=>mergeUsedUtilityTypes(e,t.usedUtilityTypes),emptyUsedUtilityTypes()),a=r.map(e=>e.fieldType),o=`{\n ${a.join(`;
16
+ `)}${a.length>0?`;`:``}\n}`,s=Object.values(n).some(e=>e.required!==!0),c=Object.values(n).some(e=>e.hooks?.create||e.default!==void 0||e.optionalOnCreate===!0);return usesColumnTypeAlias(i)||s||c?{type:`ObjectColumnType<${o}>`,usedUtilityTypes:{...i,ObjectColumnType:!0}}:{type:o,usedUtilityTypes:i}}function getBaseType(e,t,n){let r=e.type,i=emptyUsedUtilityTypes();if(r===`enum`)return{type:getEnumType(e),usedUtilityTypes:i};if(r===`nested`)return getNestedType(e,t);let a=mapFieldTypeToColumnType(r,t&&!(n&&r===`time`));switch(a){case`Timestamp`:i.Timestamp=!0;break;case`TemporalDate`:i.TemporalDate=!0;break;case`TemporalInstant`:i.TemporalInstant=!0;break;case`TemporalTime`:i.TemporalTime=!0}return{type:a,usedUtilityTypes:i}}function generateFieldType(e,t,n=!1){let r=getBaseType(e,t,n),i={...r.usedUtilityTypes},a=e.array===!0,o=e.required!==!0,s=c.has(r.type),l=r.type;return a&&(s||l.startsWith(`ObjectColumnType<`)?(l=`ArrayColumnType<${r.type}>`,i.ArrayColumnType=!0):l=e.type===`enum`?`(${r.type})[]`:`${r.type}[]`),o&&(l=`${l} | null`),e.serial&&(i.Serial=!0,l=`Serial<${l}>`),(e.hooks?.create||e.default!==void 0||e.optionalOnCreate===!0)&&(l=`Generated<${l}>`),{type:l,usedUtilityTypes:i}}function generateTableInterface(t,n,r){let i=Object.entries(n).filter(([e])=>e!==`id`).map(([e,t])=>({fieldName:e,...generateFieldType(t,r)})),a=[`id: Generated<string>;`,...i.map(e=>`${e.fieldName}: ${e.type};`)],o=i.reduce((e,t)=>mergeUsedUtilityTypes(e,t.usedUtilityTypes),emptyUsedUtilityTypes());return{typeDef:e`
13
17
  ${t}: {
14
18
  ${a.join(`
15
19
  `)}
@@ -49,5 +53,5 @@ import{t as e}from"./multiline-EyzjEwn9.mjs";import{resolve as t}from"pathe";con
49
53
  `].join(`
50
54
 
51
55
  `)+`
52
- `}const c=`@tailor-platform/kysely-type`,l=`./generated/tailordb.ts`;function kyselyTypePlugin(e){return{id:c,description:`Generates Kysely type definitions for TailorDB tables`,pluginConfig:e,async onTailorDBReady(e){let{distPath:n,pgliteSchemaPath:r,temporal:i}=e.pluginConfig;if(r&&t(n)===t(r))throw Error(`distPath and pgliteSchemaPath must resolve to different files.`);let a=[];for(let t of e.tailordb){let e=[];for(let n of Object.values(t.tables)){let t=await processKyselyType(n,i);e.push(t)}e.length!==0&&a.push({namespace:t.namespace,types:e})}let o=[];if(a.length>0){let t=generateUnifiedKyselyTypes(a,i);o.push({path:e.pluginConfig.distPath,content:t}),e.pluginConfig.pgliteSchemaPath&&o.push({path:e.pluginConfig.pgliteSchemaPath,content:generatePGliteSchemaModule(e.tailordb.filter(e=>Object.keys(e.tables).length>0))})}return{files:o}}}}export{processKyselyFields as a,dropUnresolvableReferences as c,generateUnifiedKyselyTypes as i,generatePgliteSchemaModule as l,c as n,s as o,kyselyTypePlugin as r,mapFieldTypeToColumnType as s,l as t,withoutReference as u};
53
- //# sourceMappingURL=kysely-type-DVL90_oX.mjs.map
56
+ `}const l=`@tailor-platform/kysely-type`,u=`./generated/tailordb.ts`;function kyselyTypePlugin(e){return{id:l,description:`Generates Kysely type definitions for TailorDB tables`,pluginConfig:e,async onTailorDBReady(e){let{distPath:n,pgliteSchemaPath:r,temporal:i}=e.pluginConfig;if(r&&t(n)===t(r))throw Error(`distPath and pgliteSchemaPath must resolve to different files.`);let a=[];for(let t of e.tailordb){let e=[];for(let n of Object.values(t.tables)){let t=await processKyselyType(n,i);e.push(t)}e.length!==0&&a.push({namespace:t.namespace,types:e})}let o=[];if(a.length>0){let t=generateUnifiedKyselyTypes(a,i);o.push({path:e.pluginConfig.distPath,content:t}),e.pluginConfig.pgliteSchemaPath&&o.push({path:e.pluginConfig.pgliteSchemaPath,content:generatePGliteSchemaModule(e.tailordb.filter(e=>Object.keys(e.tables).length>0))})}return{files:o}}}}export{processKyselyFields as a,dropUnresolvableReferences as c,generateUnifiedKyselyTypes as i,generatePgliteSchemaModule as l,l as n,c as o,kyselyTypePlugin as r,mapFieldTypeToColumnType as s,u as t,withoutReference as u};
57
+ //# sourceMappingURL=kysely-type-DhAZqdQg.mjs.map