@tailor-platform/sdk 1.58.0 → 1.60.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 +65 -0
- package/dist/{application-B59TaTk_.mjs → application-FnWOxBk7.mjs} +46 -27
- package/dist/application-FnWOxBk7.mjs.map +1 -0
- package/dist/application-VOdgMtOD.mjs +4 -0
- package/dist/{authconnection-TsdLYaLs.d.mts → authconnection-BIYzEh2p.d.mts} +2 -2
- package/dist/authconnection-D8SJGMpj.mjs.map +1 -1
- package/dist/cli/erd-viewer-assets/app.js +4 -4
- package/dist/cli/index.mjs +57 -13
- package/dist/cli/index.mjs.map +1 -1
- package/dist/cli/lib.mjs +4 -3
- package/dist/cli/lib.mjs.map +1 -1
- package/dist/client-B-jRdlC_.mjs +4 -0
- package/dist/{client-62B-r3MN.mjs → client-W5P4NYYX.mjs} +117 -4
- package/dist/{client-62B-r3MN.mjs.map → client-W5P4NYYX.mjs.map} +1 -1
- package/dist/configure/index.d.mts +1 -1
- package/dist/configure/index.mjs +8 -8
- package/dist/configure/index.mjs.map +1 -1
- package/dist/{crashreport-CCGpLUlP.mjs → crashreport-D3DvAzdg.mjs} +3 -3
- package/dist/crashreport-D3DvAzdg.mjs.map +1 -0
- package/dist/{crashreport-CXD_Kjk-.mjs → crashreport-lnVTnbB5.mjs} +1 -1
- package/dist/file-B58Dm-2P.mjs.map +1 -1
- package/dist/{file-VTJbbOL3.d.mts → file-BzK8z3X-.d.mts} +2 -2
- package/dist/globals-ByrCoDip.mjs +109 -0
- package/dist/globals-ByrCoDip.mjs.map +1 -0
- package/dist/iconv-DreIffeM.mjs.map +1 -1
- package/dist/{iconv-Chu6Hit2.d.mts → iconv-kwrmd1U_.d.mts} +2 -2
- package/dist/{idp-Di9N4FSJ.d.mts → idp-BlBPtXJ-.d.mts} +2 -2
- package/dist/idp-Ch95ag8h.mjs.map +1 -1
- package/dist/{index-BWoHfE-i.d.mts → index-Cr6ufjZ5.d.mts} +10 -8
- package/dist/{index-DTSQthwF.d.mts → index-DRhMpdnA.d.mts} +7 -7
- package/dist/{job-CEAJLiGp.mjs → job-BpsFXPbi.mjs} +8 -17
- package/dist/job-BpsFXPbi.mjs.map +1 -0
- package/dist/mock-Dpu__UeJ.mjs +805 -0
- package/dist/mock-Dpu__UeJ.mjs.map +1 -0
- package/dist/registry-D0uB0OrK.mjs +178 -0
- package/dist/registry-D0uB0OrK.mjs.map +1 -0
- package/dist/{repl-editor-ihh8koiR.mjs → repl-editor-Y9QJDL0K.mjs} +3 -9
- package/dist/{repl-editor-ihh8koiR.mjs.map → repl-editor-Y9QJDL0K.mjs.map} +1 -1
- package/dist/runtime/authconnection.d.mts +1 -1
- package/dist/runtime/file.d.mts +1 -1
- package/dist/runtime/globals.d.mts +5 -5
- package/dist/runtime/iconv.d.mts +1 -1
- package/dist/runtime/idp.d.mts +1 -1
- package/dist/runtime/index.d.mts +7 -7
- package/dist/runtime/secretmanager.d.mts +1 -1
- package/dist/runtime/workflow.d.mts +1 -1
- package/dist/{runtime-BC-FbQkg.mjs → runtime-CrUa8Z2k.mjs} +238 -273
- package/dist/runtime-CrUa8Z2k.mjs.map +1 -0
- package/dist/secretmanager-B9h-U_8U.mjs.map +1 -1
- package/dist/{secretmanager-BhpDmxwT.d.mts → secretmanager-CKLB3wAQ.d.mts} +2 -2
- package/dist/utils/test/index.d.mts +5 -5
- package/dist/utils/test/index.mjs +7 -7
- package/dist/utils/test/index.mjs.map +1 -1
- package/dist/vitest/environment.mjs +3 -4
- package/dist/vitest/environment.mjs.map +1 -1
- package/dist/vitest/index.d.mts +167 -120
- package/dist/vitest/index.mjs +6 -6
- package/dist/vitest/index.mjs.map +1 -1
- package/dist/vitest/setup.d.mts +1 -1
- package/dist/vitest/setup.mjs +4 -3
- package/dist/vitest/setup.mjs.map +1 -1
- package/dist/workflow--aPbA8Uq.mjs.map +1 -1
- package/dist/{workflow-dYYH7QFa.d.mts → workflow-CMamswkK.d.mts} +2 -2
- package/docs/cli/auth.md +40 -0
- package/docs/cli-reference.md +1 -0
- package/docs/configuration.md +1 -1
- package/docs/runtime.md +9 -12
- package/docs/services/auth.md +19 -1
- package/docs/testing.md +92 -85
- package/package.json +5 -5
- package/dist/application-B59TaTk_.mjs.map +0 -1
- package/dist/application-gO_pa5BO.mjs +0 -4
- package/dist/client-BWl3f1XS.mjs +0 -4
- package/dist/crashreport-CCGpLUlP.mjs.map +0 -1
- package/dist/job-CEAJLiGp.mjs.map +0 -1
- package/dist/mock-B6PI49C_.mjs +0 -844
- package/dist/mock-B6PI49C_.mjs.map +0 -1
- package/dist/runtime-BC-FbQkg.mjs.map +0 -1
- package/dist/test-env-key-CSnK4W1Y.mjs +0 -30
- package/dist/test-env-key-CSnK4W1Y.mjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"crashreport-D3DvAzdg.mjs","names":[],"sources":["../src/cli/crashreport/config.ts","../src/cli/crashreport/writer.ts","../src/cli/crashreport/sender.ts","../src/cli/crashreport/sanitize.ts","../src/cli/crashreport/report.ts","../src/cli/crashreport/index.ts"],"sourcesContent":["import * as path from \"pathe\";\nimport { isCI } from \"std-env\";\nimport { xdgConfig } from \"xdg-basedir\";\n\nexport interface CrashReportConfig {\n readonly localEnabled: boolean;\n readonly remoteEnabled: boolean;\n readonly localDir: string;\n}\n\n/**\n * Parse crash report configuration from environment variables.\n * Local crash log writing is enabled by default (opt-out via TAILOR_CRASH_REPORTS_LOCAL=off).\n * Remote sending is disabled by default (opt-in via TAILOR_CRASH_REPORTS_REMOTE=on).\n * Both are auto-disabled in CI environments.\n * @returns Crash report configuration\n */\nexport function parseCrashReportConfig(): CrashReportConfig {\n if (isCI) {\n return {\n localEnabled: false,\n remoteEnabled: false,\n localDir: \"\",\n };\n }\n\n const localEnabled = (process.env.TAILOR_CRASH_REPORTS_LOCAL ?? \"on\").toLowerCase() !== \"off\";\n const remoteEnabled = (process.env.TAILOR_CRASH_REPORTS_REMOTE ?? \"off\").toLowerCase() === \"on\";\n const localDir = xdgConfig ? path.join(xdgConfig, \"tailor-platform\", \"crash-reports\") : \"\";\n\n return {\n localEnabled: localEnabled && localDir !== \"\",\n remoteEnabled,\n localDir,\n };\n}\n","import * as fs from \"node:fs\";\nimport * as path from \"pathe\";\nimport { ensureSecretDir, writeSecretFile } from \"@/cli/shared/secret-file\";\nimport type { CrashReport } from \"./report\";\n\nconst MAX_CRASH_FILES = 10;\n\n/** Marker line that separates human-readable content from the JSON footer. */\nexport const JSON_FOOTER_MARKER = \"--- JSON ---\";\n\n/** File extension for crash log files. */\nexport const CRASH_LOG_EXTENSION = \".crash.log\";\n\n/**\n * Format a CrashReport as human-readable text for local crash log files.\n * @param report - Crash report to format\n * @returns Formatted text content\n */\nexport function formatCrashReport(report: CrashReport): string {\n const lines = [\n `Crash Report: ${report.id}`,\n `Timestamp: ${report.timestamp}`,\n `Error Type: ${report.errorType}`,\n \"\",\n \"--- Environment ---\",\n `SDK Version: ${report.sdkVersion}`,\n `Node Version: ${report.nodeVersion}`,\n `OS: ${report.osPlatform} ${report.osRelease}`,\n `Arch: ${report.arch}`,\n \"\",\n \"--- Command ---\",\n `Command: ${report.command}`,\n `Arguments: ${JSON.stringify(report.argv)}`,\n \"\",\n \"--- Error ---\",\n `Name: ${report.errorName}`,\n `Message: ${report.errorMessage}`,\n \"\",\n \"--- Stack Trace ---\",\n report.stackTrace || \"(no stack trace available)\",\n \"\",\n JSON_FOOTER_MARKER,\n JSON.stringify(report),\n \"\",\n ];\n return lines.join(\"\\n\");\n}\n\n/**\n * Generate a filename for a crash log file.\n * Format: {timestamp}-{shortId}.crash.log\n * @param report - Crash report to generate filename for\n * @returns Filename string\n */\nfunction generateFilename(report: CrashReport): string {\n const safeTimestamp = report.timestamp.replace(/[:.]/g, \"-\");\n const shortId = report.id.slice(0, 8);\n return `${safeTimestamp}-${shortId}${CRASH_LOG_EXTENSION}`;\n}\n\n/**\n * Remove old crash log files, keeping only the most recent ones.\n * @param dir - Crash log directory\n */\nfunction cleanupOldFiles(dir: string): void {\n try {\n const files = fs\n .readdirSync(dir)\n .filter((f) => f.endsWith(CRASH_LOG_EXTENSION))\n .toSorted()\n .toReversed();\n\n for (const file of files.slice(MAX_CRASH_FILES)) {\n fs.unlinkSync(path.join(dir, file));\n }\n } catch {\n // Best-effort cleanup, ignore errors\n }\n}\n\n/**\n * Write a crash report to a local file.\n * Creates the directory if it doesn't exist. Keeps only the last 10 crash files.\n * Never throws - returns the file path on success or undefined on failure.\n * @param report - Crash report to write\n * @param dir - Directory to write the crash log file to\n * @returns File path on success, undefined on failure\n */\nexport function writeCrashReport(report: CrashReport, dir: string): string | undefined {\n try {\n ensureSecretDir(dir);\n\n const filename = generateFilename(report);\n const filePath = path.join(dir, filename);\n const content = formatCrashReport(report);\n\n writeSecretFile(filePath, content);\n cleanupOldFiles(dir);\n\n return filePath;\n } catch {\n return undefined;\n }\n}\n","import type { CrashReport } from \"./report\";\n\nconst SEND_TIMEOUT_MS = 5000;\nconst PRODUCTION_ENDPOINT = \"https://sdk-error-tracking-926vh9t4cl.erp.dev/query\";\n\nconst SUBMIT_MUTATION = `\nmutation SubmitCrashReport(\n $id: String!\n $timestamp: String!\n $sdkVersion: String!\n $nodeVersion: String!\n $osPlatform: String!\n $osRelease: String!\n $arch: String!\n $command: String!\n $argv: [String]\n $errorName: String!\n $errorMessage: String!\n $stackTrace: String\n $errorType: String!\n $userId: String\n $userEmail: String\n) {\n submitCrashReport(\n id: $id\n timestamp: $timestamp\n sdkVersion: $sdkVersion\n nodeVersion: $nodeVersion\n osPlatform: $osPlatform\n osRelease: $osRelease\n arch: $arch\n command: $command\n argv: $argv\n errorName: $errorName\n errorMessage: $errorMessage\n stackTrace: $stackTrace\n errorType: $errorType\n userId: $userId\n userEmail: $userEmail\n ) {\n success\n }\n}`;\n\n/**\n * Send a crash report to the remote endpoint via GraphQL mutation.\n * Best-effort: never throws, returns boolean success.\n * @param report - Crash report to send\n * @param ua - User-Agent header value\n * @returns true if the request succeeded, false otherwise\n */\nexport async function sendCrashReport(report: CrashReport, ua: string): Promise<boolean> {\n try {\n const endpoint = process.env.TAILOR_CRASH_REPORT_ENDPOINT || PRODUCTION_ENDPOINT;\n const response = await fetch(endpoint, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"User-Agent\": ua,\n },\n body: JSON.stringify({\n query: SUBMIT_MUTATION,\n variables: report,\n }),\n signal: AbortSignal.timeout(SEND_TIMEOUT_MS),\n });\n\n if (!response.ok) return false;\n\n const data = (await response.json()) as {\n errors?: unknown[];\n data?: { submitCrashReport: { success: boolean } };\n };\n if (data.errors?.length) return false;\n return data.data?.submitCrashReport.success === true;\n } catch {\n return false;\n }\n}\n","import * as os from \"node:os\";\n\nconst HOME_DIR = os.homedir();\n\n// Patterns for sanitization (global variants for use with .replace())\nconst UUID_PATTERN = /\\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\\b/gi;\nconst LONG_HEX_PATTERN = /\\b[0-9a-fA-F]{32,}\\b/g;\nconst EMAIL_PATTERN = /\\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}\\b/g;\nconst ABSOLUTE_PATH_PATTERN = /(?:\\/(?:[\\w.@\\- ]+\\/)+[\\w.@\\- ]+)/g;\nconst WINDOWS_PATH_PATTERN = /(?:[A-Za-z]:\\\\(?:[\\w.@\\- ]+\\\\)+[\\w.@\\- ]+)/g;\nconst URL_QUERY_PATTERN = /[?&][^?\\s]*/g;\n\n// Non-global variants for single-match .test() calls (avoids lastIndex state issues)\nconst EMAIL_TEST_PATTERN = /\\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}\\b/;\nconst WINDOWS_DRIVE_TEST_PATTERN = /^[A-Za-z]:\\\\/;\n\n// SDK package path marker for relative paths\nconst SDK_PACKAGE_MARKER = \"packages/sdk/\";\n\nfunction lastSegment(filePath: string, separator: string): string {\n return filePath.split(separator).pop() ?? filePath;\n}\n\n/**\n * Sanitize a stack trace by replacing absolute paths with relative SDK paths.\n * External paths are replaced with `<external>/filename.ext`.\n * Home directories are replaced with `~/<redacted>/`.\n * @param stack - Raw stack trace string\n * @returns Sanitized stack trace\n */\nexport function sanitizeStackTrace(stack: string): string {\n // V8 stack traces start with \"ErrorType: message\\n at ...\".\n // The error message may span multiple lines before the first \" at \" frame.\n // Apply message sanitization to all message lines so secrets embedded in\n // multiline error messages are redacted consistently with errorMessage.\n const firstFrameIndex = stack.search(/\\n\\s+at /);\n let result: string;\n if (firstFrameIndex !== -1) {\n result = sanitizeMessage(stack.slice(0, firstFrameIndex)) + stack.slice(firstFrameIndex);\n } else {\n result = sanitizeMessage(stack);\n }\n\n result = result.replace(ABSOLUTE_PATH_PATTERN, (match) => {\n const sdkIndex = match.indexOf(SDK_PACKAGE_MARKER);\n if (sdkIndex !== -1) {\n return match.slice(sdkIndex);\n }\n\n if (match.startsWith(HOME_DIR)) {\n return `~/<redacted>/${lastSegment(match, \"/\")}`;\n }\n\n return `<external>/${lastSegment(match, \"/\")}`;\n });\n result = result.replace(WINDOWS_PATH_PATTERN, (match) => {\n const normalized = match.replace(/\\\\/g, \"/\");\n const sdkIndex = normalized.indexOf(SDK_PACKAGE_MARKER);\n if (sdkIndex !== -1) {\n return normalized.slice(sdkIndex);\n }\n return `<external>/${lastSegment(match, \"\\\\\")}`;\n });\n return result;\n}\n\n/**\n * Sanitize an error message by redacting sensitive information.\n * Redacts: UUIDs, long hex tokens, email addresses, absolute paths, URL query strings.\n * @param message - Raw error message\n * @returns Sanitized error message\n */\nexport function sanitizeMessage(message: string): string {\n let result = message;\n // Strip serialized request/response bodies that may contain secrets\n result = result.replace(/\\nRequest:\\s*[\\s\\S]*$/, \"\\nRequest: <redacted>\");\n result = result.replace(UUID_PATTERN, \"<uuid>\");\n result = result.replace(LONG_HEX_PATTERN, \"<redacted>\");\n result = result.replace(EMAIL_PATTERN, \"<email>\");\n result = result.replace(URL_QUERY_PATTERN, \"?<redacted>\");\n result = result.replace(ABSOLUTE_PATH_PATTERN, (match) => `<path>/${lastSegment(match, \"/\")}`);\n result = result.replace(WINDOWS_PATH_PATTERN, (match) => `<path>/${lastSegment(match, \"\\\\\")}`);\n\n return result;\n}\n\n/**\n * Sanitize process.argv by keeping command/subcommand names and redacting\n * values of sensitive flags.\n * @param argv - Raw process.argv array\n * @returns Sanitized argv array\n */\nexport function sanitizeArgv(argv: string[]): string[] {\n const result: string[] = [];\n let redactNext = false;\n\n for (const arg of argv) {\n if (redactNext) {\n // If the next token is itself a flag, treat it as a new flag rather\n // than consuming it as the previous flag's value. This avoids leaking\n // the *next* flag's value (e.g., `--verbose --workspace-id secret`\n // would otherwise expose `secret`).\n if (!arg.startsWith(\"-\")) {\n result.push(\"<redacted>\");\n redactNext = false;\n continue;\n }\n redactNext = false;\n }\n\n if (arg.startsWith(\"-\")) {\n // --flag=value: keep flag name, redact value\n const eqIndex = arg.indexOf(\"=\");\n if (eqIndex !== -1) {\n result.push(`${arg.slice(0, eqIndex)}=<redacted>`);\n continue;\n }\n\n // --flag / -f: keep flag name, redact next arg as its value\n result.push(arg);\n redactNext = true;\n continue;\n }\n\n // Redact absolute paths\n if (arg.startsWith(\"/\") && arg.includes(\"/\", 1)) {\n result.push(\"<path>\");\n continue;\n }\n\n // Redact Windows-style absolute paths\n if (WINDOWS_DRIVE_TEST_PATTERN.test(arg)) {\n result.push(\"<path>\");\n continue;\n }\n\n // Redact email addresses\n if (EMAIL_TEST_PATTERN.test(arg)) {\n result.push(\"<email>\");\n continue;\n }\n\n result.push(arg);\n }\n\n return result;\n}\n","import * as crypto from \"node:crypto\";\nimport * as fs from \"node:fs\";\nimport * as os from \"node:os\";\nimport { parseYAML } from \"confbox\";\nimport * as path from \"pathe\";\nimport { xdgConfig } from \"xdg-basedir\";\nimport { 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 crashreport 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;CAC1D,IAAI,MACF,OAAO;EACL,cAAc;EACd,eAAe;EACf,UAAU;CACZ;CAGF,MAAM,gBAAgB,QAAQ,IAAI,8BAA8B,MAAM,YAAY,MAAM;CACxF,MAAM,iBAAiB,QAAQ,IAAI,+BAA+B,OAAO,YAAY,MAAM;CAC3F,MAAM,WAAW,YAAY,KAAK,KAAK,WAAW,mBAAmB,eAAe,IAAI;CAExF,OAAO;EACL,cAAc,gBAAgB,aAAa;EAC3C;EACA;CACF;AACF;;;;AC9BA,MAAM,kBAAkB;;AAGxB,MAAa,qBAAqB;;AAGlC,MAAa,sBAAsB;;;;;;AAOnC,SAAgB,kBAAkB,QAA6B;CA2B7D,OAAO;EAzBL,iBAAiB,OAAO;EACxB,cAAc,OAAO;EACrB,eAAe,OAAO;EACtB;EACA;EACA,gBAAgB,OAAO;EACvB,iBAAiB,OAAO;EACxB,OAAO,OAAO,WAAW,GAAG,OAAO;EACnC,SAAS,OAAO;EAChB;EACA;EACA,YAAY,OAAO;EACnB,cAAc,KAAK,UAAU,OAAO,IAAI;EACxC;EACA;EACA,SAAS,OAAO;EAChB,YAAY,OAAO;EACnB;EACA;EACA,OAAO,cAAc;EACrB;EACA;EACA,KAAK,UAAU,MAAM;EACrB;CAES,EAAE,KAAK,IAAI;AACxB;;;;;;;AAQA,SAAS,iBAAiB,QAA6B;CAGrD,OAAO,GAFe,OAAO,UAAU,QAAQ,SAAS,GAElC,EAAE,GADR,OAAO,GAAG,MAAM,GAAG,CACF,IAAI;AACvC;;;;;AAMA,SAAS,gBAAgB,KAAmB;CAC1C,IAAI;EACF,MAAM,QAAQ,GACX,YAAY,GAAG,EACf,QAAQ,MAAM,EAAE,SAAS,mBAAmB,CAAC,EAC7C,SAAS,EACT,WAAW;EAEd,KAAK,MAAM,QAAQ,MAAM,MAAM,eAAe,GAC5C,GAAG,WAAW,KAAK,KAAK,KAAK,IAAI,CAAC;CAEtC,QAAQ,CAER;AACF;;;;;;;;;AAUA,SAAgB,iBAAiB,QAAqB,KAAiC;CACrF,IAAI;EACF,gBAAgB,GAAG;EAEnB,MAAM,WAAW,iBAAiB,MAAM;EACxC,MAAM,WAAW,KAAK,KAAK,KAAK,QAAQ;EAGxC,gBAAgB,UAFA,kBAAkB,MAEF,CAAC;EACjC,gBAAgB,GAAG;EAEnB,OAAO;CACT,QAAQ;EACN;CACF;AACF;;;;ACrGA,MAAM,kBAAkB;AACxB,MAAM,sBAAsB;AAE5B,MAAM,kBAAkB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8CxB,eAAsB,gBAAgB,QAAqB,IAA8B;CACvF,IAAI;EACF,MAAM,WAAW,QAAQ,IAAI,gCAAgC;EAC7D,MAAM,WAAW,MAAM,MAAM,UAAU;GACrC,QAAQ;GACR,SAAS;IACP,gBAAgB;IAChB,cAAc;GAChB;GACA,MAAM,KAAK,UAAU;IACnB,OAAO;IACP,WAAW;GACb,CAAC;GACD,QAAQ,YAAY,QAAQ,eAAe;EAC7C,CAAC;EAED,IAAI,CAAC,SAAS,IAAI,OAAO;EAEzB,MAAM,OAAQ,MAAM,SAAS,KAAK;EAIlC,IAAI,KAAK,QAAQ,QAAQ,OAAO;EAChC,OAAO,KAAK,MAAM,kBAAkB,YAAY;CAClD,QAAQ;EACN,OAAO;CACT;AACF;;;;AC5EA,MAAM,WAAW,GAAG,QAAQ;AAG5B,MAAM,eAAe;AACrB,MAAM,mBAAmB;AACzB,MAAM,gBAAgB;AACtB,MAAM,wBAAwB;AAC9B,MAAM,uBAAuB;AAC7B,MAAM,oBAAoB;AAG1B,MAAM,qBAAqB;AAC3B,MAAM,6BAA6B;AAGnC,MAAM,qBAAqB;AAE3B,SAAS,YAAY,UAAkB,WAA2B;CAChE,OAAO,SAAS,MAAM,SAAS,EAAE,IAAI,KAAK;AAC5C;;;;;;;;AASA,SAAgB,mBAAmB,OAAuB;CAKxD,MAAM,kBAAkB,MAAM,OAAO,UAAU;CAC/C,IAAI;CACJ,IAAI,oBAAoB,IACtB,SAAS,gBAAgB,MAAM,MAAM,GAAG,eAAe,CAAC,IAAI,MAAM,MAAM,eAAe;MAEvF,SAAS,gBAAgB,KAAK;CAGhC,SAAS,OAAO,QAAQ,wBAAwB,UAAU;EACxD,MAAM,WAAW,MAAM,QAAQ,kBAAkB;EACjD,IAAI,aAAa,IACf,OAAO,MAAM,MAAM,QAAQ;EAG7B,IAAI,MAAM,WAAW,QAAQ,GAC3B,OAAO,gBAAgB,YAAY,OAAO,GAAG;EAG/C,OAAO,cAAc,YAAY,OAAO,GAAG;CAC7C,CAAC;CACD,SAAS,OAAO,QAAQ,uBAAuB,UAAU;EACvD,MAAM,aAAa,MAAM,QAAQ,OAAO,GAAG;EAC3C,MAAM,WAAW,WAAW,QAAQ,kBAAkB;EACtD,IAAI,aAAa,IACf,OAAO,WAAW,MAAM,QAAQ;EAElC,OAAO,cAAc,YAAY,OAAO,IAAI;CAC9C,CAAC;CACD,OAAO;AACT;;;;;;;AAQA,SAAgB,gBAAgB,SAAyB;CACvD,IAAI,SAAS;CAEb,SAAS,OAAO,QAAQ,yBAAyB,uBAAuB;CACxE,SAAS,OAAO,QAAQ,cAAc,QAAQ;CAC9C,SAAS,OAAO,QAAQ,kBAAkB,YAAY;CACtD,SAAS,OAAO,QAAQ,eAAe,SAAS;CAChD,SAAS,OAAO,QAAQ,mBAAmB,aAAa;CACxD,SAAS,OAAO,QAAQ,wBAAwB,UAAU,UAAU,YAAY,OAAO,GAAG,GAAG;CAC7F,SAAS,OAAO,QAAQ,uBAAuB,UAAU,UAAU,YAAY,OAAO,IAAI,GAAG;CAE7F,OAAO;AACT;;;;;;;AAQA,SAAgB,aAAa,MAA0B;CACrD,MAAM,SAAmB,CAAC;CAC1B,IAAI,aAAa;CAEjB,KAAK,MAAM,OAAO,MAAM;EACtB,IAAI,YAAY;GAKd,IAAI,CAAC,IAAI,WAAW,GAAG,GAAG;IACxB,OAAO,KAAK,YAAY;IACxB,aAAa;IACb;GACF;GACA,aAAa;EACf;EAEA,IAAI,IAAI,WAAW,GAAG,GAAG;GAEvB,MAAM,UAAU,IAAI,QAAQ,GAAG;GAC/B,IAAI,YAAY,IAAI;IAClB,OAAO,KAAK,GAAG,IAAI,MAAM,GAAG,OAAO,EAAE,YAAY;IACjD;GACF;GAGA,OAAO,KAAK,GAAG;GACf,aAAa;GACb;EACF;EAGA,IAAI,IAAI,WAAW,GAAG,KAAK,IAAI,SAAS,KAAK,CAAC,GAAG;GAC/C,OAAO,KAAK,QAAQ;GACpB;EACF;EAGA,IAAI,2BAA2B,KAAK,GAAG,GAAG;GACxC,OAAO,KAAK,QAAQ;GACpB;EACF;EAGA,IAAI,mBAAmB,KAAK,GAAG,GAAG;GAChC,OAAO,KAAK,SAAS;GACrB;EACF;EAEA,OAAO,KAAK,GAAG;CACjB;CAEA,OAAO;AACT;;;;AC3GA,MAAM,qBAAqB;;;;;;AAO3B,SAAS,eAAuB;CAC9B,MAAM,OAAO,QAAQ,KAAK,MAAM,CAAC;CACjC,MAAM,eAAyB,CAAC;CAChC,KAAK,MAAM,OAAO,MAAM;EACtB,IAAI,IAAI,WAAW,GAAG,KAAK,aAAa,UAAU,oBAAoB;EACtE,aAAa,KAAK,GAAG;CACvB;CACA,OAAO,aAAa,KAAK,GAAG,KAAK;AACnC;;;;;;;AAQA,SAAgB,iBAAiB,SAA+C;CAC9E,MAAM,EAAE,OAAO,YAAY,cAAc;CAEzC,MAAM,UAAU,iBAAiB;CACjC,MAAM,aAAa,UAAU,MAAM,UAAU,OAAO,KAAK;CACzD,MAAM,WAAW,WAAW,MAAM,QAAQ,MAAM,QAAQ;CACxD,MAAM,YAAY,UAAU,MAAM,OAAO;CAEzC,MAAM,cAAc,gBAAgB;CAEpC,OAAO;EACL,IAAI,OAAO,WAAW;EACtB,4BAAW,IAAI,KAAK,GAAE,YAAY;EAClC;EACA,aAAa,QAAQ;EACrB,YAAY,QAAQ;EACpB,WAAW,GAAG,QAAQ;EACtB,MAAM,QAAQ;EACd,SAAS,gBAAgB,aAAa,CAAC;EACvC,MAAM,aAAa,QAAQ,IAAI;EAC/B;EACA,cAAc,gBAAgB,UAAU;EACxC,YAAY,mBAAmB,QAAQ;EACvC;EACA,QAAQ;EACR,WAAW;CACb;AACF;;;;;;AAOA,SAAS,kBAAiC;CACxC,IAAI;EACF,IAAI,CAAC,WAAW,OAAO;EACvB,MAAM,aAAa,KAAK,KAAK,WAAW,mBAAmB,aAAa;EACxE,IAAI,CAAC,GAAG,WAAW,UAAU,GAAG,OAAO;EAEvC,OADY,UAAU,GAAG,aAAa,YAAY,OAAO,CAChD,GAAG,gBAAgB;CAC9B,QAAQ;EACN,OAAO;CACT;AACF;;;;;;;;;;;;;AC1FA,eAAsB,YAAY,OAAgB,WAAqC;CACrF,IAAI;EACF,MAAM,SAAS,uBAAuB;EACtC,IAAI,CAAC,OAAO,gBAAgB,CAAC,OAAO,eAAe;EAKnD,MAAM,SAAS,iBAAiB;GAAE;GAAO,aAFtB,MADO,gBAAgB,GACX,WAAW;GAEW;EAAU,CAAC;EAEhE,IAAI,OAAO,cAAc;GACvB,MAAM,WAAW,iBAAiB,QAAQ,OAAO,QAAQ;GACzD,IAAI,UACF,OAAO,IACL;IACE;IACA;IACA,KAAK;IACL;IACA;IACA,yCAAyC,SAAS;GACpD,EAAE,KAAK,IAAI,CACb;EAEJ;EAEA,IAAI,OAAO,eAAe;GAGxB,MAAM,EAAE,cAAc,MAAM,OAAO;GAEnC,MAAM,gBAAgB,QAAQ,MADb,UAAU,CACK;EAClC;CACF,QAAQ,CAER;AACF;;;;;;AAOA,SAAgB,qBAA2B;CACzC,MAAM,SAAS,uBAAuB;CACtC,IAAI,CAAC,OAAO,gBAAgB,CAAC,OAAO,eAAe;CAEnD,MAAM,eAAe,OAAgB,cAAyB;EAC5D,MAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;EACrE,OAAO,MAAM,OAAO;EACpB,AAAK,YAAY,OAAO,SAAS,EAAE,cAAc;GAC/C,QAAQ,KAAK,CAAC;EAChB,CAAC;CACH;CAEA,QAAQ,GAAG,sBAAsB,UAAU,YAAY,OAAO,mBAAmB,CAAC;CAClF,QAAQ,GAAG,uBAAuB,WAAW,YAAY,QAAQ,oBAAoB,CAAC;AACxF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"file-B58Dm-2P.mjs","names":[],"sources":["../src/runtime/file.ts"],"sourcesContent":["/**\n * TailorDB file (BLOB) utilities.\n *\n * Thin typed wrapper around the platform-provided `tailordb.file` runtime API.\n * At runtime this delegates to `globalThis.tailordb.file`. Use `fileMock` from\n * `@tailor-platform/sdk/vitest` to mock these calls in unit tests.\n * @example\n * import { file } from \"@tailor-platform/sdk/runtime\";\n *\n * const { metadata } = await file.upload(\n * \"my-namespace\",\n * \"Document\",\n * \"attachment\",\n * recordId,\n * bytes,\n * );\n */\n\n/** Upload response metadata. */\nexport interface UploadMetadata {\n fileSize: number;\n sha256sum: string;\n}\n\n/** Download response metadata. */\nexport interface DownloadMetadata {\n contentType: string;\n fileSize: number;\n sha256sum: string;\n lastUploadedAt: string;\n}\n\n/** File metadata (for {@link getMetadata}). */\nexport interface FileMetadata {\n contentType: string;\n fileSize: number;\n sha256sum: string;\n urlPath: string;\n lastUploadedAt?: string;\n}\n\n/** Stream metadata (first chunk emitted by {@link openDownloadStream}). */\nexport interface StreamMetadata {\n contentType: string;\n fileSize: number;\n sha256sum: string;\n}\n\n/** Upload options. */\nexport interface FileUploadOptions {\n contentType?: string;\n}\n\n/** Upload stream options. */\nexport interface FileUploadStreamOptions {\n contentType?: string;\n fileSize?: number;\n}\n\n/** Upload response. */\nexport interface FileUploadResponse {\n metadata: UploadMetadata;\n}\n\n/** Download response. */\nexport interface FileDownloadResponse {\n data: Uint8Array;\n metadata: DownloadMetadata;\n}\n\n/** Download-as-Base64 response. */\nexport interface FileDownloadAsBase64Response {\n data: string;\n metadata: DownloadMetadata;\n}\n\n/** Download stream response. */\nexport interface FileDownloadStreamResponse {\n body: ReadableStream<Uint8Array>;\n metadata: DownloadMetadata;\n}\n\n/** Stream chunk types emitted by {@link FileStreamIterator}. */\nexport type StreamValue =\n | { type: \"metadata\"; metadata: StreamMetadata }\n | { type: \"chunk\"; data: Uint8Array; position: number }\n | { type: \"complete\" };\n\n/** Stream iterator returned by {@link openDownloadStream}. */\nexport interface FileStreamIterator extends AsyncIterableIterator<StreamValue> {\n next(): Promise<IteratorResult<StreamValue>>;\n close(): Promise<void>;\n}\n\n/** Error code emitted by {@link TailorDBFileError}. */\nexport type TailorDBFileErrorCode =\n | \"INVALID_PARAMS\"\n | \"INVALID_DATA_TYPE\"\n | \"OPERATION_FAILED\"\n | \"DELETE_FAILED\"\n | \"STREAM_OPEN_FAILED\"\n | \"STREAM_READ_ERROR\"\n | \"STREAM_ERROR\"\n | \"FILE_TOO_LARGE\";\n\n/**\n * Type-only shape of the `TailorDBFileError` runtime class. The class itself\n * is provided by the platform runtime (and by `injectMocks` in tests); this\n * interface mirrors it so callers can `import type { TailorDBFileError }` from\n * the wrapper module without depending on any ambient declaration.\n */\nexport interface TailorDBFileError extends Error {\n name: \"TailorDBFileError\";\n code?: TailorDBFileErrorCode;\n cause?: unknown;\n}\n\n/**\n * Platform API surface for `tailordb.file`. Describes the shape the platform\n * runtime injects on `globalThis.tailordb.file`.\n *\n * Each method below is also re-exported as a top-level named export from this\n * module (e.g. `upload`, `download`, `deleteFile`) so callers can either\n * `import * as file from \"@tailor-platform/sdk/runtime/file\"` or pick\n * individual methods.\n */\nexport interface TailorDBFileAPI {\n /**\n * Upload a file to TailorDB.\n * @param namespace - TailorDB namespace\n * @param typeName - TailorDB type name\n * @param fieldName - File field name on the type\n * @param recordId - Record ID owning the field\n * @param data - File contents\n * @param options - Upload options (e.g. `contentType`)\n * @returns Upload response containing the file metadata\n */\n upload(\n namespace: string,\n typeName: string,\n fieldName: string,\n recordId: string,\n data: string | ArrayBuffer | Uint8Array | number[],\n options?: FileUploadOptions,\n ): Promise<FileUploadResponse>;\n\n /**\n * Download a file from TailorDB.\n *\n * Throws `TailorDBFileError` with code `FILE_TOO_LARGE` when the file\n * exceeds 10MB — use {@link downloadStream} for large files.\n * @param namespace - TailorDB namespace\n * @param typeName - TailorDB type name\n * @param fieldName - File field name on the type\n * @param recordId - Record ID owning the field\n * @returns Bytes and metadata for the file\n */\n download(\n namespace: string,\n typeName: string,\n fieldName: string,\n recordId: string,\n ): Promise<FileDownloadResponse>;\n\n /**\n * Download a file from TailorDB as a Base64-encoded string.\n *\n * Throws `TailorDBFileError` with code `FILE_TOO_LARGE` when the file\n * exceeds 10MB — use {@link downloadStream} for large files.\n * @param namespace - TailorDB namespace\n * @param typeName - TailorDB type name\n * @param fieldName - File field name on the type\n * @param recordId - Record ID owning the field\n * @returns Base64-encoded contents and metadata for the file\n */\n downloadAsBase64(\n namespace: string,\n typeName: string,\n fieldName: string,\n recordId: string,\n ): Promise<FileDownloadAsBase64Response>;\n\n /**\n * Delete a file from TailorDB. Exported as `deleteFile` (and aliased as\n * `delete`) so it can be used both with named and namespace imports.\n * @param namespace - TailorDB namespace\n * @param typeName - TailorDB type name\n * @param fieldName - File field name on the type\n * @param recordId - Record ID owning the field\n * @returns Resolves once the file has been deleted\n */\n delete(namespace: string, typeName: string, fieldName: string, recordId: string): Promise<void>;\n\n /**\n * Get file metadata from TailorDB.\n * @param namespace - TailorDB namespace\n * @param typeName - TailorDB type name\n * @param fieldName - File field name on the type\n * @param recordId - Record ID owning the field\n * @returns Metadata for the stored file\n */\n getMetadata(\n namespace: string,\n typeName: string,\n fieldName: string,\n recordId: string,\n ): Promise<FileMetadata>;\n\n /**\n * Open a download stream for large files.\n * @deprecated Use {@link downloadStream} instead.\n * @param namespace - TailorDB namespace\n * @param typeName - TailorDB type name\n * @param fieldName - File field name on the type\n * @param recordId - Record ID owning the field\n * @returns Async iterator yielding file chunks; call `close()` to release resources\n */\n openDownloadStream(\n namespace: string,\n typeName: string,\n fieldName: string,\n recordId: string,\n ): Promise<FileStreamIterator>;\n\n /**\n * Download a file as a ReadableStream.\n * @param namespace - TailorDB namespace\n * @param typeName - TailorDB type name\n * @param fieldName - File field name on the type\n * @param recordId - Record ID owning the field\n * @returns ReadableStream body and metadata for the file\n */\n downloadStream(\n namespace: string,\n typeName: string,\n fieldName: string,\n recordId: string,\n ): Promise<FileDownloadStreamResponse>;\n\n /**\n * Upload a file using a ReadableStream.\n * @param namespace - TailorDB namespace\n * @param typeName - TailorDB type name\n * @param fieldName - File field name on the type\n * @param recordId - Record ID owning the field\n * @param readableStream - ReadableStream providing the file data\n * @param options - Upload stream options (e.g. `contentType`, `fileSize`)\n * @returns Upload response containing the file metadata\n */\n uploadStream(\n namespace: string,\n typeName: string,\n fieldName: string,\n recordId: string,\n readableStream: ReadableStream<Uint8Array | ArrayBuffer>,\n options?: FileUploadStreamOptions,\n ): Promise<FileUploadResponse>;\n}\n\nconst api = (): TailorDBFileAPI =>\n (globalThis as { tailordb: { file: TailorDBFileAPI } }).tailordb.file;\n\n/**\n * See {@link TailorDBFileAPI.upload}.\n * @param args - Forwarded to {@link TailorDBFileAPI.upload}\n * @returns Upload response containing the file metadata\n */\nexport const upload: TailorDBFileAPI[\"upload\"] = (...args) => api().upload(...args);\n\n/**\n * See {@link TailorDBFileAPI.download}.\n * @param args - Forwarded to {@link TailorDBFileAPI.download}\n * @returns Bytes and metadata for the file\n */\nexport const download: TailorDBFileAPI[\"download\"] = (...args) => api().download(...args);\n\n/**\n * See {@link TailorDBFileAPI.downloadAsBase64}.\n * @param args - Forwarded to {@link TailorDBFileAPI.downloadAsBase64}\n * @returns Base64-encoded contents and metadata for the file\n */\nexport const downloadAsBase64: TailorDBFileAPI[\"downloadAsBase64\"] = (...args) =>\n api().downloadAsBase64(...args);\n\n/**\n * See {@link TailorDBFileAPI.delete}.\n * @param args - Forwarded to {@link TailorDBFileAPI.delete}\n * @returns Resolves once the file has been deleted\n */\nexport const deleteFile: TailorDBFileAPI[\"delete\"] = (...args) => api().delete(...args);\n\n/**\n * See {@link TailorDBFileAPI.getMetadata}.\n * @param args - Forwarded to {@link TailorDBFileAPI.getMetadata}\n * @returns Metadata for the stored file\n */\nexport const getMetadata: TailorDBFileAPI[\"getMetadata\"] = (...args) => api().getMetadata(...args);\n\n/**\n * See {@link TailorDBFileAPI.openDownloadStream}.\n * @deprecated Use {@link downloadStream} instead.\n * @param args - Forwarded to {@link TailorDBFileAPI.openDownloadStream}\n * @returns Async iterator yielding file chunks; call `close()` to release resources\n */\nexport const openDownloadStream: TailorDBFileAPI[\"openDownloadStream\"] = (...args) =>\n api().openDownloadStream(...args);\n\n/**\n * See {@link TailorDBFileAPI.downloadStream}.\n * @param args - Forwarded to {@link TailorDBFileAPI.downloadStream}\n * @returns ReadableStream body and metadata for the file\n */\nexport const downloadStream: TailorDBFileAPI[\"downloadStream\"] = (...args) =>\n api().downloadStream(...args);\n\n/**\n * See {@link TailorDBFileAPI.uploadStream}.\n * @param args - Forwarded to {@link TailorDBFileAPI.uploadStream}\n * @returns Upload response containing the file metadata\n */\nexport const uploadStream: TailorDBFileAPI[\"uploadStream\"] = (...args) =>\n api().uploadStream(...args);\n\nexport { deleteFile as delete };\n"],"mappings":";;;;;;;;;;;;;;;AAmQA,MAAM,YACH,WAAuD,SAAS;;;;;;AAOnE,MAAa,UAAqC,GAAG,SAAS,IAAI,EAAE,OAAO,GAAG,IAAI;;;;;;AAOlF,MAAa,YAAyC,GAAG,SAAS,IAAI,EAAE,SAAS,GAAG,IAAI;;;;;;AAOxF,MAAa,oBAAyD,GAAG,SACvE,IAAI,EAAE,iBAAiB,GAAG,IAAI;;;;;;AAOhC,MAAa,cAAyC,GAAG,SAAS,IAAI,EAAE,OAAO,GAAG,IAAI;;;;;;AAOtF,MAAa,eAA+C,GAAG,SAAS,IAAI,EAAE,YAAY,GAAG,IAAI;;;;;;;AAQjG,MAAa,sBAA6D,GAAG,SAC3E,IAAI,EAAE,mBAAmB,GAAG,IAAI;;;;;;AAOlC,MAAa,kBAAqD,GAAG,SACnE,IAAI,EAAE,eAAe,GAAG,IAAI;;;;;;AAO9B,MAAa,gBAAiD,GAAG,SAC/D,IAAI,EAAE,aAAa,GAAG,IAAI"}
|
|
1
|
+
{"version":3,"file":"file-B58Dm-2P.mjs","names":[],"sources":["../src/runtime/file.ts"],"sourcesContent":["/**\n * TailorDB file (BLOB) utilities.\n *\n * Thin typed wrapper around the platform-provided `tailordb.file` runtime API.\n * At runtime this delegates to `globalThis.tailordb.file`. Use `mockFile` from\n * `@tailor-platform/sdk/vitest` to mock these calls in unit tests.\n * @example\n * import { file } from \"@tailor-platform/sdk/runtime\";\n *\n * const { metadata } = await file.upload(\n * \"my-namespace\",\n * \"Document\",\n * \"attachment\",\n * recordId,\n * bytes,\n * );\n */\n\n/** Upload response metadata. */\nexport interface UploadMetadata {\n fileSize: number;\n sha256sum: string;\n}\n\n/** Download response metadata. */\nexport interface DownloadMetadata {\n contentType: string;\n fileSize: number;\n sha256sum: string;\n lastUploadedAt: string;\n}\n\n/** File metadata (for {@link getMetadata}). */\nexport interface FileMetadata {\n contentType: string;\n fileSize: number;\n sha256sum: string;\n urlPath: string;\n lastUploadedAt?: string;\n}\n\n/** Stream metadata (first chunk emitted by {@link openDownloadStream}). */\nexport interface StreamMetadata {\n contentType: string;\n fileSize: number;\n sha256sum: string;\n}\n\n/** Upload options. */\nexport interface FileUploadOptions {\n contentType?: string;\n}\n\n/** Upload stream options. */\nexport interface FileUploadStreamOptions {\n contentType?: string;\n fileSize?: number;\n}\n\n/** Upload response. */\nexport interface FileUploadResponse {\n metadata: UploadMetadata;\n}\n\n/** Download response. */\nexport interface FileDownloadResponse {\n data: Uint8Array;\n metadata: DownloadMetadata;\n}\n\n/** Download-as-Base64 response. */\nexport interface FileDownloadAsBase64Response {\n data: string;\n metadata: DownloadMetadata;\n}\n\n/** Download stream response. */\nexport interface FileDownloadStreamResponse {\n body: ReadableStream<Uint8Array>;\n metadata: DownloadMetadata;\n}\n\n/** Stream chunk types emitted by {@link FileStreamIterator}. */\nexport type StreamValue =\n | { type: \"metadata\"; metadata: StreamMetadata }\n | { type: \"chunk\"; data: Uint8Array; position: number }\n | { type: \"complete\" };\n\n/** Stream iterator returned by {@link openDownloadStream}. */\nexport interface FileStreamIterator extends AsyncIterableIterator<StreamValue> {\n next(): Promise<IteratorResult<StreamValue>>;\n close(): Promise<void>;\n}\n\n/** Error code emitted by {@link TailorDBFileError}. */\nexport type TailorDBFileErrorCode =\n | \"INVALID_PARAMS\"\n | \"INVALID_DATA_TYPE\"\n | \"OPERATION_FAILED\"\n | \"DELETE_FAILED\"\n | \"STREAM_OPEN_FAILED\"\n | \"STREAM_READ_ERROR\"\n | \"STREAM_ERROR\"\n | \"FILE_TOO_LARGE\";\n\n/**\n * Type-only shape of the `TailorDBFileError` runtime class. The class itself\n * is provided by the platform runtime (and by `injectMocks` in tests); this\n * interface mirrors it so callers can `import type { TailorDBFileError }` from\n * the wrapper module without depending on any ambient declaration.\n */\nexport interface TailorDBFileError extends Error {\n name: \"TailorDBFileError\";\n code?: TailorDBFileErrorCode;\n cause?: unknown;\n}\n\n/**\n * Platform API surface for `tailordb.file`. Describes the shape the platform\n * runtime injects on `globalThis.tailordb.file`.\n *\n * Each method below is also re-exported as a top-level named export from this\n * module (e.g. `upload`, `download`, `deleteFile`) so callers can either\n * `import * as file from \"@tailor-platform/sdk/runtime/file\"` or pick\n * individual methods.\n */\nexport interface TailorDBFileAPI {\n /**\n * Upload a file to TailorDB.\n * @param namespace - TailorDB namespace\n * @param typeName - TailorDB type name\n * @param fieldName - File field name on the type\n * @param recordId - Record ID owning the field\n * @param data - File contents\n * @param options - Upload options (e.g. `contentType`)\n * @returns Upload response containing the file metadata\n */\n upload(\n namespace: string,\n typeName: string,\n fieldName: string,\n recordId: string,\n data: string | ArrayBuffer | Uint8Array | number[],\n options?: FileUploadOptions,\n ): Promise<FileUploadResponse>;\n\n /**\n * Download a file from TailorDB.\n *\n * Throws `TailorDBFileError` with code `FILE_TOO_LARGE` when the file\n * exceeds 10MB — use {@link downloadStream} for large files.\n * @param namespace - TailorDB namespace\n * @param typeName - TailorDB type name\n * @param fieldName - File field name on the type\n * @param recordId - Record ID owning the field\n * @returns Bytes and metadata for the file\n */\n download(\n namespace: string,\n typeName: string,\n fieldName: string,\n recordId: string,\n ): Promise<FileDownloadResponse>;\n\n /**\n * Download a file from TailorDB as a Base64-encoded string.\n *\n * Throws `TailorDBFileError` with code `FILE_TOO_LARGE` when the file\n * exceeds 10MB — use {@link downloadStream} for large files.\n * @param namespace - TailorDB namespace\n * @param typeName - TailorDB type name\n * @param fieldName - File field name on the type\n * @param recordId - Record ID owning the field\n * @returns Base64-encoded contents and metadata for the file\n */\n downloadAsBase64(\n namespace: string,\n typeName: string,\n fieldName: string,\n recordId: string,\n ): Promise<FileDownloadAsBase64Response>;\n\n /**\n * Delete a file from TailorDB. Exported as `deleteFile` (and aliased as\n * `delete`) so it can be used both with named and namespace imports.\n * @param namespace - TailorDB namespace\n * @param typeName - TailorDB type name\n * @param fieldName - File field name on the type\n * @param recordId - Record ID owning the field\n * @returns Resolves once the file has been deleted\n */\n delete(namespace: string, typeName: string, fieldName: string, recordId: string): Promise<void>;\n\n /**\n * Get file metadata from TailorDB.\n * @param namespace - TailorDB namespace\n * @param typeName - TailorDB type name\n * @param fieldName - File field name on the type\n * @param recordId - Record ID owning the field\n * @returns Metadata for the stored file\n */\n getMetadata(\n namespace: string,\n typeName: string,\n fieldName: string,\n recordId: string,\n ): Promise<FileMetadata>;\n\n /**\n * Open a download stream for large files.\n * @deprecated Use {@link downloadStream} instead.\n * @param namespace - TailorDB namespace\n * @param typeName - TailorDB type name\n * @param fieldName - File field name on the type\n * @param recordId - Record ID owning the field\n * @returns Async iterator yielding file chunks; call `close()` to release resources\n */\n openDownloadStream(\n namespace: string,\n typeName: string,\n fieldName: string,\n recordId: string,\n ): Promise<FileStreamIterator>;\n\n /**\n * Download a file as a ReadableStream.\n * @param namespace - TailorDB namespace\n * @param typeName - TailorDB type name\n * @param fieldName - File field name on the type\n * @param recordId - Record ID owning the field\n * @returns ReadableStream body and metadata for the file\n */\n downloadStream(\n namespace: string,\n typeName: string,\n fieldName: string,\n recordId: string,\n ): Promise<FileDownloadStreamResponse>;\n\n /**\n * Upload a file using a ReadableStream.\n * @param namespace - TailorDB namespace\n * @param typeName - TailorDB type name\n * @param fieldName - File field name on the type\n * @param recordId - Record ID owning the field\n * @param readableStream - ReadableStream providing the file data\n * @param options - Upload stream options (e.g. `contentType`, `fileSize`)\n * @returns Upload response containing the file metadata\n */\n uploadStream(\n namespace: string,\n typeName: string,\n fieldName: string,\n recordId: string,\n readableStream: ReadableStream<Uint8Array | ArrayBuffer>,\n options?: FileUploadStreamOptions,\n ): Promise<FileUploadResponse>;\n}\n\nconst api = (): TailorDBFileAPI =>\n (globalThis as { tailordb: { file: TailorDBFileAPI } }).tailordb.file;\n\n/**\n * See {@link TailorDBFileAPI.upload}.\n * @param args - Forwarded to {@link TailorDBFileAPI.upload}\n * @returns Upload response containing the file metadata\n */\nexport const upload: TailorDBFileAPI[\"upload\"] = (...args) => api().upload(...args);\n\n/**\n * See {@link TailorDBFileAPI.download}.\n * @param args - Forwarded to {@link TailorDBFileAPI.download}\n * @returns Bytes and metadata for the file\n */\nexport const download: TailorDBFileAPI[\"download\"] = (...args) => api().download(...args);\n\n/**\n * See {@link TailorDBFileAPI.downloadAsBase64}.\n * @param args - Forwarded to {@link TailorDBFileAPI.downloadAsBase64}\n * @returns Base64-encoded contents and metadata for the file\n */\nexport const downloadAsBase64: TailorDBFileAPI[\"downloadAsBase64\"] = (...args) =>\n api().downloadAsBase64(...args);\n\n/**\n * See {@link TailorDBFileAPI.delete}.\n * @param args - Forwarded to {@link TailorDBFileAPI.delete}\n * @returns Resolves once the file has been deleted\n */\nexport const deleteFile: TailorDBFileAPI[\"delete\"] = (...args) => api().delete(...args);\n\n/**\n * See {@link TailorDBFileAPI.getMetadata}.\n * @param args - Forwarded to {@link TailorDBFileAPI.getMetadata}\n * @returns Metadata for the stored file\n */\nexport const getMetadata: TailorDBFileAPI[\"getMetadata\"] = (...args) => api().getMetadata(...args);\n\n/**\n * See {@link TailorDBFileAPI.openDownloadStream}.\n * @deprecated Use {@link downloadStream} instead.\n * @param args - Forwarded to {@link TailorDBFileAPI.openDownloadStream}\n * @returns Async iterator yielding file chunks; call `close()` to release resources\n */\nexport const openDownloadStream: TailorDBFileAPI[\"openDownloadStream\"] = (...args) =>\n api().openDownloadStream(...args);\n\n/**\n * See {@link TailorDBFileAPI.downloadStream}.\n * @param args - Forwarded to {@link TailorDBFileAPI.downloadStream}\n * @returns ReadableStream body and metadata for the file\n */\nexport const downloadStream: TailorDBFileAPI[\"downloadStream\"] = (...args) =>\n api().downloadStream(...args);\n\n/**\n * See {@link TailorDBFileAPI.uploadStream}.\n * @param args - Forwarded to {@link TailorDBFileAPI.uploadStream}\n * @returns Upload response containing the file metadata\n */\nexport const uploadStream: TailorDBFileAPI[\"uploadStream\"] = (...args) =>\n api().uploadStream(...args);\n\nexport { deleteFile as delete };\n"],"mappings":";;;;;;;;;;;;;;;AAmQA,MAAM,YACH,WAAuD,SAAS;;;;;;AAOnE,MAAa,UAAqC,GAAG,SAAS,IAAI,EAAE,OAAO,GAAG,IAAI;;;;;;AAOlF,MAAa,YAAyC,GAAG,SAAS,IAAI,EAAE,SAAS,GAAG,IAAI;;;;;;AAOxF,MAAa,oBAAyD,GAAG,SACvE,IAAI,EAAE,iBAAiB,GAAG,IAAI;;;;;;AAOhC,MAAa,cAAyC,GAAG,SAAS,IAAI,EAAE,OAAO,GAAG,IAAI;;;;;;AAOtF,MAAa,eAA+C,GAAG,SAAS,IAAI,EAAE,YAAY,GAAG,IAAI;;;;;;;AAQjG,MAAa,sBAA6D,GAAG,SAC3E,IAAI,EAAE,mBAAmB,GAAG,IAAI;;;;;;AAOlC,MAAa,kBAAqD,GAAG,SACnE,IAAI,EAAE,eAAe,GAAG,IAAI;;;;;;AAO9B,MAAa,gBAAiD,GAAG,SAC/D,IAAI,EAAE,aAAa,GAAG,IAAI"}
|
|
@@ -5,7 +5,7 @@ declare namespace file_d_exports {
|
|
|
5
5
|
* TailorDB file (BLOB) utilities.
|
|
6
6
|
*
|
|
7
7
|
* Thin typed wrapper around the platform-provided `tailordb.file` runtime API.
|
|
8
|
-
* At runtime this delegates to `globalThis.tailordb.file`. Use `
|
|
8
|
+
* At runtime this delegates to `globalThis.tailordb.file`. Use `mockFile` from
|
|
9
9
|
* `@tailor-platform/sdk/vitest` to mock these calls in unit tests.
|
|
10
10
|
* @example
|
|
11
11
|
* import { file } from "@tailor-platform/sdk/runtime";
|
|
@@ -247,4 +247,4 @@ declare const downloadStream: TailorDBFileAPI["downloadStream"];
|
|
|
247
247
|
declare const uploadStream: TailorDBFileAPI["uploadStream"];
|
|
248
248
|
//#endregion
|
|
249
249
|
export { upload as C, openDownloadStream as S, download as _, FileMetadata as a, file_d_exports as b, FileUploadResponse as c, StreamValue as d, TailorDBFileAPI as f, deleteFile as g, UploadMetadata as h, FileDownloadStreamResponse as i, FileUploadStreamOptions as l, TailorDBFileErrorCode as m, FileDownloadAsBase64Response as n, FileStreamIterator as o, TailorDBFileError as p, FileDownloadResponse as r, FileUploadOptions as s, DownloadMetadata as t, StreamMetadata as u, downloadAsBase64 as v, uploadStream as w, getMetadata as x, downloadStream as y };
|
|
250
|
-
//# sourceMappingURL=file-
|
|
250
|
+
//# sourceMappingURL=file-BzK8z3X-.d.mts.map
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
|
|
2
|
+
import { c as runRegisteredJob, l as runRegisteredWorkflow } from "./registry-D0uB0OrK.mjs";
|
|
3
|
+
|
|
4
|
+
//#region src/vitest/workflow-runtime.ts
|
|
5
|
+
function createDefaultWorkflowRuntime() {
|
|
6
|
+
return {
|
|
7
|
+
triggerJobFunction: (name, args) => runRegisteredJob(name, args),
|
|
8
|
+
triggerWorkflow: (name, args) => runRegisteredWorkflow(name, args),
|
|
9
|
+
wait: (key) => {
|
|
10
|
+
throw new Error(`No wait handler for "${key}". Acquire mockWorkflow() and call setWaitHandler(...).`);
|
|
11
|
+
},
|
|
12
|
+
resolve: async () => {
|
|
13
|
+
throw new Error("No resolve handler. Acquire mockWorkflow() and call setResolveHandler(...).");
|
|
14
|
+
}
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
//#endregion
|
|
19
|
+
//#region src/vitest/globals.ts
|
|
20
|
+
/**
|
|
21
|
+
* Base platform globals for the tailor-runtime test environment.
|
|
22
|
+
*
|
|
23
|
+
* This module is intentionally free of any `vitest` (`vi`) dependency so it can
|
|
24
|
+
* be imported from the Vitest *environment* module (which runs in a realm where
|
|
25
|
+
* `vi` is not available). It installs only the always-present structural pieces:
|
|
26
|
+
*
|
|
27
|
+
* - `globalThis.tailor` / `globalThis.tailordb` container objects
|
|
28
|
+
* - `globalThis.tailor.context.getInvoker` default stub
|
|
29
|
+
* - the platform error classes (`TailorErrors`, `TailorErrorMessage`,
|
|
30
|
+
* `TailorDBFileError`)
|
|
31
|
+
* - the `__tailorRuntimeActive` sentinel flag
|
|
32
|
+
*
|
|
33
|
+
* The per-namespace mock behavior (TailorDB client, workflow, secretmanager, …)
|
|
34
|
+
* is installed on demand by the `xMock()` factories in `./mock`, which run in
|
|
35
|
+
* test context where `vi` *is* available.
|
|
36
|
+
*/
|
|
37
|
+
const RUNTIME_FLAG_KEY = "__tailorRuntimeActive";
|
|
38
|
+
var TailorErrorsMock = class extends Error {
|
|
39
|
+
errors;
|
|
40
|
+
constructor(errors) {
|
|
41
|
+
if (!Array.isArray(errors)) throw new TypeError("TailorErrors: errors must be an array");
|
|
42
|
+
const validated = errors.map((e, i) => {
|
|
43
|
+
if (typeof e.message !== "string") throw new TypeError(`TailorErrors: errors[${i}].message must be a string`);
|
|
44
|
+
if (!Array.isArray(e.path)) throw new TypeError(`TailorErrors: errors[${i}].path must be an array`);
|
|
45
|
+
return {
|
|
46
|
+
message: e.message,
|
|
47
|
+
path: e.path
|
|
48
|
+
};
|
|
49
|
+
});
|
|
50
|
+
super(`TailorErrors: ${JSON.stringify({ errors: validated })}`);
|
|
51
|
+
this.name = "TailorErrors";
|
|
52
|
+
this.errors = validated;
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
var TailorErrorMessageMock = class extends Error {
|
|
56
|
+
constructor(message) {
|
|
57
|
+
super(message);
|
|
58
|
+
this.name = "TailorErrorMessage";
|
|
59
|
+
}
|
|
60
|
+
};
|
|
61
|
+
var TailorDBFileErrorMock = class extends Error {
|
|
62
|
+
code;
|
|
63
|
+
cause;
|
|
64
|
+
constructor(message, code, cause) {
|
|
65
|
+
super(message);
|
|
66
|
+
this.name = "TailorDBFileError";
|
|
67
|
+
this.code = code;
|
|
68
|
+
this.cause = cause;
|
|
69
|
+
}
|
|
70
|
+
};
|
|
71
|
+
function defaultGetInvoker() {
|
|
72
|
+
return null;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Install the always-present base platform globals (containers, context stub,
|
|
76
|
+
* error classes, runtime flag). Per-namespace mocks are layered on top by the
|
|
77
|
+
* `xMock()` factories in `./mock`.
|
|
78
|
+
* @param global - The global object to install into (typically `globalThis`)
|
|
79
|
+
*/
|
|
80
|
+
function installPlatformGlobals(global) {
|
|
81
|
+
const g = global;
|
|
82
|
+
g[RUNTIME_FLAG_KEY] = true;
|
|
83
|
+
g.tailor = {
|
|
84
|
+
context: { getInvoker: defaultGetInvoker },
|
|
85
|
+
workflow: createDefaultWorkflowRuntime()
|
|
86
|
+
};
|
|
87
|
+
g.tailordb = {};
|
|
88
|
+
g.TailorErrors = TailorErrorsMock;
|
|
89
|
+
g.TailorErrorMessage = TailorErrorMessageMock;
|
|
90
|
+
g.TailorDBFileError = TailorDBFileErrorMock;
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Remove the base platform globals (and anything the namespace mocks layered on
|
|
94
|
+
* top, since they live under the same containers).
|
|
95
|
+
* @param global - The global object to clean up (typically `globalThis`)
|
|
96
|
+
*/
|
|
97
|
+
function cleanupPlatformGlobals(global) {
|
|
98
|
+
const g = global;
|
|
99
|
+
delete g.tailordb;
|
|
100
|
+
delete g.tailor;
|
|
101
|
+
delete g.TailorErrors;
|
|
102
|
+
delete g.TailorErrorMessage;
|
|
103
|
+
delete g.TailorDBFileError;
|
|
104
|
+
delete g[RUNTIME_FLAG_KEY];
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
//#endregion
|
|
108
|
+
export { cleanupPlatformGlobals as n, installPlatformGlobals as r, RUNTIME_FLAG_KEY as t };
|
|
109
|
+
//# sourceMappingURL=globals-ByrCoDip.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"globals-ByrCoDip.mjs","names":[],"sources":["../src/vitest/workflow-runtime.ts","../src/vitest/globals.ts"],"sourcesContent":["// Default `tailor.workflow` runner installed by the `tailor-runtime` environment.\n// Must stay free of `vitest` (`vi`): it loads via `./globals` in the environment\n// realm where `vi` is unavailable, hence relative imports only (no `@/` alias).\nimport { runRegisteredJob, runRegisteredWorkflow } from \"../configure/services/workflow/registry\";\n\nexport interface DefaultWorkflowRuntime {\n triggerJobFunction: (name: string, args?: unknown) => unknown;\n triggerWorkflow: (name: string, args?: unknown, options?: unknown) => Promise<string>;\n wait: (key: string, payload?: unknown) => unknown;\n resolve: (\n executionId: string,\n key: string,\n callback: (payload: unknown) => unknown,\n ) => Promise<void>;\n}\n\nexport function createDefaultWorkflowRuntime(): DefaultWorkflowRuntime {\n return {\n triggerJobFunction: (name, args) => runRegisteredJob(name, args),\n triggerWorkflow: (name, args) => runRegisteredWorkflow(name, args),\n wait: (key: string): unknown => {\n throw new Error(\n `No wait handler for \"${key}\". Acquire mockWorkflow() and call setWaitHandler(...).`,\n );\n },\n resolve: async (): Promise<void> => {\n throw new Error(\n \"No resolve handler. Acquire mockWorkflow() and call setResolveHandler(...).\",\n );\n },\n };\n}\n","/**\n * Base platform globals for the tailor-runtime test environment.\n *\n * This module is intentionally free of any `vitest` (`vi`) dependency so it can\n * be imported from the Vitest *environment* module (which runs in a realm where\n * `vi` is not available). It installs only the always-present structural pieces:\n *\n * - `globalThis.tailor` / `globalThis.tailordb` container objects\n * - `globalThis.tailor.context.getInvoker` default stub\n * - the platform error classes (`TailorErrors`, `TailorErrorMessage`,\n * `TailorDBFileError`)\n * - the `__tailorRuntimeActive` sentinel flag\n *\n * The per-namespace mock behavior (TailorDB client, workflow, secretmanager, …)\n * is installed on demand by the `xMock()` factories in `./mock`, which run in\n * test context where `vi` *is* available.\n */\n\nimport { createDefaultWorkflowRuntime } from \"./workflow-runtime\";\nimport type { ContextInvoker } from \"../runtime/context\";\nimport type { TailorDBFileErrorCode } from \"../runtime/file\";\n\n// Sentinel set when the tailor-runtime environment is active. setup.ts reads it\n// to decide whether to run its blocked-globals lifecycle and config-secret\n// loading.\nexport const RUNTIME_FLAG_KEY = \"__tailorRuntimeActive\";\n\n// ---------------------------------------------------------------------------\n// Error class mocks\n// ---------------------------------------------------------------------------\n\ninterface TailorErrorItem {\n message: string;\n path: (string | number)[];\n}\n\nclass TailorErrorsMock extends Error {\n errors: TailorErrorItem[];\n\n constructor(errors: TailorErrorItem[]) {\n if (!Array.isArray(errors)) {\n throw new TypeError(\"TailorErrors: errors must be an array\");\n }\n const validated = errors.map((e, i) => {\n if (typeof e.message !== \"string\") {\n throw new TypeError(`TailorErrors: errors[${i}].message must be a string`);\n }\n if (!Array.isArray(e.path)) {\n throw new TypeError(`TailorErrors: errors[${i}].path must be an array`);\n }\n return { message: e.message, path: e.path };\n });\n // Match the PF runtime's TailorErrors serialization, which prefixes the\n // JSON payload with \"TailorErrors: \". Other SDK code (e.g. apply\n // integration fixtures) strips this prefix before JSON.parse.\n super(`TailorErrors: ${JSON.stringify({ errors: validated })}`);\n this.name = \"TailorErrors\";\n this.errors = validated;\n }\n}\n\nclass TailorErrorMessageMock extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"TailorErrorMessage\";\n }\n}\n\nclass TailorDBFileErrorMock extends Error {\n code?: TailorDBFileErrorCode;\n override cause: unknown;\n\n constructor(message: string, code?: TailorDBFileErrorCode, cause?: unknown) {\n super(message);\n this.name = \"TailorDBFileError\";\n this.code = code;\n this.cause = cause;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Base install / cleanup\n// ---------------------------------------------------------------------------\n\n// Stub-only injection. SDK consumers configure invokers at the body level\n// (resolver/executor/workflow `.body()` `invoker` arg) or, for bundled tests,\n// via `vi.spyOn(globalThis.tailor.context, \"getInvoker\")`.\nfunction defaultGetInvoker(): ContextInvoker | null {\n return null;\n}\n\n/**\n * Install the always-present base platform globals (containers, context stub,\n * error classes, runtime flag). Per-namespace mocks are layered on top by the\n * `xMock()` factories in `./mock`.\n * @param global - The global object to install into (typically `globalThis`)\n */\nexport function installPlatformGlobals(global: typeof globalThis): void {\n const g = global as Record<string, unknown>;\n\n g[RUNTIME_FLAG_KEY] = true;\n\n // Containers. Namespace mocks (secretmanager, …) are added to these by the\n // corresponding `xMock()` on acquisition. `workflow` carries a default runner\n // so `.trigger()` runs the real job chain locally without `mockWorkflow()`;\n // `mockWorkflow()` overlays and restores it.\n g.tailor = {\n context: { getInvoker: defaultGetInvoker },\n workflow: createDefaultWorkflowRuntime(),\n };\n g.tailordb = {};\n\n g.TailorErrors = TailorErrorsMock;\n g.TailorErrorMessage = TailorErrorMessageMock;\n g.TailorDBFileError = TailorDBFileErrorMock;\n}\n\n/**\n * Remove the base platform globals (and anything the namespace mocks layered on\n * top, since they live under the same containers).\n * @param global - The global object to clean up (typically `globalThis`)\n */\nexport function cleanupPlatformGlobals(global: typeof globalThis): void {\n const g = global as Record<string, unknown>;\n delete g.tailordb;\n delete g.tailor;\n delete g.TailorErrors;\n delete g.TailorErrorMessage;\n delete g.TailorDBFileError;\n delete g[RUNTIME_FLAG_KEY];\n}\n"],"mappings":";;;;AAgBA,SAAgB,+BAAuD;CACrE,OAAO;EACL,qBAAqB,MAAM,SAAS,iBAAiB,MAAM,IAAI;EAC/D,kBAAkB,MAAM,SAAS,sBAAsB,MAAM,IAAI;EACjE,OAAO,QAAyB;GAC9B,MAAM,IAAI,MACR,wBAAwB,IAAI,wDAC9B;EACF;EACA,SAAS,YAA2B;GAClC,MAAM,IAAI,MACR,6EACF;EACF;CACF;AACF;;;;;;;;;;;;;;;;;;;;;ACNA,MAAa,mBAAmB;AAWhC,IAAM,mBAAN,cAA+B,MAAM;CACnC;CAEA,YAAY,QAA2B;EACrC,IAAI,CAAC,MAAM,QAAQ,MAAM,GACvB,MAAM,IAAI,UAAU,uCAAuC;EAE7D,MAAM,YAAY,OAAO,KAAK,GAAG,MAAM;GACrC,IAAI,OAAO,EAAE,YAAY,UACvB,MAAM,IAAI,UAAU,wBAAwB,EAAE,2BAA2B;GAE3E,IAAI,CAAC,MAAM,QAAQ,EAAE,IAAI,GACvB,MAAM,IAAI,UAAU,wBAAwB,EAAE,wBAAwB;GAExE,OAAO;IAAE,SAAS,EAAE;IAAS,MAAM,EAAE;GAAK;EAC5C,CAAC;EAID,MAAM,iBAAiB,KAAK,UAAU,EAAE,QAAQ,UAAU,CAAC,GAAG;EAC9D,KAAK,OAAO;EACZ,KAAK,SAAS;CAChB;AACF;AAEA,IAAM,yBAAN,cAAqC,MAAM;CACzC,YAAY,SAAiB;EAC3B,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF;AAEA,IAAM,wBAAN,cAAoC,MAAM;CACxC;CACA,AAAS;CAET,YAAY,SAAiB,MAA8B,OAAiB;EAC1E,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,KAAK,QAAQ;CACf;AACF;AASA,SAAS,oBAA2C;CAClD,OAAO;AACT;;;;;;;AAQA,SAAgB,uBAAuB,QAAiC;CACtE,MAAM,IAAI;CAEV,EAAE,oBAAoB;CAMtB,EAAE,SAAS;EACT,SAAS,EAAE,YAAY,kBAAkB;EACzC,UAAU,6BAA6B;CACzC;CACA,EAAE,WAAW,CAAC;CAEd,EAAE,eAAe;CACjB,EAAE,qBAAqB;CACvB,EAAE,oBAAoB;AACxB;;;;;;AAOA,SAAgB,uBAAuB,QAAiC;CACtE,MAAM,IAAI;CACV,OAAO,EAAE;CACT,OAAO,EAAE;CACT,OAAO,EAAE;CACT,OAAO,EAAE;CACT,OAAO,EAAE;CACT,OAAO,EAAE;AACX"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"iconv-DreIffeM.mjs","names":[],"sources":["../src/runtime/iconv.ts"],"sourcesContent":["/**\n * Character encoding conversion utilities.\n *\n * Thin typed wrapper around the platform-provided `tailor.iconv` runtime API.\n * At runtime this delegates to `globalThis.tailor.iconv`, which is provided by\n * the Tailor Platform Function runtime. Use `
|
|
1
|
+
{"version":3,"file":"iconv-DreIffeM.mjs","names":[],"sources":["../src/runtime/iconv.ts"],"sourcesContent":["/**\n * Character encoding conversion utilities.\n *\n * Thin typed wrapper around the platform-provided `tailor.iconv` runtime API.\n * At runtime this delegates to `globalThis.tailor.iconv`, which is provided by\n * the Tailor Platform Function runtime. Use `mockIconv` from\n * `@tailor-platform/sdk/vitest` to mock these calls in unit tests.\n * @example\n * import { iconv } from \"@tailor-platform/sdk/runtime\";\n *\n * const utf8 = iconv.convert(sjisBuffer, \"Shift_JIS\", \"UTF-8\"); // string\n * const sjis = iconv.convert(\"こんにちは\", \"UTF-8\", \"Shift_JIS\"); // Uint8Array\n *\n * const conv = new iconv.Iconv(\"Shift_JIS\", \"UTF-8\");\n * const out = conv.convert(sjisBuffer);\n */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\n/** Instance methods exposed by `tailor.iconv.Iconv`. */\nexport interface IconvInstance {\n convert(input: string | Uint8Array | ArrayBuffer): string | Uint8Array;\n}\n\n/** Constructor shape for `tailor.iconv.Iconv`. */\nexport interface IconvConstructor {\n new (fromEncoding: string, toEncoding: string): IconvInstance;\n}\n\n/**\n * Platform API surface for `tailor.iconv`. Describes the shape the platform\n * runtime injects on `globalThis.tailor.iconv` so the wrapper and ambient\n * globals stay in sync.\n *\n * Each method below is also re-exported as a top-level named export from this\n * module (e.g. `convert`, `decode`, `encode`) so callers can either\n * `import * as iconv from \"@tailor-platform/sdk/runtime/iconv\"` or pick\n * individual methods.\n */\nexport interface TailorIconvAPI {\n /**\n * Convert a string or buffer between encodings.\n * @param str - Input data to convert\n * @param fromEncoding - Source encoding name\n * @param toEncoding - Target encoding name\n * @returns `string` when `toEncoding` is `\"UTF8\"` or `\"UTF-8\"`, otherwise `Uint8Array`.\n */\n convert<T extends string>(\n str: string | Uint8Array | ArrayBuffer,\n fromEncoding: string,\n toEncoding: T,\n ): T extends \"UTF8\" | \"UTF-8\" ? string : Uint8Array;\n\n /**\n * Convert a buffer between encodings.\n * @param buffer - Input bytes to convert\n * @param fromEncoding - Source encoding name\n * @param toEncoding - Target encoding name\n * @returns `string` when `toEncoding` is `\"UTF8\"` or `\"UTF-8\"`, otherwise `Uint8Array`.\n */\n convertBuffer<T extends string>(\n buffer: Uint8Array | ArrayBuffer,\n fromEncoding: string,\n toEncoding: T,\n ): T extends \"UTF8\" | \"UTF-8\" ? string : Uint8Array;\n\n /**\n * Decode a buffer to a UTF-8 string using the given source encoding.\n * @param buffer - Input bytes\n * @param encoding - Source encoding name\n * @returns Decoded UTF-8 string\n */\n decode(buffer: Uint8Array | ArrayBuffer, encoding: string): string;\n\n /**\n * Encode a UTF-8 string into the given target encoding.\n * @param str - Input string\n * @param encoding - Target encoding name\n * @returns `string` when `encoding` is `\"UTF8\"` or `\"UTF-8\"`, otherwise `Uint8Array`.\n */\n encode<T extends string>(\n str: string,\n encoding: T,\n ): T extends \"UTF8\" | \"UTF-8\" ? string : Uint8Array;\n\n /**\n * Returns the list of supported encoding names.\n * @returns Array of encoding names supported by the platform iconv runtime\n */\n encodings(): string[];\n\n /** Constructor for the stateful {@link Iconv} converter. */\n Iconv: IconvConstructor;\n}\n\nconst api = (): TailorIconvAPI =>\n (globalThis as { tailor: { iconv: TailorIconvAPI } }).tailor.iconv;\n\n/**\n * See {@link TailorIconvAPI.convert}.\n * @param args - Forwarded to {@link TailorIconvAPI.convert}\n * @returns `string` when `toEncoding` is `\"UTF8\"` or `\"UTF-8\"`, otherwise `Uint8Array`.\n */\nexport const convert: TailorIconvAPI[\"convert\"] = (...args) => api().convert(...args);\n\n/**\n * See {@link TailorIconvAPI.convertBuffer}.\n * @param args - Forwarded to {@link TailorIconvAPI.convertBuffer}\n * @returns `string` when `toEncoding` is `\"UTF8\"` or `\"UTF-8\"`, otherwise `Uint8Array`.\n */\nexport const convertBuffer: TailorIconvAPI[\"convertBuffer\"] = (...args) =>\n api().convertBuffer(...args);\n\n/**\n * See {@link TailorIconvAPI.decode}.\n * @param args - Forwarded to {@link TailorIconvAPI.decode}\n * @returns Decoded UTF-8 string\n */\nexport const decode: TailorIconvAPI[\"decode\"] = (...args) => api().decode(...args);\n\n/**\n * See {@link TailorIconvAPI.encode}.\n * @param args - Forwarded to {@link TailorIconvAPI.encode}\n * @returns `string` when `encoding` is `\"UTF8\"` or `\"UTF-8\"`, otherwise `Uint8Array`.\n */\nexport const encode: TailorIconvAPI[\"encode\"] = (...args) => api().encode(...args);\n\n/**\n * See {@link TailorIconvAPI.encodings}.\n * @returns Array of encoding names supported by the platform iconv runtime\n */\nexport const encodings: TailorIconvAPI[\"encodings\"] = () => api().encodings();\n\n/**\n * Stateful converter for repeated conversions between a fixed encoding pair.\n * Compatible with the `node-iconv` API surface.\n */\nexport class Iconv {\n private impl: IconvInstance;\n\n constructor(fromEncoding: string, toEncoding: string) {\n this.impl = new (api().Iconv)(fromEncoding, toEncoding);\n }\n\n /**\n * Convert input using this converter's fixed encoding pair.\n * @param input - Bytes or string to convert\n * @returns Encoded output (string for UTF-8 targets, otherwise `Uint8Array`).\n */\n convert(input: string | Uint8Array | ArrayBuffer): string | Uint8Array {\n return this.impl.convert(input);\n }\n}\n"],"mappings":";;;;;;;;;;;;AA+FA,MAAM,YACH,WAAqD,OAAO;;;;;;AAO/D,MAAa,WAAsC,GAAG,SAAS,IAAI,EAAE,QAAQ,GAAG,IAAI;;;;;;AAOpF,MAAa,iBAAkD,GAAG,SAChE,IAAI,EAAE,cAAc,GAAG,IAAI;;;;;;AAO7B,MAAa,UAAoC,GAAG,SAAS,IAAI,EAAE,OAAO,GAAG,IAAI;;;;;;AAOjF,MAAa,UAAoC,GAAG,SAAS,IAAI,EAAE,OAAO,GAAG,IAAI;;;;;AAMjF,MAAa,kBAA+C,IAAI,EAAE,UAAU;;;;;AAM5E,IAAa,QAAb,MAAmB;CACjB,AAAQ;CAER,YAAY,cAAsB,YAAoB;EACpD,KAAK,OAAO,KAAK,IAAI,GAAE,MAAO,cAAc,UAAU;CACxD;;;;;;CAOA,QAAQ,OAA+D;EACrE,OAAO,KAAK,KAAK,QAAQ,KAAK;CAChC;AACF"}
|
|
@@ -6,7 +6,7 @@ declare namespace iconv_d_exports {
|
|
|
6
6
|
*
|
|
7
7
|
* Thin typed wrapper around the platform-provided `tailor.iconv` runtime API.
|
|
8
8
|
* At runtime this delegates to `globalThis.tailor.iconv`, which is provided by
|
|
9
|
-
* the Tailor Platform Function runtime. Use `
|
|
9
|
+
* the Tailor Platform Function runtime. Use `mockIconv` from
|
|
10
10
|
* `@tailor-platform/sdk/vitest` to mock these calls in unit tests.
|
|
11
11
|
* @example
|
|
12
12
|
* import { iconv } from "@tailor-platform/sdk/runtime";
|
|
@@ -119,4 +119,4 @@ declare class Iconv {
|
|
|
119
119
|
}
|
|
120
120
|
//#endregion
|
|
121
121
|
export { convert as a, encode as c, TailorIconvAPI as i, encodings as l, IconvConstructor as n, convertBuffer as o, IconvInstance as r, decode as s, Iconv as t, iconv_d_exports as u };
|
|
122
|
-
//# sourceMappingURL=iconv-
|
|
122
|
+
//# sourceMappingURL=iconv-kwrmd1U_.d.mts.map
|
|
@@ -5,7 +5,7 @@ declare namespace idp_d_exports {
|
|
|
5
5
|
* IDP (Identity Provider) utilities.
|
|
6
6
|
*
|
|
7
7
|
* Thin typed wrapper around the platform-provided `tailor.idp` runtime API.
|
|
8
|
-
* At runtime this delegates to `globalThis.tailor.idp`. Use `
|
|
8
|
+
* At runtime this delegates to `globalThis.tailor.idp`. Use `mockIdp` from
|
|
9
9
|
* `@tailor-platform/sdk/vitest` to mock these calls in unit tests.
|
|
10
10
|
* @example
|
|
11
11
|
* import { idp } from "@tailor-platform/sdk/runtime";
|
|
@@ -157,4 +157,4 @@ declare class Client {
|
|
|
157
157
|
}
|
|
158
158
|
//#endregion
|
|
159
159
|
export { IdpClientInstance as a, SendPasswordResetEmailInput as c, User as d, UserQuery as f, IdpClientConstructor as i, TailorIdpAPI as l, ClientConfig as n, ListUsersOptions as o, idp_d_exports as p, CreateUserInput as r, ListUsersResponse as s, Client as t, UpdateUserInput as u };
|
|
160
|
-
//# sourceMappingURL=idp-
|
|
160
|
+
//# sourceMappingURL=idp-BlBPtXJ-.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"idp-Ch95ag8h.mjs","names":["#impl"],"sources":["../src/runtime/idp.ts"],"sourcesContent":["/**\n * IDP (Identity Provider) utilities.\n *\n * Thin typed wrapper around the platform-provided `tailor.idp` runtime API.\n * At runtime this delegates to `globalThis.tailor.idp`. Use `
|
|
1
|
+
{"version":3,"file":"idp-Ch95ag8h.mjs","names":["#impl"],"sources":["../src/runtime/idp.ts"],"sourcesContent":["/**\n * IDP (Identity Provider) utilities.\n *\n * Thin typed wrapper around the platform-provided `tailor.idp` runtime API.\n * At runtime this delegates to `globalThis.tailor.idp`. Use `mockIdp` from\n * `@tailor-platform/sdk/vitest` to mock these calls in unit tests.\n * @example\n * import { idp } from \"@tailor-platform/sdk/runtime\";\n *\n * const client = new idp.Client({ namespace: \"my-namespace\" });\n * const { users } = await client.users({ first: 10 });\n */\n\n/** Configuration object for {@link Client}. */\nexport interface ClientConfig {\n namespace: string;\n}\n\n/** User record returned by IDP operations. */\nexport interface User {\n id: string;\n name: string;\n disabled: boolean;\n createdAt?: string;\n}\n\n/** Filter options for {@link Client.users}. */\nexport interface UserQuery {\n /** Filter by user IDs */\n ids?: string[];\n /** Filter by user names */\n names?: string[];\n}\n\n/** Pagination/filter options for {@link Client.users}. */\nexport interface ListUsersOptions {\n /** Maximum number of users to return */\n first?: number;\n /** Page token for pagination */\n after?: string;\n /** Query filter for users */\n query?: UserQuery;\n}\n\n/** Response shape for {@link Client.users}. */\nexport interface ListUsersResponse {\n users: User[];\n nextPageToken: string | null;\n totalCount: number;\n}\n\n/** Input for {@link Client.createUser}. */\nexport interface CreateUserInput {\n /** The user's name (typically email) */\n name: string;\n /** The user's password. If omitted, the user is created without a password (cannot log in with any password). */\n password?: string;\n /** Whether the user is disabled */\n disabled?: boolean;\n}\n\n/** Input for {@link Client.updateUser}. */\nexport interface UpdateUserInput {\n /** The user's ID */\n id: string;\n /** New name for the user */\n name?: string;\n /** New password for the user. Cannot be used with clearPassword. */\n password?: string;\n /** If true, remove the user's password. Cannot be used with password. */\n clearPassword?: boolean;\n /** New disabled status for the user */\n disabled?: boolean;\n}\n\n/** Input for {@link Client.sendPasswordResetEmail}. */\nexport interface SendPasswordResetEmailInput {\n /** The ID of the user */\n userId: string;\n /** The URI to redirect to after password reset */\n redirectUri: string;\n /** The sender display name. Defaults to 'Tailor Platform IdP'. */\n fromName?: string;\n /** The email subject line. Defaults to the localized default subject. */\n subject?: string;\n}\n\n/** Instance methods exposed by `tailor.idp.Client`. */\nexport interface IdpClientInstance {\n users(options?: ListUsersOptions): Promise<ListUsersResponse>;\n user(userId: string): Promise<User>;\n userByName(name: string): Promise<User>;\n createUser(input: CreateUserInput): Promise<User>;\n updateUser(input: UpdateUserInput): Promise<User>;\n deleteUser(userId: string): Promise<boolean>;\n sendPasswordResetEmail(input: SendPasswordResetEmailInput): Promise<boolean>;\n}\n\n/**\n * Constructor shape for `tailor.idp.Client`.\n * @internal\n */\nexport interface IdpClientConstructor {\n new (config: ClientConfig): IdpClientInstance;\n}\n\n/**\n * Platform API surface for `tailor.idp`. Describes the shape the platform\n * runtime injects on `globalThis.tailor.idp`.\n * @internal\n */\nexport interface TailorIdpAPI {\n Client: IdpClientConstructor;\n}\n\n/**\n * IDP Client for user management operations.\n *\n * Wraps the platform-provided `tailor.idp.Client` and exposes the same surface.\n */\nexport class Client {\n #impl: IdpClientInstance;\n\n constructor(config: ClientConfig) {\n this.#impl = new (globalThis as { tailor: { idp: TailorIdpAPI } }).tailor.idp.Client(config);\n }\n\n /**\n * List users in the namespace with optional filtering and pagination.\n * @param options - Pagination and filter options\n * @returns Page of users with `nextPageToken` and `totalCount`\n */\n users(options?: ListUsersOptions): Promise<ListUsersResponse> {\n return this.#impl.users(options);\n }\n\n /**\n * Get a user by ID.\n * @param userId - IDP user ID\n * @returns The matching user\n */\n user(userId: string): Promise<User> {\n return this.#impl.user(userId);\n }\n\n /**\n * Get a user by name.\n * @param name - IDP user name\n * @returns The matching user\n */\n userByName(name: string): Promise<User> {\n return this.#impl.userByName(name);\n }\n\n /**\n * Create a new user.\n * @param input - User attributes\n * @returns The newly created user\n */\n createUser(input: CreateUserInput): Promise<User> {\n return this.#impl.createUser(input);\n }\n\n /**\n * Update an existing user.\n * @param input - User ID plus attributes to update\n * @returns The updated user\n */\n updateUser(input: UpdateUserInput): Promise<User> {\n return this.#impl.updateUser(input);\n }\n\n /**\n * Delete a user by ID.\n * @param userId - IDP user ID\n * @returns `true` when the user was deleted\n */\n deleteUser(userId: string): Promise<boolean> {\n return this.#impl.deleteUser(userId);\n }\n\n /**\n * Send a password reset email to a user.\n * @param input - Target user ID and redirect URI\n * @returns `true` when the email was queued\n */\n sendPasswordResetEmail(input: SendPasswordResetEmailInput): Promise<boolean> {\n return this.#impl.sendPasswordResetEmail(input);\n }\n}\n"],"mappings":";;;;;;;;;;AAwHA,IAAa,SAAb,MAAoB;CAClB;CAEA,YAAY,QAAsB;EAChC,KAAKA,QAAQ,IAAK,WAAiD,OAAO,IAAI,OAAO,MAAM;CAC7F;;;;;;CAOA,MAAM,SAAwD;EAC5D,OAAO,KAAKA,MAAM,MAAM,OAAO;CACjC;;;;;;CAOA,KAAK,QAA+B;EAClC,OAAO,KAAKA,MAAM,KAAK,MAAM;CAC/B;;;;;;CAOA,WAAW,MAA6B;EACtC,OAAO,KAAKA,MAAM,WAAW,IAAI;CACnC;;;;;;CAOA,WAAW,OAAuC;EAChD,OAAO,KAAKA,MAAM,WAAW,KAAK;CACpC;;;;;;CAOA,WAAW,OAAuC;EAChD,OAAO,KAAKA,MAAM,WAAW,KAAK;CACpC;;;;;;CAOA,WAAW,QAAkC;EAC3C,OAAO,KAAKA,MAAM,WAAW,MAAM;CACrC;;;;;;CAOA,uBAAuB,OAAsD;EAC3E,OAAO,KAAKA,MAAM,uBAAuB,KAAK;CAChD;AACF"}
|
|
@@ -211,6 +211,14 @@ type ResolverConfig = ReturnType<typeof createResolver<any, any>>;
|
|
|
211
211
|
//#region src/types/resolver.d.ts
|
|
212
212
|
type QueryType = Resolver["operation"];
|
|
213
213
|
//#endregion
|
|
214
|
+
//#region src/configure/services/workflow/test-env-key.d.ts
|
|
215
|
+
/**
|
|
216
|
+
* Env-var fallback read by `.trigger()` when `mockWorkflow().setEnv()` is unset.
|
|
217
|
+
* @deprecated Use `mockWorkflow().setEnv()` from `@tailor-platform/sdk/vitest`.
|
|
218
|
+
* @internal
|
|
219
|
+
*/
|
|
220
|
+
declare const WORKFLOW_TEST_ENV_KEY = "TAILOR_TEST_WORKFLOW_ENV";
|
|
221
|
+
//#endregion
|
|
214
222
|
//#region src/configure/services/workflow/job.d.ts
|
|
215
223
|
/**
|
|
216
224
|
* Context object passed as the second argument to workflow job body functions.
|
|
@@ -248,12 +256,6 @@ interface WorkflowJob<Name extends string = string, Input = undefined, Output =
|
|
|
248
256
|
trigger: [Input] extends [undefined] ? () => Promise<Awaited<Output>> : (input: Input) => Promise<Awaited<Output>>;
|
|
249
257
|
body: (input: Input, context: WorkflowJobContext) => Output | Promise<Output>;
|
|
250
258
|
}
|
|
251
|
-
/**
|
|
252
|
-
* Env-var fallback read by `.trigger()` when `workflowMock.setEnv()` is unset.
|
|
253
|
-
* Kept for backward compatibility.
|
|
254
|
-
* @deprecated Use `workflowMock.setEnv()` from `@tailor-platform/sdk/vitest`.
|
|
255
|
-
*/
|
|
256
|
-
declare const WORKFLOW_TEST_ENV_KEY = "TAILOR_TEST_WORKFLOW_ENV";
|
|
257
259
|
interface CreateWorkflowJobConfig<Name extends string, I, O> {
|
|
258
260
|
readonly name: Name;
|
|
259
261
|
readonly body: JobBody<I, O>;
|
|
@@ -1219,5 +1221,5 @@ declare namespace t {
|
|
|
1219
1221
|
type infer<T> = TailorOutput<T>;
|
|
1220
1222
|
}
|
|
1221
1223
|
//#endregion
|
|
1222
|
-
export { authAccessTokenIssuedTrigger as $, IncomingWebhookResponseConfig as A, TailorField as At, AuthAccessTokenRevokedArgs as B, defineWaitPoint as C,
|
|
1223
|
-
//# sourceMappingURL=index-
|
|
1224
|
+
export { authAccessTokenIssuedTrigger as $, IncomingWebhookResponseConfig as A, TailorField as At, AuthAccessTokenRevokedArgs as B, defineWaitPoint as C, WORKFLOW_TEST_ENV_KEY as Ct, IncomingWebhookArgs as D, defineAuth as Dt, Trigger as E, AuthInvoker as Et, ScheduleTrigger as F, IdpUserTrigger as G, IdpUserArgs as H, scheduleTrigger as I, RecordDeletedArgs as J, IdpUserUpdatedArgs as K, AuthAccessTokenArgs as L, IncomingWebhookTriggerOptions as M, MachineUserNameRegistry as Mt, incomingWebhookTrigger as N, IncomingWebhookRequest as O, IdpName as Ot, ScheduleArgs as P, TailorDBTrigger as Q, AuthAccessTokenIssuedArgs as R, WaitPointInstance as S, createWorkflowJob as St, createExecutor as T, createResolver as Tt, IdpUserCreatedArgs as U, AuthAccessTokenTrigger as V, IdpUserDeletedArgs as W, ResolverExecutedArgs as X, RecordUpdatedArgs as Y, ResolverExecutedTrigger as Z, defineIdp as _, Workflow as _t, defineGenerators as a, idpUserTrigger as at, unsafeAllowAllIdPPermission as b, WorkflowJob as bt, HttpAdapterGraphQLRequest as c, recordDeletedTrigger as ct, HttpAdapterInputFn as d, resolverExecutedTrigger as dt, authAccessTokenRefreshedTrigger as et, HttpAdapterOutputFn as f, FunctionOperation as ft, defineSecretManager as g, WorkflowOperation as gt, createHttpAdapter as h, WebhookOperation as ht, defineConfig as i, idpUserDeletedTrigger as it, IncomingWebhookTrigger as j, MachineUserName as jt, IncomingWebhookResponse as k, IdpNameRegistry as kt, HttpAdapterGraphQLResponse as l, recordTrigger as lt, HttpAdapterResponse as m, Operation as mt, output as n, authAccessTokenTrigger as nt, definePlugins as o, idpUserUpdatedTrigger as ot, HttpAdapterRequest as p, GqlOperation as pt, RecordCreatedArgs as q, t as r, idpUserCreatedTrigger as rt, HttpAdapter as s, recordCreatedTrigger as st, infer as t, authAccessTokenRevokedTrigger as tt, HttpAdapterInput as u, recordUpdatedTrigger as ut, IdPPermission as v, WorkflowConfig as vt, defineWaitPoints as w, QueryType as wt, defineStaticWebSite as x, WorkflowJobContext as xt, IdPPermissionCondition as y, createWorkflow as yt, AuthAccessTokenRefreshedArgs as z };
|
|
1225
|
+
//# sourceMappingURL=index-Cr6ufjZ5.d.mts.map
|
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import { t as TailorAuthconnectionAPI } from "./authconnection-
|
|
1
|
+
import { t as TailorAuthconnectionAPI } from "./authconnection-BIYzEh2p.mjs";
|
|
2
2
|
import { r as TailorContextAPI } from "./context-CUBwSBq4.mjs";
|
|
3
|
-
import { f as TailorDBFileAPI } from "./file-
|
|
4
|
-
import { i as TailorIconvAPI } from "./iconv-
|
|
5
|
-
import { l as TailorIdpAPI } from "./idp-
|
|
6
|
-
import { t as TailorSecretmanagerAPI } from "./secretmanager-
|
|
7
|
-
import { n as TailorWorkflowAPI } from "./workflow-
|
|
3
|
+
import { f as TailorDBFileAPI } from "./file-BzK8z3X-.mjs";
|
|
4
|
+
import { i as TailorIconvAPI } from "./iconv-kwrmd1U_.mjs";
|
|
5
|
+
import { l as TailorIdpAPI } from "./idp-BlBPtXJ-.mjs";
|
|
6
|
+
import { t as TailorSecretmanagerAPI } from "./secretmanager-CKLB3wAQ.mjs";
|
|
7
|
+
import { n as TailorWorkflowAPI } from "./workflow-CMamswkK.mjs";
|
|
8
8
|
|
|
9
9
|
//#region src/runtime/index.d.ts
|
|
10
10
|
/** SQL command type recorded on a {@link TailordbQueryResult}. */
|
|
@@ -43,4 +43,4 @@ interface TailordbRuntime {
|
|
|
43
43
|
}
|
|
44
44
|
//#endregion
|
|
45
45
|
export { TailordbQueryResult as a, TailordbCommandType as i, TailordbClientConstructor as n, TailordbRuntime as o, TailordbClientInstance as r, TailorRuntime as t };
|
|
46
|
-
//# sourceMappingURL=index-
|
|
46
|
+
//# sourceMappingURL=index-DRhMpdnA.d.mts.map
|
|
@@ -1,15 +1,9 @@
|
|
|
1
1
|
|
|
2
2
|
import { t as brandValue } from "./brand-DlnJ375c.mjs";
|
|
3
|
-
import { n as
|
|
3
|
+
import { n as dispatchTriggerJob, o as registerJob } from "./registry-D0uB0OrK.mjs";
|
|
4
4
|
|
|
5
5
|
//#region src/configure/services/workflow/job.ts
|
|
6
6
|
/**
|
|
7
|
-
* Env-var fallback read by `.trigger()` when `workflowMock.setEnv()` is unset.
|
|
8
|
-
* Kept for backward compatibility.
|
|
9
|
-
* @deprecated Use `workflowMock.setEnv()` from `@tailor-platform/sdk/vitest`.
|
|
10
|
-
*/
|
|
11
|
-
const WORKFLOW_TEST_ENV_KEY = "TAILOR_TEST_WORKFLOW_ENV";
|
|
12
|
-
/**
|
|
13
7
|
* Create a workflow job definition.
|
|
14
8
|
*
|
|
15
9
|
* All jobs must be named exports from the workflow file.
|
|
@@ -42,22 +36,19 @@ const WORKFLOW_TEST_ENV_KEY = "TAILOR_TEST_WORKFLOW_ENV";
|
|
|
42
36
|
* },
|
|
43
37
|
* });
|
|
44
38
|
*/
|
|
45
|
-
/* @__NO_SIDE_EFFECTS__ */
|
|
46
39
|
function createWorkflowJob(config) {
|
|
47
40
|
const body = config.body;
|
|
41
|
+
if (!process.env.TAILOR_PLATFORM_BUNDLE) registerJob(config.name, body);
|
|
42
|
+
const trigger = process.env.TAILOR_PLATFORM_BUNDLE ? async () => {
|
|
43
|
+
throw new Error("This workflow job's .trigger() is rewritten at build time and is unavailable in the bundle");
|
|
44
|
+
} : async (args) => await dispatchTriggerJob(config.name, args);
|
|
48
45
|
return brandValue({
|
|
49
46
|
name: config.name,
|
|
50
|
-
trigger
|
|
51
|
-
const fromGlobal = readWorkflowTestEnv();
|
|
52
|
-
return await body(args, {
|
|
53
|
-
env: fromGlobal !== void 0 ? { ...fromGlobal } : JSON.parse(process.env["TAILOR_TEST_WORKFLOW_ENV"] || "{}"),
|
|
54
|
-
invoker: null
|
|
55
|
-
});
|
|
56
|
-
},
|
|
47
|
+
trigger,
|
|
57
48
|
body
|
|
58
49
|
}, "workflow-job");
|
|
59
50
|
}
|
|
60
51
|
|
|
61
52
|
//#endregion
|
|
62
|
-
export { createWorkflowJob as
|
|
63
|
-
//# sourceMappingURL=job-
|
|
53
|
+
export { createWorkflowJob as t };
|
|
54
|
+
//# sourceMappingURL=job-BpsFXPbi.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"job-BpsFXPbi.mjs","names":[],"sources":["../src/configure/services/workflow/job.ts"],"sourcesContent":["import { brandValue } from \"@/utils/brand\";\nimport { dispatchTriggerJob, registerJob, type RegisteredJobBody } from \"./registry\";\nimport type { TailorEnv } from \"@/types/env\";\nimport type { JsonCompatible } from \"@/types/helpers\";\nimport type { TailorInvoker } from \"@/types/user\";\n\n/**\n * Context object passed as the second argument to workflow job body functions.\n */\nexport type WorkflowJobContext = {\n env: TailorEnv;\n invoker?: TailorInvoker;\n};\n\n/**\n * The body function type for a workflow job.\n * Resolves to the callable signature when `I` / `O` are JsonValue-compatible,\n * or to a template-literal error string that surfaces at the `body:` property.\n */\ntype JobBody<I, O> = [null] extends [I]\n ? \"ERROR: Input cannot be null at the top level\"\n : [I] extends [undefined]\n ? [O] extends [JsonCompatible<O> | undefined | void]\n ? (input: I, context: WorkflowJobContext) => O | Promise<O>\n : \"ERROR: Output must be JsonValue-compatible (plain objects/arrays; no class instances or functions)\"\n : [undefined] extends [I]\n ? \"ERROR: Input cannot include undefined at the top level\"\n : [I] extends [JsonCompatible<I>]\n ? [O] extends [JsonCompatible<O> | undefined | void]\n ? (input: I, context: WorkflowJobContext) => O | Promise<O>\n : \"ERROR: Output must be JsonValue-compatible (plain objects/arrays; no class instances or functions)\"\n : \"ERROR: Input must be JsonValue-compatible (plain objects/arrays; no class instances or functions)\";\n\n/**\n * WorkflowJob represents a job that can be triggered in a workflow.\n *\n * Type constraints:\n * - Input: Must be JsonValue-compatible (plain objects/arrays; no class instances or functions) or undefined.\n * - Output: Must be JsonValue-compatible (plain objects/arrays; no class instances or functions), undefined, or void.\n * - Trigger returns `Awaited<Output>` as-is (no Jsonify transformation).\n */\nexport interface WorkflowJob<Name extends string = string, Input = undefined, Output = undefined> {\n name: Name;\n /**\n * Trigger this job with the given input. Returns a Promise that resolves\n * to the job's output value.\n * @example\n * body: async (input) => {\n * const a = await jobA.trigger({ id: input.id });\n * const b = await jobB.trigger({ id: input.id });\n * return { a, b };\n * }\n */\n trigger: [Input] extends [undefined]\n ? () => Promise<Awaited<Output>>\n : (input: Input) => Promise<Awaited<Output>>;\n body: (input: Input, context: WorkflowJobContext) => Output | Promise<Output>;\n}\n\nexport { WORKFLOW_TEST_ENV_KEY } from \"./test-env-key\";\n\ninterface CreateWorkflowJobConfig<Name extends string, I, O> {\n readonly name: Name;\n readonly body: JobBody<I, O>;\n}\n\n/**\n * Create a workflow job definition.\n *\n * All jobs must be named exports from the workflow file.\n * Job names must be unique across the entire project.\n *\n * Input and output must be JsonValue-compatible (primitives, plain objects, arrays).\n * Functions and objects with a `toJSON` method are rejected at the type level;\n * class instances exposing methods are rejected via the property walk.\n * @param config - Job configuration with name and body function.\n * @param config.name - Unique job name across the project.\n * @param config.body - Async function that processes the job input.\n * @returns A WorkflowJob that can be triggered from other jobs.\n * @example\n * // Simple job with async body:\n * export const fetchData = createWorkflowJob({\n * name: \"fetch-data\",\n * body: async (input: { id: string }) => {\n * const db = getDB(\"tailordb\");\n * return await db.selectFrom(\"Table\").selectAll().where(\"id\", \"=\", input.id).executeTakeFirst();\n * },\n * });\n * @example\n * // Orchestrator job that fans out to other jobs.\n * export const orchestrate = createWorkflowJob({\n * name: \"orchestrate\",\n * body: async (input: { orderId: string }) => {\n * const inventory = await checkInventory.trigger({ orderId: input.orderId });\n * const payment = await processPayment.trigger({ orderId: input.orderId });\n * return { inventory, payment };\n * },\n * });\n */\nexport function createWorkflowJob<const Name extends string, I = undefined, O = undefined>(\n config: CreateWorkflowJobConfig<Name, I, O>,\n): WorkflowJob<Name, I, Awaited<O>> {\n const body = config.body as (input: I, context: WorkflowJobContext) => O | Promise<O>;\n\n // Test-only registry/trigger shim; the platform bundle sets the flag so it is DCE'd.\n if (!process.env.TAILOR_PLATFORM_BUNDLE) {\n registerJob(config.name, body as RegisteredJobBody);\n }\n\n const trigger = process.env.TAILOR_PLATFORM_BUNDLE\n ? async () => {\n throw new Error(\n \"This workflow job's .trigger() is rewritten at build time and is unavailable in the bundle\",\n );\n }\n : async (args?: unknown) => (await dispatchTriggerJob(config.name, args)) as Awaited<O>;\n\n return brandValue(\n { name: config.name, trigger, body } as WorkflowJob<Name, I, Awaited<O>>,\n \"workflow-job\",\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmGA,SAAgB,kBACd,QACkC;CAClC,MAAM,OAAO,OAAO;CAGpB,IAAI,CAAC,QAAQ,IAAI,wBACf,YAAY,OAAO,MAAM,IAAyB;CAGpD,MAAM,UAAU,QAAQ,IAAI,yBACxB,YAAY;EACV,MAAM,IAAI,MACR,4FACF;CACF,IACA,OAAO,SAAoB,MAAM,mBAAmB,OAAO,MAAM,IAAI;CAEzE,OAAO,WACL;EAAE,MAAM,OAAO;EAAM;EAAS;CAAK,GACnC,cACF;AACF"}
|