@tailor-platform/sdk 1.28.0 → 1.29.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +18 -0
- package/dist/{application-CBJFUKrU.mjs → application-Clwpv84E.mjs} +9 -5
- package/dist/application-Clwpv84E.mjs.map +1 -0
- package/dist/{application-WyZetOky.mjs → application-Dl1d7w-b.mjs} +3 -3
- package/dist/chunk-DEt8GZDa.mjs +8 -0
- package/dist/cli/index.mjs +54 -19
- package/dist/cli/index.mjs.map +1 -1
- package/dist/cli/lib.mjs +5 -5
- package/dist/cli/skills.mjs +1 -1
- package/dist/client-CW4Oh3iz.mjs +6 -0
- package/dist/client-CZmQBXAY.mjs +16294 -0
- package/dist/client-CZmQBXAY.mjs.map +1 -0
- package/dist/configure/index.mjs +1 -1
- package/dist/{crash-report-Cot_9Esm.mjs → crash-report-CYrETw1c.mjs} +2 -2
- package/dist/{crash-report-Ju8cQF-l.mjs → crash-report-DizNMVnm.mjs} +3 -3
- package/dist/{crash-report-Ju8cQF-l.mjs.map → crash-report-DizNMVnm.mjs.map} +1 -1
- package/dist/{interceptor-B0d_GrI5.mjs → interceptor-DgQNmwWJ.mjs} +2 -2
- package/dist/{interceptor-B0d_GrI5.mjs.map → interceptor-DgQNmwWJ.mjs.map} +1 -1
- package/dist/kysely/index.mjs +1 -1
- package/dist/{package-json-DHfTiUCS.mjs → package-json-DiZWrkIA.mjs} +1 -1
- package/dist/plugin/builtin/enum-constants/index.mjs +1 -1
- package/dist/plugin/builtin/file-utils/index.mjs +1 -1
- package/dist/plugin/builtin/kysely-type/index.mjs +1 -1
- package/dist/plugin/builtin/seed/index.mjs +1 -1
- package/dist/plugin/index.mjs +1 -1
- package/dist/{query-WYq8RvYp.mjs → query-B1-hq2Hm.mjs} +69 -27
- package/dist/query-B1-hq2Hm.mjs.map +1 -0
- package/dist/seed/index.mjs +1 -1
- package/dist/{telemetry-VvNfsyEE.mjs → telemetry-BSUlYTs-.mjs} +2 -2
- package/dist/{telemetry-VvNfsyEE.mjs.map → telemetry-BSUlYTs-.mjs.map} +1 -1
- package/dist/telemetry-BtN2l0f1.mjs +4 -0
- package/dist/utils/test/index.mjs +1 -1
- package/docs/cli/user.md +21 -22
- package/docs/cli/workspace.md +0 -7
- package/docs/cli-reference.md +12 -10
- package/docs/services/executor.md +46 -0
- package/package.json +8 -8
- package/dist/application-CBJFUKrU.mjs.map +0 -1
- package/dist/chunk-Cz-A8uMR.mjs +0 -3
- package/dist/client-C2_wgujH.mjs +0 -6
- package/dist/client-bTbnbQbB.mjs +0 -957
- package/dist/client-bTbnbQbB.mjs.map +0 -1
- package/dist/query-WYq8RvYp.mjs.map +0 -1
- package/dist/telemetry-BevrwWwF.mjs +0 -4
package/dist/configure/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import "../chunk-
|
|
1
|
+
import "../chunk-DEt8GZDa.mjs";
|
|
2
2
|
import { i as t$1, n as unsafeAllowAllGqlPermission, r as unsafeAllowAllTypePermission, t as db } from "../schema-BePzTFBV.mjs";
|
|
3
3
|
import { t as brandValue } from "../brand-GZnI4eYb.mjs";
|
|
4
4
|
import { n as createWorkflowJob, t as WORKFLOW_TEST_ENV_KEY } from "../job-DdfW7vH3.mjs";
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import "./chunk-
|
|
1
|
+
import "./chunk-DEt8GZDa.mjs";
|
|
2
2
|
import "./logger-CqezTedh.mjs";
|
|
3
3
|
import "./package-json-D3x2nBPB.mjs";
|
|
4
|
-
import { n as reportCrash, t as initCrashReporting } from "./crash-report-
|
|
4
|
+
import { n as reportCrash, t as initCrashReporting } from "./crash-report-DizNMVnm.mjs";
|
|
5
5
|
|
|
6
6
|
export { reportCrash };
|
|
@@ -2,10 +2,10 @@ import { n as logger } from "./logger-CqezTedh.mjs";
|
|
|
2
2
|
import { t as readPackageJson } from "./package-json-D3x2nBPB.mjs";
|
|
3
3
|
import * as fs from "node:fs";
|
|
4
4
|
import * as path from "pathe";
|
|
5
|
+
import * as crypto from "node:crypto";
|
|
5
6
|
import * as os from "node:os";
|
|
6
7
|
import { parseYAML } from "confbox";
|
|
7
8
|
import { xdgConfig } from "xdg-basedir";
|
|
8
|
-
import * as crypto from "node:crypto";
|
|
9
9
|
import { isCI } from "std-env";
|
|
10
10
|
|
|
11
11
|
//#region src/cli/crash-report/config.ts
|
|
@@ -385,7 +385,7 @@ async function reportCrash(error, errorType) {
|
|
|
385
385
|
].join("\n"));
|
|
386
386
|
}
|
|
387
387
|
if (config.remoteEnabled) {
|
|
388
|
-
const { userAgent } = await import("./client-
|
|
388
|
+
const { userAgent } = await import("./client-CW4Oh3iz.mjs");
|
|
389
389
|
await sendCrashReport(report, await userAgent());
|
|
390
390
|
}
|
|
391
391
|
} catch {}
|
|
@@ -411,4 +411,4 @@ function initCrashReporting() {
|
|
|
411
411
|
|
|
412
412
|
//#endregion
|
|
413
413
|
export { JSON_FOOTER_MARKER as a, CRASH_LOG_EXTENSION as i, reportCrash as n, parseCrashReportConfig as o, sendCrashReport as r, initCrashReporting as t };
|
|
414
|
-
//# sourceMappingURL=crash-report-
|
|
414
|
+
//# sourceMappingURL=crash-report-DizNMVnm.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"crash-report-Ju8cQF-l.mjs","names":[],"sources":["../src/cli/crash-report/config.ts","../src/cli/crash-report/writer.ts","../src/cli/crash-report/sender.ts","../src/cli/crash-report/sanitize.ts","../src/cli/crash-report/report.ts","../src/cli/crash-report/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 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 .sort()\n .reverse();\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 fs.mkdirSync(dir, { recursive: true });\n\n const filename = generateFilename(report);\n const filePath = path.join(dir, filename);\n const content = formatCrashReport(report);\n\n fs.writeFileSync(filePath, content, \"utf-8\");\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 { 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.\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(parseCommand()),\n argv: sanitizeArgv(process.argv),\n errorName,\n errorMessage: sanitizeMessage(rawMessage),\n stackTrace: sanitizeStackTrace(rawStack),\n errorType,\n userId: currentUser,\n userEmail: currentUser,\n };\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 email, or null if unavailable\n */\nfunction readCurrentUser(): string | 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 { current_user?: string | null };\n return raw?.current_user ?? null;\n } catch {\n return null;\n }\n}\n","import { logger } from \"@/cli/shared/logger\";\nimport { readPackageJson } from \"@/cli/shared/package-json\";\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-sdk crash-report send --file \"${filePath}\"`,\n ].join(\"\\n\"),\n );\n }\n }\n\n if (config.remoteEnabled) {\n // Lazy import: client.ts pulls in heavy dependencies (OAuth2, Connect, Protobuf)\n // that should not be loaded on the startup critical path via initCrashReporting().\n const { userAgent } = await import(\"@/cli/shared/client\");\n const ua = await userAgent();\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":";;;;;;;;;;;;;;;;;;AAiBA,SAAgB,yBAA4C;AAC1D,KAAI,KACF,QAAO;EACL,cAAc;EACd,eAAe;EACf,UAAU;EACX;CAGH,MAAM,gBAAgB,QAAQ,IAAI,8BAA8B,MAAM,aAAa,KAAK;CACxF,MAAM,iBAAiB,QAAQ,IAAI,+BAA+B,OAAO,aAAa,KAAK;CAC3F,MAAM,WAAW,YAAY,KAAK,KAAK,WAAW,mBAAmB,gBAAgB,GAAG;AAExF,QAAO;EACL,cAAc,gBAAgB,aAAa;EAC3C;EACA;EACD;;;;;AC9BH,MAAM,kBAAkB;;AAGxB,MAAa,qBAAqB;;AAGlC,MAAa,sBAAsB;;;;;;AAOnC,SAAgB,kBAAkB,QAA6B;AA2B7D,QA1Bc;EACZ,iBAAiB,OAAO;EACxB,cA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B,CAAC,OAAO,cAAe;EAKnD,MAAM,SAAS,iBAAiB;GAAE;GAAO,aAHrB,MAAM,iBAAiB,EACZ,WAAW;GAEW;GAAW,CAAC;AAEjE,MAAI,OAAO,cAAc;GACvB,MAAM,WAAW,iBAAiB,QAAQ,OAAO,SAAS;AAC1D,OAAI,SACF,QAAO,IACL;IACE;IACA;IACA,KAAK;IACL;IACA;IACA,0CAA0C,SAAS;IACpD,CAAC,KAAK,KAAK,CACb;;AAIL,MAAI,OAAO,eAAe;GAGxB,MAAM,EAAE,cAAc,MAAM,OAAO;AAEnC,SAAM,gBAAgB,QADX,MAAM,WAAW,CACK;;SAE7B;;;;;;;AAUV,SAAgB,qBAA2B;CACzC,MAAM,SAAS,wBAAwB;AACvC,KAAI,CAAC,OAAO,gBAAgB,CAAC,OAAO,cAAe;CAEnD,MAAM,eAAe,OAAgB,cAAyB;EAC5D,MAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;AACtE,SAAO,MAAM,QAAQ;AACrB,EAAK,YAAY,OAAO,UAAU,CAAC,cAAc;AAC/C,WAAQ,KAAK,EAAE;IACf;;AAGJ,SAAQ,GAAG,sBAAsB,UAAU,YAAY,OAAO,oBAAoB,CAAC;AACnF,SAAQ,GAAG,uBAAuB,WAAW,YAAY,QAAQ,qBAAqB,CAAC"}
|
|
1
|
+
{"version":3,"file":"crash-report-DizNMVnm.mjs","names":[],"sources":["../src/cli/crash-report/config.ts","../src/cli/crash-report/writer.ts","../src/cli/crash-report/sender.ts","../src/cli/crash-report/sanitize.ts","../src/cli/crash-report/report.ts","../src/cli/crash-report/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 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 .sort()\n .reverse();\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 fs.mkdirSync(dir, { recursive: true });\n\n const filename = generateFilename(report);\n const filePath = path.join(dir, filename);\n const content = formatCrashReport(report);\n\n fs.writeFileSync(filePath, content, \"utf-8\");\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 { 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.\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(parseCommand()),\n argv: sanitizeArgv(process.argv),\n errorName,\n errorMessage: sanitizeMessage(rawMessage),\n stackTrace: sanitizeStackTrace(rawStack),\n errorType,\n userId: currentUser,\n userEmail: currentUser,\n };\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 email, or null if unavailable\n */\nfunction readCurrentUser(): string | 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 { current_user?: string | null };\n return raw?.current_user ?? null;\n } catch {\n return null;\n }\n}\n","import { logger } from \"@/cli/shared/logger\";\nimport { readPackageJson } from \"@/cli/shared/package-json\";\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-sdk crash-report send --file \"${filePath}\"`,\n ].join(\"\\n\"),\n );\n }\n }\n\n if (config.remoteEnabled) {\n // Lazy import: client.ts pulls in heavy dependencies (OAuth2, Connect, Protobuf)\n // that should not be loaded on the startup critical path via initCrashReporting().\n const { userAgent } = await import(\"@/cli/shared/client\");\n const ua = await userAgent();\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":";;;;;;;;;;;;;;;;;;AAiBA,SAAgB,yBAA4C;AAC1D,KAAI,KACF,QAAO;EACL,cAAc;EACd,eAAe;EACf,UAAU;EACX;CAGH,MAAM,gBAAgB,QAAQ,IAAI,8BAA8B,MAAM,aAAa,KAAK;CACxF,MAAM,iBAAiB,QAAQ,IAAI,+BAA+B,OAAO,aAAa,KAAK;CAC3F,MAAM,WAAW,YAAY,KAAK,KAAK,WAAW,mBAAmB,gBAAgB,GAAG;AAExF,QAAO;EACL,cAAc,gBAAgB,aAAa;EAC3C;EACA;EACD;;;;;AC9BH,MAAM,kBAAkB;;AAGxB,MAAa,qBAAqB;;AAGlC,MAAa,sBAAsB;;;;;;AAOnC,SAAgB,kBAAkB,QAA6B;AA2B7D,QA1B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;AACvC,MAAI,CAAC,OAAO,gBAAgB,CAAC,OAAO,cAAe;EAKnD,MAAM,SAAS,iBAAiB;GAAE;GAAO,aAHrB,MAAM,iBAAiB,EACZ,WAAW;GAEW;GAAW,CAAC;AAEjE,MAAI,OAAO,cAAc;GACvB,MAAM,WAAW,iBAAiB,QAAQ,OAAO,SAAS;AAC1D,OAAI,SACF,QAAO,IACL;IACE;IACA;IACA,KAAK;IACL;IACA;IACA,0CAA0C,SAAS;IACpD,CAAC,KAAK,KAAK,CACb;;AAIL,MAAI,OAAO,eAAe;GAGxB,MAAM,EAAE,cAAc,MAAM,OAAO;AAEnC,SAAM,gBAAgB,QADX,MAAM,WAAW,CACK;;SAE7B;;;;;;;AAUV,SAAgB,qBAA2B;CACzC,MAAM,SAAS,wBAAwB;AACvC,KAAI,CAAC,OAAO,gBAAgB,CAAC,OAAO,cAAe;CAEnD,MAAM,eAAe,OAAgB,cAAyB;EAC5D,MAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;AACtE,SAAO,MAAM,QAAQ;AACrB,EAAK,YAAY,OAAO,UAAU,CAAC,cAAc;AAC/C,WAAQ,KAAK,EAAE;IACf;;AAGJ,SAAQ,GAAG,sBAAsB,UAAU,YAAY,OAAO,oBAAoB,CAAC;AACnF,SAAQ,GAAG,uBAAuB,WAAW,YAAY,QAAQ,qBAAqB,CAAC"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import "./chunk-
|
|
1
|
+
import "./chunk-DEt8GZDa.mjs";
|
|
2
2
|
import { SpanStatusCode, trace } from "@opentelemetry/api";
|
|
3
3
|
|
|
4
4
|
//#region src/cli/telemetry/interceptor.ts
|
|
@@ -31,4 +31,4 @@ function createTracingInterceptor() {
|
|
|
31
31
|
|
|
32
32
|
//#endregion
|
|
33
33
|
export { createTracingInterceptor };
|
|
34
|
-
//# sourceMappingURL=interceptor-
|
|
34
|
+
//# sourceMappingURL=interceptor-DgQNmwWJ.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"interceptor-
|
|
1
|
+
{"version":3,"file":"interceptor-DgQNmwWJ.mjs","names":[],"sources":["../src/cli/telemetry/interceptor.ts"],"sourcesContent":["import { trace, SpanStatusCode } from \"@opentelemetry/api\";\nimport type { Interceptor } from \"@connectrpc/connect\";\n\n/**\n * Create a Connect-RPC interceptor that records OTLP spans for each RPC call.\n * When no TracerProvider is registered, the OTel API automatically provides\n * noop spans with zero overhead.\n * @returns Tracing interceptor\n */\nexport function createTracingInterceptor(): Interceptor {\n return (next) => async (req) => {\n const tracer = trace.getTracer(\"tailor-sdk\");\n\n return tracer.startActiveSpan(`rpc.${req.method.name}`, async (span) => {\n span.setAttribute(\"rpc.method\", req.method.name);\n span.setAttribute(\"rpc.service\", \"OperatorService\");\n span.setAttribute(\"rpc.system\", \"connect-rpc\");\n\n try {\n const response = await next(req);\n span.setStatus({ code: SpanStatusCode.OK });\n return response;\n } catch (error) {\n span.setStatus({ code: SpanStatusCode.ERROR });\n if (error instanceof Error) {\n span.recordException(error);\n }\n throw error;\n } finally {\n span.end();\n }\n });\n };\n}\n"],"mappings":";;;;;;;;;;AASA,SAAgB,2BAAwC;AACtD,SAAQ,SAAS,OAAO,QAAQ;AAG9B,SAFe,MAAM,UAAU,aAAa,CAE9B,gBAAgB,OAAO,IAAI,OAAO,QAAQ,OAAO,SAAS;AACtE,QAAK,aAAa,cAAc,IAAI,OAAO,KAAK;AAChD,QAAK,aAAa,eAAe,kBAAkB;AACnD,QAAK,aAAa,cAAc,cAAc;AAE9C,OAAI;IACF,MAAM,WAAW,MAAM,KAAK,IAAI;AAChC,SAAK,UAAU,EAAE,MAAM,eAAe,IAAI,CAAC;AAC3C,WAAO;YACA,OAAO;AACd,SAAK,UAAU,EAAE,MAAM,eAAe,OAAO,CAAC;AAC9C,QAAI,iBAAiB,MACnB,MAAK,gBAAgB,MAAM;AAE7B,UAAM;aACE;AACR,SAAK,KAAK;;IAEZ"}
|
package/dist/kysely/index.mjs
CHANGED
package/dist/plugin/index.mjs
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { t as db } from "./schema-BePzTFBV.mjs";
|
|
2
2
|
import { i as symbols, n as logger, r as styles, t as CIPromptError } from "./logger-CqezTedh.mjs";
|
|
3
|
-
import { A as
|
|
3
|
+
import { A as AuthHookPoint, B as TenantProviderConfig_TenantProviderType, C as PipelineResolver_OperationType, D as ExecutorJobStatus, F as AuthSCIMAttribute_Mutability, G as FilterSchema, H as GetApplicationSchemaHealthResponse_ApplicationSchemaHealthStatus, I as AuthSCIMAttribute_Type, J as Subgraph_ServiceType, K as PageDirection, L as AuthSCIMAttribute_Uniqueness, M as AuthInvokerSchema, N as AuthOAuth2Client_ClientType, O as ExecutorTargetType, P as AuthOAuth2Client_GrantType, R as AuthSCIMConfig_AuthorizationType, S as TailorDBType_PermitAction, T as FunctionExecution_Status, U as ConditionSchema, V as UserProfileProviderConfig_UserProfileProviderType, W as Condition_Operator, _ as TailorDBGQLPermission_Action, b as TailorDBType_Permission_Operator, d as platformBaseUrl, f as resolveStaticWebsiteUrls, g as WorkflowJobExecution_Status, h as WorkflowExecution_Status, i as fetchMachineUserToken, j as AuthIDPConfig_AuthType, k as ExecutorTriggerType, l as initOperatorClient, m as WorkspacePlatformUserRole, p as userAgent, q as ApplicationSchemaUpdateAttemptStatus, r as fetchAll, v as TailorDBGQLPermission_Operator, w as IdPLang, x as TailorDBType_Permission_Permit, y as TailorDBGQLPermission_Permit } from "./client-CZmQBXAY.mjs";
|
|
4
4
|
import { t as readPackageJson } from "./package-json-D3x2nBPB.mjs";
|
|
5
|
-
import { S as writePlatformConfig, _ as hashFile, a as loadConfig, b as loadWorkspaceId, d as TailorDBTypeSchema, f as stringifyFunction, g as getDistDir, h as createBundleCache, l as OAuth2ClientSchema, m as loadFilesWithIgnores, n as generatePluginFilesIfNeeded, p as tailorUserMap, r as loadApplication, s as createExecutorService, t as defineApplication, x as readPlatformConfig, y as loadAccessToken } from "./application-
|
|
6
|
-
import { r as withSpan } from "./telemetry-
|
|
5
|
+
import { S as writePlatformConfig, _ as hashFile, a as loadConfig, b as loadWorkspaceId, d as TailorDBTypeSchema, f as stringifyFunction, g as getDistDir, h as createBundleCache, l as OAuth2ClientSchema, m as loadFilesWithIgnores, n as generatePluginFilesIfNeeded, p as tailorUserMap, r as loadApplication, s as createExecutorService, t as defineApplication, x as readPlatformConfig, y as loadAccessToken } from "./application-Clwpv84E.mjs";
|
|
6
|
+
import { r as withSpan } from "./telemetry-BSUlYTs-.mjs";
|
|
7
7
|
import { arg, createDefineCommand, defineCommand, runCommand } from "politty";
|
|
8
8
|
import { z } from "zod";
|
|
9
9
|
import * as fs$1 from "node:fs";
|
|
@@ -15,20 +15,20 @@ import { formatDistanceToNowStrict } from "date-fns";
|
|
|
15
15
|
import { getBorderCharacters, table } from "table";
|
|
16
16
|
import { ValueSchema, timestampDate } from "@bufbuild/protobuf/wkt";
|
|
17
17
|
import { Code, ConnectError } from "@connectrpc/connect";
|
|
18
|
+
import * as crypto from "node:crypto";
|
|
19
|
+
import { createHash } from "node:crypto";
|
|
20
|
+
import { pathToFileURL } from "node:url";
|
|
18
21
|
import { resolveTSConfig } from "pkg-types";
|
|
19
22
|
import { tmpdir } from "node:os";
|
|
20
23
|
import { findUpSync } from "find-up-simple";
|
|
21
24
|
import ml from "multiline-ts";
|
|
22
|
-
import * as crypto from "node:crypto";
|
|
23
|
-
import { createHash } from "node:crypto";
|
|
24
25
|
import * as rolldown from "rolldown";
|
|
25
26
|
import * as fs from "node:fs/promises";
|
|
26
27
|
import { glob } from "node:fs/promises";
|
|
27
|
-
import { pathToFileURL } from "node:url";
|
|
28
28
|
import * as inflection from "inflection";
|
|
29
29
|
import { create, fromJson, toJson } from "@bufbuild/protobuf";
|
|
30
30
|
import { ExitPromptError } from "@inquirer/core";
|
|
31
|
-
import { confirm, input } from "@inquirer/prompts";
|
|
31
|
+
import { confirm, input, password } from "@inquirer/prompts";
|
|
32
32
|
import { isCI } from "std-env";
|
|
33
33
|
import ora from "ora";
|
|
34
34
|
import { setTimeout as setTimeout$1 } from "timers/promises";
|
|
@@ -2622,7 +2622,8 @@ function withGuard(fn) {
|
|
|
2622
2622
|
}
|
|
2623
2623
|
const prompt = {
|
|
2624
2624
|
confirm: withGuard(confirm),
|
|
2625
|
-
text: withGuard(input)
|
|
2625
|
+
text: withGuard(input),
|
|
2626
|
+
password: withGuard(password)
|
|
2626
2627
|
};
|
|
2627
2628
|
|
|
2628
2629
|
//#endregion
|
|
@@ -2850,7 +2851,7 @@ async function planExecutor(context) {
|
|
|
2850
2851
|
name: executor.name,
|
|
2851
2852
|
request: {
|
|
2852
2853
|
workspaceId,
|
|
2853
|
-
executor: protoExecutor(application
|
|
2854
|
+
executor: protoExecutor(application, executor)
|
|
2854
2855
|
},
|
|
2855
2856
|
metaRequest
|
|
2856
2857
|
});
|
|
@@ -2859,7 +2860,7 @@ async function planExecutor(context) {
|
|
|
2859
2860
|
name: executor.name,
|
|
2860
2861
|
request: {
|
|
2861
2862
|
workspaceId,
|
|
2862
|
-
executor: protoExecutor(application
|
|
2863
|
+
executor: protoExecutor(application, executor)
|
|
2863
2864
|
},
|
|
2864
2865
|
metaRequest
|
|
2865
2866
|
});
|
|
@@ -2883,7 +2884,26 @@ async function planExecutor(context) {
|
|
|
2883
2884
|
resourceOwners
|
|
2884
2885
|
};
|
|
2885
2886
|
}
|
|
2886
|
-
function
|
|
2887
|
+
function resolveTailorDBNamespace(application, typeName) {
|
|
2888
|
+
for (const service of application.tailorDBServices) if (service.types[typeName]) return service.namespace;
|
|
2889
|
+
throw new Error(`TailorDB type "${typeName}" not found in any namespace. Available namespaces: ${application.tailorDBServices.map((s) => s.namespace).join(", ")}`);
|
|
2890
|
+
}
|
|
2891
|
+
function resolveResolverNamespace(application, resolverName) {
|
|
2892
|
+
for (const service of application.resolverServices) if (Object.values(service.resolvers).some((r) => r.name === resolverName)) return service.namespace;
|
|
2893
|
+
throw new Error(`Resolver "${resolverName}" not found in any namespace. Available namespaces: ${application.resolverServices.map((s) => s.namespace).join(", ")}`);
|
|
2894
|
+
}
|
|
2895
|
+
function resolveIdpNamespace(application) {
|
|
2896
|
+
if (application.idpServices.length === 0) throw new Error("No IdP service configured");
|
|
2897
|
+
if (application.idpServices.length > 1) throw new Error("Multiple IdP services found; cannot determine which to use for executor trigger");
|
|
2898
|
+
return application.idpServices[0].name;
|
|
2899
|
+
}
|
|
2900
|
+
function resolveAuthNamespace(application) {
|
|
2901
|
+
if (!application.authService) throw new Error("No Auth service configured");
|
|
2902
|
+
return application.authService.parsedConfig.name;
|
|
2903
|
+
}
|
|
2904
|
+
function protoExecutor(application, executor) {
|
|
2905
|
+
const appName = application.name;
|
|
2906
|
+
const env = application.env;
|
|
2887
2907
|
const trigger = executor.trigger;
|
|
2888
2908
|
let triggerType;
|
|
2889
2909
|
let triggerConfig;
|
|
@@ -2900,6 +2920,12 @@ function protoExecutor(appName, executor, env) {
|
|
|
2900
2920
|
authAccessTokenRefreshed: "auth.access_token.refreshed",
|
|
2901
2921
|
authAccessTokenRevoked: "auth.access_token.revoked"
|
|
2902
2922
|
};
|
|
2923
|
+
function typedEventTrigger(typedConfig) {
|
|
2924
|
+
return { config: {
|
|
2925
|
+
case: "event",
|
|
2926
|
+
value: { typedConfig }
|
|
2927
|
+
} };
|
|
2928
|
+
}
|
|
2903
2929
|
switch (trigger.kind) {
|
|
2904
2930
|
case "schedule":
|
|
2905
2931
|
triggerType = ExecutorTriggerType.SCHEDULE;
|
|
@@ -2915,23 +2941,27 @@ function protoExecutor(appName, executor, env) {
|
|
|
2915
2941
|
case "recordUpdated":
|
|
2916
2942
|
case "recordDeleted":
|
|
2917
2943
|
triggerType = ExecutorTriggerType.EVENT;
|
|
2918
|
-
triggerConfig = {
|
|
2919
|
-
case: "
|
|
2944
|
+
triggerConfig = typedEventTrigger({
|
|
2945
|
+
case: "tailordb",
|
|
2920
2946
|
value: {
|
|
2921
|
-
|
|
2922
|
-
|
|
2947
|
+
eventTypes: [eventType[trigger.kind]],
|
|
2948
|
+
namespaceName: resolveTailorDBNamespace(application, trigger.typeName),
|
|
2949
|
+
typeName: trigger.typeName,
|
|
2950
|
+
...trigger.condition ? { condition: { expr: `(${stringifyFunction(trigger.condition)})(${argsExpr})` } } : {}
|
|
2923
2951
|
}
|
|
2924
|
-
}
|
|
2952
|
+
});
|
|
2925
2953
|
break;
|
|
2926
2954
|
case "resolverExecuted":
|
|
2927
2955
|
triggerType = ExecutorTriggerType.EVENT;
|
|
2928
|
-
triggerConfig = {
|
|
2929
|
-
case: "
|
|
2956
|
+
triggerConfig = typedEventTrigger({
|
|
2957
|
+
case: "pipeline",
|
|
2930
2958
|
value: {
|
|
2931
|
-
|
|
2932
|
-
|
|
2959
|
+
eventTypes: [eventType[trigger.kind]],
|
|
2960
|
+
namespaceName: resolveResolverNamespace(application, trigger.resolverName),
|
|
2961
|
+
resolverName: trigger.resolverName,
|
|
2962
|
+
...trigger.condition ? { condition: { expr: `(${stringifyFunction(trigger.condition)})(${argsExpr})` } } : {}
|
|
2933
2963
|
}
|
|
2934
|
-
}
|
|
2964
|
+
});
|
|
2935
2965
|
break;
|
|
2936
2966
|
case "incomingWebhook":
|
|
2937
2967
|
triggerType = ExecutorTriggerType.INCOMING_WEBHOOK;
|
|
@@ -2943,14 +2973,26 @@ function protoExecutor(appName, executor, env) {
|
|
|
2943
2973
|
case "idpUserCreated":
|
|
2944
2974
|
case "idpUserUpdated":
|
|
2945
2975
|
case "idpUserDeleted":
|
|
2976
|
+
triggerType = ExecutorTriggerType.EVENT;
|
|
2977
|
+
triggerConfig = typedEventTrigger({
|
|
2978
|
+
case: "idp",
|
|
2979
|
+
value: {
|
|
2980
|
+
eventTypes: [eventType[trigger.kind]],
|
|
2981
|
+
namespaceName: resolveIdpNamespace(application)
|
|
2982
|
+
}
|
|
2983
|
+
});
|
|
2984
|
+
break;
|
|
2946
2985
|
case "authAccessTokenIssued":
|
|
2947
2986
|
case "authAccessTokenRefreshed":
|
|
2948
2987
|
case "authAccessTokenRevoked":
|
|
2949
2988
|
triggerType = ExecutorTriggerType.EVENT;
|
|
2950
|
-
triggerConfig = {
|
|
2951
|
-
case: "
|
|
2952
|
-
value: {
|
|
2953
|
-
|
|
2989
|
+
triggerConfig = typedEventTrigger({
|
|
2990
|
+
case: "auth",
|
|
2991
|
+
value: {
|
|
2992
|
+
eventTypes: [eventType[trigger.kind]],
|
|
2993
|
+
namespaceName: resolveAuthNamespace(application)
|
|
2994
|
+
}
|
|
2995
|
+
});
|
|
2954
2996
|
break;
|
|
2955
2997
|
default: throw new Error(`Unknown trigger: ${trigger}`);
|
|
2956
2998
|
}
|
|
@@ -10425,7 +10467,7 @@ async function generate(options) {
|
|
|
10425
10467
|
if (options.init) await handleInitOption(namespacesWithMigrations, options.yes);
|
|
10426
10468
|
let pluginManager;
|
|
10427
10469
|
if (plugins.length > 0) pluginManager = new PluginManager(plugins);
|
|
10428
|
-
const { defineApplication } = await import("./application-
|
|
10470
|
+
const { defineApplication } = await import("./application-Dl1d7w-b.mjs");
|
|
10429
10471
|
const application = defineApplication({
|
|
10430
10472
|
config,
|
|
10431
10473
|
pluginManager
|
|
@@ -12604,4 +12646,4 @@ function printGqlResult(result, options = {}) {
|
|
|
12604
12646
|
|
|
12605
12647
|
//#endregion
|
|
12606
12648
|
export { listExecutors as $, workspaceArgs as $t, truncate as A, getLatestMigrationNumber as At, listOAuth2Clients as B, hasChanges as Bt, listCommand$2 as C, INITIAL_SCHEMA_NUMBER as Ct, resumeWorkflow as D, compareSnapshots as Dt, resumeCommand as E, compareLocalTypesWithSnapshot as Et, showCommand as F, isValidMigrationNumber as Ft, listCommand$5 as G, generateUserTypes as Gt, getOAuth2Client as H, prompt as Ht, logBetaWarning as I, loadDiff as It, listWebhookExecutors as J, defineAppCommand as Jt, listMachineUsers as K, apiCall as Kt, remove as L, reconstructSnapshotFromMigrations as Lt, generate as M, getMigrationFilePath as Mt, generateCommand as N, getMigrationFiles as Nt, listCommand$3 as O, createSnapshotFromLocalTypes as Ot, show as P, getNextMigrationNumber as Pt, listCommand$6 as Q, isVerbose as Qt, removeCommand$1 as R, formatDiffSummary as Rt, listApps as S, DIFF_FILE_NAME as St, healthCommand as T, SCHEMA_FILE_NAME as Tt, getMachineUserToken as U, sdkNameLabelKey as Ut, getCommand$1 as V, getNamespacesWithMigrations as Vt, tokenCommand as W, trnPrefix as Wt, triggerCommand as X, confirmationArgs as Xt, webhookCommand as Y, commonArgs as Yt, triggerExecutor as Z, deploymentArgs as Zt, getWorkspace as _, waitForExecution$1 as _t, updateUser as a, startWorkflow as at, createCommand as b, bundleMigrationScript as bt, listCommand as c, executionsCommand as ct, inviteUser as d, functionExecutionStatusToString as dt, getExecutorJob as et, restoreCommand as f, formatKeyValueTable as ft, getCommand as g, executeScript as gt, listWorkspaces as h, apply as ht, updateCommand as i, startCommand as it, truncateCommand as j, getMigrationDirPath as jt, listWorkflows as k, formatMigrationNumber as kt, listUsers as l, getWorkflowExecution as lt, listCommand$1 as m, getExecutor as mt, queryCommand as n, listExecutorJobs as nt, removeCommand as o, getCommand$2 as ot, restoreWorkspace as p, getCommand$3 as pt, generate$1 as q, apiCommand as qt, isCLIError as r, watchExecutorJob as rt, removeUser as s, getWorkflow as st, query as t, jobsCommand as tt, inviteCommand as u, listWorkflowExecutions as ut, deleteCommand as v, MIGRATION_LABEL_KEY as vt, getAppHealth as w, MIGRATE_FILE_NAME as wt, createWorkspace as x, DB_TYPES_FILE_NAME as xt, deleteWorkspace as y, parseMigrationLabelNumber as yt, listCommand$4 as z, formatMigrationDiff as zt };
|
|
12607
|
-
//# sourceMappingURL=query-
|
|
12649
|
+
//# sourceMappingURL=query-B1-hq2Hm.mjs.map
|