@tailor-platform/sdk 2.0.0-next.0 → 2.0.0-next.2
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 +161 -0
- package/dist/application-Dtqap5jM.mjs +3 -0
- package/dist/{client-CobIRHl-.mjs → application-XuMWK4eq.mjs} +5869 -25
- package/dist/application-XuMWK4eq.mjs.map +1 -0
- package/dist/{assert-CKfwrmCV.mjs → assert-DBxo8jPo.mjs} +1 -2
- package/dist/{assert-CKfwrmCV.mjs.map → assert-DBxo8jPo.mjs.map} +1 -1
- package/dist/{authconnection-D8SJGMpj.mjs → authconnection-D2MhtTN5.mjs} +2 -3
- package/dist/{authconnection-D8SJGMpj.mjs.map → authconnection-D2MhtTN5.mjs.map} +1 -1
- package/dist/{authconnection-BIYzEh2p.d.mts → authconnection-DvUQAjQS.d.mts} +1 -1
- package/dist/{brand-DlnJ375c.mjs → brand-Eo4pLXPJ.mjs} +1 -2
- package/dist/{brand-DlnJ375c.mjs.map → brand-Eo4pLXPJ.mjs.map} +1 -1
- package/dist/cli/index.mjs +241 -237
- package/dist/cli/index.mjs.map +1 -1
- package/dist/cli/lib.d.mts +547 -620
- package/dist/cli/lib.mjs +9 -11
- package/dist/cli/lib.mjs.map +1 -1
- package/dist/completion/zsh-worker.zsh +4108 -0
- package/dist/configure/index.d.mts +9 -7
- package/dist/configure/index.mjs +76 -40
- package/dist/configure/index.mjs.map +1 -1
- package/dist/{context-s0lxhu8_.mjs → context-Bd266-ru.mjs} +2 -3
- package/dist/context-Bd266-ru.mjs.map +1 -0
- package/dist/{context-CUBwSBq4.d.mts → context-C2lEi9uw.d.mts} +7 -28
- package/dist/{crashreport-D1wKBJ8N.mjs → crashreport-BMWcxeSE.mjs} +1 -2
- package/dist/{crashreport-BhD0y14F.mjs → crashreport-DFq-vsU0.mjs} +21 -14
- package/dist/{crashreport-BhD0y14F.mjs.map → crashreport-DFq-vsU0.mjs.map} +1 -1
- package/dist/{enum-constants-C7DaWeQo.mjs → enum-constants-j9QBF0cB.mjs} +1 -2
- package/dist/enum-constants-j9QBF0cB.mjs.map +1 -0
- package/dist/{errors-EsY4XO6O.mjs → errors-Dtf2WPaW.mjs} +1 -2
- package/dist/{errors-EsY4XO6O.mjs.map → errors-Dtf2WPaW.mjs.map} +1 -1
- package/dist/{field-C4zdJLW5.mjs → field-DOsJCPFa.mjs} +1 -2
- package/dist/field-DOsJCPFa.mjs.map +1 -0
- package/dist/{file-B58Dm-2P.mjs → file-BbdFGdMV.mjs} +3 -12
- package/dist/file-BbdFGdMV.mjs.map +1 -0
- package/dist/{file-BzK8z3X-.d.mts → file-Dq3NIt_F.d.mts} +3 -42
- package/dist/{file-utils-BHPxPXmn.mjs → file-utils-CYZnO1pX.mjs} +6 -7
- package/dist/file-utils-CYZnO1pX.mjs.map +1 -0
- package/dist/{globals-ByrCoDip.mjs → globals-Cf0sxIt8.mjs} +53 -5
- package/dist/globals-Cf0sxIt8.mjs.map +1 -0
- package/dist/http-adapter.generated-DFsXDdm5.d.mts +581 -0
- package/dist/{iconv-kwrmd1U_.d.mts → iconv-Co-TOPuH.d.mts} +1 -1
- package/dist/{iconv-DreIffeM.mjs → iconv-D2vi8G36.mjs} +2 -3
- package/dist/{iconv-DreIffeM.mjs.map → iconv-D2vi8G36.mjs.map} +1 -1
- package/dist/{idp-Ch95ag8h.mjs → idp-BDbK5gjm.mjs} +2 -3
- package/dist/{idp-Ch95ag8h.mjs.map → idp-BDbK5gjm.mjs.map} +1 -1
- package/dist/{idp-BlBPtXJ-.d.mts → idp-DrhVrLmV.d.mts} +1 -1
- package/dist/{index-CLxubakC.d.mts → index-BI-_j9Z3.d.mts} +49 -261
- package/dist/{index-CPRnOjjt.d.mts → index-C4JirJH8.d.mts} +2 -2
- package/dist/{index-CQZVJ5SX.d.mts → index-CZfWhr0a.d.mts} +2 -2
- package/dist/{index-DRhMpdnA.d.mts → index-Cg8VKAdN.d.mts} +8 -8
- package/dist/{index-CfRFkXIO.d.mts → index-DYRjoLXD.d.mts} +2 -2
- package/dist/index-lFpcjHPU.d.mts +201 -0
- package/dist/{index-DUupuPhZ.d.mts → index-nW7hE6oE.d.mts} +2 -2
- package/dist/{interceptor-DOqRkCya.mjs → interceptor-D-q1rvRl.mjs} +1 -2
- package/dist/{interceptor-DOqRkCya.mjs.map → interceptor-D-q1rvRl.mjs.map} +1 -1
- package/dist/kysely/index.mjs +0 -1
- package/dist/kysely/index.mjs.map +1 -1
- package/dist/{kysely-type-D1e0Vwkd.mjs → kysely-type-DR8uzZTA.mjs} +2 -3
- package/dist/kysely-type-DR8uzZTA.mjs.map +1 -0
- package/dist/{logger-DpJyJvNz.mjs → logger-CxF-Ex5d.mjs} +1 -2
- package/dist/{logger-DpJyJvNz.mjs.map → logger-CxF-Ex5d.mjs.map} +1 -1
- package/dist/{mock-DMgIygjE.mjs → mock-FPxmnt-y.mjs} +9 -56
- package/dist/mock-FPxmnt-y.mjs.map +1 -0
- package/dist/{multiline-Cf9ODpr1.mjs → multiline-sfHpTZZK.mjs} +1 -2
- package/dist/{multiline-Cf9ODpr1.mjs.map → multiline-sfHpTZZK.mjs.map} +1 -1
- package/dist/{package-json-DcQApfPQ.mjs → package-json-8b0O9TlX.mjs} +1 -2
- package/dist/{package-json-DcQApfPQ.mjs.map → package-json-8b0O9TlX.mjs.map} +1 -1
- package/dist/package-json-Cv2Z-TqQ.mjs +3 -0
- package/dist/plugin/builtin/enum-constants/index.d.mts +1 -1
- package/dist/plugin/builtin/enum-constants/index.mjs +1 -2
- package/dist/plugin/builtin/file-utils/index.d.mts +1 -1
- package/dist/plugin/builtin/file-utils/index.mjs +1 -2
- package/dist/plugin/builtin/kysely-type/index.d.mts +1 -1
- package/dist/plugin/builtin/kysely-type/index.mjs +1 -2
- package/dist/plugin/builtin/seed/index.d.mts +1 -1
- package/dist/plugin/builtin/seed/index.mjs +1 -2
- package/dist/plugin/index.d.mts +4 -5
- package/dist/plugin/index.mjs +0 -1
- package/dist/plugin/index.mjs.map +1 -1
- package/dist/registry-DH4m7eYo.mjs +53 -0
- package/dist/registry-DH4m7eYo.mjs.map +1 -0
- package/dist/{repl-editor-CJG3sz7A.mjs → repl-editor-DmGr9zMw.mjs} +2 -3
- package/dist/{repl-editor-CJG3sz7A.mjs.map → repl-editor-DmGr9zMw.mjs.map} +1 -1
- package/dist/{chunk-BkoGK1jX.mjs → rolldown-runtime-DXywRVcq.mjs} +0 -1
- package/dist/runtime/authconnection.d.mts +1 -1
- package/dist/runtime/authconnection.mjs +1 -2
- package/dist/runtime/context.d.mts +1 -1
- package/dist/runtime/context.mjs +1 -2
- package/dist/runtime/file.d.mts +2 -2
- package/dist/runtime/file.mjs +2 -3
- package/dist/runtime/globals.d.mts +8 -41
- package/dist/runtime/globals.mjs +0 -1
- package/dist/runtime/iconv.d.mts +1 -1
- package/dist/runtime/iconv.mjs +1 -2
- package/dist/runtime/idp.d.mts +1 -1
- package/dist/runtime/idp.mjs +1 -2
- package/dist/runtime/index.d.mts +8 -8
- package/dist/runtime/index.mjs +7 -8
- package/dist/runtime/secretmanager.d.mts +1 -1
- package/dist/runtime/secretmanager.mjs +1 -2
- package/dist/runtime/workflow.d.mts +2 -2
- package/dist/runtime/workflow.mjs +1 -2
- package/dist/{runtime-C7qTBDD2.mjs → runtime-CY4JvrDj.mjs} +1069 -542
- package/dist/runtime-CY4JvrDj.mjs.map +1 -0
- package/dist/{schema-1msIhXwA.mjs → schema-Dtw9Orye.mjs} +18 -16
- package/dist/schema-Dtw9Orye.mjs.map +1 -0
- package/dist/{secret-file-CWzF8rry.mjs → secret-file-VSVGy1V0.mjs} +27 -3
- package/dist/{secret-file-CWzF8rry.mjs.map → secret-file-VSVGy1V0.mjs.map} +1 -1
- package/dist/{secretmanager-CKLB3wAQ.d.mts → secretmanager-B3n4KHfm.d.mts} +1 -1
- package/dist/{secretmanager-B9h-U_8U.mjs → secretmanager-BVxw3ih_.mjs} +2 -3
- package/dist/{secretmanager-B9h-U_8U.mjs.map → secretmanager-BVxw3ih_.mjs.map} +1 -1
- package/dist/seed/index.mjs +0 -1
- package/dist/seed/index.mjs.map +1 -1
- package/dist/{seed-BH2FbrPV.mjs → seed-izIEyP3z.mjs} +7 -19
- package/dist/seed-izIEyP3z.mjs.map +1 -0
- package/dist/service-DCqIWibD.mjs +3 -0
- package/dist/{service-DMohAx8a2.mjs → service-DU1mVzri2.mjs} +3 -4
- package/dist/{service-DMohAx8a2.mjs.map → service-DU1mVzri2.mjs.map} +1 -1
- package/dist/{service-wI3Hvrgx.mjs → service-DjyqbCaJ.mjs} +9 -10
- package/dist/service-DjyqbCaJ.mjs.map +1 -0
- package/dist/{telemetry-BQbbVo2t.mjs → telemetry-CdqJEzkj.mjs} +2 -3
- package/dist/{telemetry-BQbbVo2t.mjs.map → telemetry-CdqJEzkj.mjs.map} +1 -1
- package/dist/telemetry-ClwW5ohF.mjs +3 -0
- package/dist/test-env-key-D7UkZp99.mjs +75 -0
- package/dist/test-env-key-D7UkZp99.mjs.map +1 -0
- package/dist/type-source-DH_LH20p.mjs +13 -0
- package/dist/type-source-DH_LH20p.mjs.map +1 -0
- package/dist/types-74etvaxy.mjs +4 -0
- package/dist/{plugin-C_FyVSdl.d.mts → types-BDRml5C3.d.mts} +128 -188
- package/dist/{types-CmzfQP_m.mjs → types-BQijbo4m.mjs} +10 -11
- package/dist/types-BQijbo4m.mjs.map +1 -0
- package/dist/types-BX4q6Mo6.d.mts +339 -0
- package/dist/types-BZ7QKVE8.d.mts +21 -0
- package/dist/{tailordb-BlBGmQK-.d.mts → types-CdcQh4Z2.d.mts} +92 -242
- package/dist/utils/test/index.d.mts +6 -14
- package/dist/utils/test/index.mjs +4 -14
- package/dist/utils/test/index.mjs.map +1 -1
- package/dist/vitest/environment.mjs +1 -2
- package/dist/vitest/environment.mjs.map +1 -1
- package/dist/vitest/index.d.mts +42 -5
- package/dist/vitest/index.mjs +133 -4
- package/dist/vitest/index.mjs.map +1 -1
- package/dist/vitest/setup.mjs +2 -3
- package/dist/vitest/setup.mjs.map +1 -1
- package/dist/{workflow--aPbA8Uq.mjs → workflow-BOmaZwwG.mjs} +9 -5
- package/dist/workflow-BOmaZwwG.mjs.map +1 -0
- package/dist/{workflow-CMamswkK.d.mts → workflow-BVy4XWjS.d.mts} +15 -10
- package/dist/workflow.generated-ClEjBYhm.d.mts +671 -0
- package/docs/cli/application.md +0 -2
- package/docs/cli/completion.md +3 -0
- package/docs/cli/crashreport.md +0 -2
- package/docs/cli/executor.md +53 -0
- package/docs/cli/function.md +1 -1
- package/docs/cli/setup.md +35 -33
- package/docs/cli/user.md +3 -3
- package/docs/cli/workflow.md +157 -20
- package/docs/cli/workspace.md +3 -3
- package/docs/cli-reference.md +26 -20
- package/docs/configuration.md +0 -2
- package/docs/github-actions.md +29 -16
- package/docs/migration/v2.md +475 -0
- package/docs/plugin/custom.md +2 -2
- package/docs/plugin/index.md +1 -1
- package/docs/runtime.md +4 -4
- package/docs/services/aigateway.md +97 -0
- package/docs/services/auth.md +31 -14
- package/docs/services/executor.md +3 -5
- package/docs/services/resolver.md +8 -10
- package/docs/services/tailordb.md +15 -13
- package/docs/services/workflow.md +17 -19
- package/docs/testing.md +75 -56
- package/package.json +18 -17
- package/dist/actor-J2gJ0eK5.d.mts +0 -24
- package/dist/application-76hhIhnJ.mjs +0 -5594
- package/dist/application-76hhIhnJ.mjs.map +0 -1
- package/dist/application-av2raLs6.mjs +0 -4
- package/dist/cli/skills.d.mts +0 -1
- package/dist/cli/skills.mjs +0 -22
- package/dist/cli/skills.mjs.map +0 -1
- package/dist/client-C68VWo4g.mjs +0 -4
- package/dist/client-CobIRHl-.mjs.map +0 -1
- package/dist/context-s0lxhu8_.mjs.map +0 -1
- package/dist/enum-constants-C7DaWeQo.mjs.map +0 -1
- package/dist/env-B-g-qgE4.d.mts +0 -7
- package/dist/field-C4zdJLW5.mjs.map +0 -1
- package/dist/file-B58Dm-2P.mjs.map +0 -1
- package/dist/file-utils-BHPxPXmn.mjs.map +0 -1
- package/dist/globals-ByrCoDip.mjs.map +0 -1
- package/dist/job-BpsFXPbi.mjs +0 -54
- package/dist/job-BpsFXPbi.mjs.map +0 -1
- package/dist/kysely-type-D1e0Vwkd.mjs.map +0 -1
- package/dist/mock-DMgIygjE.mjs.map +0 -1
- package/dist/package-json-wzO6nV9O.mjs +0 -4
- package/dist/registry-D0uB0OrK.mjs +0 -178
- package/dist/registry-D0uB0OrK.mjs.map +0 -1
- package/dist/runtime-C7qTBDD2.mjs.map +0 -1
- package/dist/schema-1msIhXwA.mjs.map +0 -1
- package/dist/seed-BH2FbrPV.mjs.map +0 -1
- package/dist/service-BHQIerYh.mjs +0 -4
- package/dist/service-wI3Hvrgx.mjs.map +0 -1
- package/dist/telemetry-w92bvGdC.mjs +0 -4
- package/dist/types-2Be3wSMc.mjs +0 -5
- package/dist/types-CmzfQP_m.mjs.map +0 -1
- package/dist/workflow--aPbA8Uq.mjs.map +0 -1
- package/dist/workflow.generated-Bf1tWylx.d.mts +0 -1416
- package/docs/generator/builtin.md +0 -257
- package/docs/generator/custom.md +0 -147
- package/docs/generator/index.md +0 -66
|
@@ -1,7 +1,6 @@
|
|
|
1
|
-
|
|
2
|
-
import {
|
|
3
|
-
import { t as
|
|
4
|
-
import { r as writeSecretFile, t as ensureSecretDir } from "./secret-file-CWzF8rry.mjs";
|
|
1
|
+
import { n as logger } from "./logger-CxF-Ex5d.mjs";
|
|
2
|
+
import { t as readPackageJson } from "./package-json-8b0O9TlX.mjs";
|
|
3
|
+
import { a as userAgentFromVersion, r as writeSecretFile, t as ensureSecretDir } from "./secret-file-VSVGy1V0.mjs";
|
|
5
4
|
import * as fs from "node:fs";
|
|
6
5
|
import * as path from "pathe";
|
|
7
6
|
import * as os from "node:os";
|
|
@@ -334,25 +333,35 @@ function buildCrashReport(options) {
|
|
|
334
333
|
errorMessage: sanitizeMessage(rawMessage),
|
|
335
334
|
stackTrace: sanitizeStackTrace(rawStack),
|
|
336
335
|
errorType,
|
|
337
|
-
userId: currentUser,
|
|
338
|
-
userEmail: currentUser
|
|
336
|
+
userId: currentUser?.id ?? null,
|
|
337
|
+
userEmail: currentUser?.email ?? null
|
|
339
338
|
};
|
|
340
339
|
}
|
|
341
340
|
/**
|
|
342
341
|
* Read current_user from Tailor Platform config without side effects.
|
|
343
342
|
* Unlike readPlatformConfig(), this never triggers migration or logs warnings.
|
|
344
|
-
* @returns The current user email, or null if unavailable
|
|
343
|
+
* @returns The current user ID and email, or null if unavailable
|
|
345
344
|
*/
|
|
346
345
|
function readCurrentUser() {
|
|
347
346
|
try {
|
|
348
347
|
if (!xdgConfig) return null;
|
|
349
348
|
const configPath = path.join(xdgConfig, "tailor-platform", "config.yaml");
|
|
350
349
|
if (!fs.existsSync(configPath)) return null;
|
|
351
|
-
|
|
350
|
+
const raw = parseYAML(fs.readFileSync(configPath, "utf-8"));
|
|
351
|
+
const currentUser = raw?.current_user ?? null;
|
|
352
|
+
if (!currentUser) return null;
|
|
353
|
+
const email = raw.users?.[currentUser]?.email;
|
|
354
|
+
return {
|
|
355
|
+
id: currentUser,
|
|
356
|
+
email: typeof email === "string" ? email : legacyEmail(currentUser)
|
|
357
|
+
};
|
|
352
358
|
} catch {
|
|
353
359
|
return null;
|
|
354
360
|
}
|
|
355
361
|
}
|
|
362
|
+
function legacyEmail(user) {
|
|
363
|
+
return user.includes("@") ? user : null;
|
|
364
|
+
}
|
|
356
365
|
|
|
357
366
|
//#endregion
|
|
358
367
|
//#region src/cli/crashreport/index.ts
|
|
@@ -369,9 +378,10 @@ async function reportCrash(error, errorType) {
|
|
|
369
378
|
try {
|
|
370
379
|
const config = parseCrashReportConfig();
|
|
371
380
|
if (!config.localEnabled && !config.remoteEnabled) return;
|
|
381
|
+
const sdkVersion = (await readPackageJson()).version ?? "unknown";
|
|
372
382
|
const report = buildCrashReport({
|
|
373
383
|
error,
|
|
374
|
-
sdkVersion
|
|
384
|
+
sdkVersion,
|
|
375
385
|
errorType
|
|
376
386
|
});
|
|
377
387
|
if (config.localEnabled) {
|
|
@@ -385,10 +395,7 @@ async function reportCrash(error, errorType) {
|
|
|
385
395
|
` tailor-sdk crashreport send --file "${filePath}"`
|
|
386
396
|
].join("\n"));
|
|
387
397
|
}
|
|
388
|
-
if (config.remoteEnabled)
|
|
389
|
-
const { userAgent } = await import("./client-C68VWo4g.mjs");
|
|
390
|
-
await sendCrashReport(report, await userAgent());
|
|
391
|
-
}
|
|
398
|
+
if (config.remoteEnabled) await sendCrashReport(report, userAgentFromVersion(sdkVersion));
|
|
392
399
|
} catch {}
|
|
393
400
|
}
|
|
394
401
|
/**
|
|
@@ -412,4 +419,4 @@ function initCrashReporting() {
|
|
|
412
419
|
|
|
413
420
|
//#endregion
|
|
414
421
|
export { JSON_FOOTER_MARKER as a, CRASH_LOG_EXTENSION as i, reportCrash as n, parseCrashReportConfig as o, sendCrashReport as r, initCrashReporting as t };
|
|
415
|
-
//# sourceMappingURL=crashreport-
|
|
422
|
+
//# sourceMappingURL=crashreport-DFq-vsU0.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"crashreport-BhD0y14F.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 // parseYAML returns null for empty documents\n // oxlint-disable-next-line typescript/no-unnecessary-condition\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,KAAI,CAAE,YAAY,MAAM;CACxF,MAAM,iBAAiB,QAAQ,IAAI,+BAA+B,MAAK,CAAE,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,gBAA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C;CACrF,IAAI;EACF,MAAM,SAAS,uBAAuB;EACtC,IAAI,CAAC,OAAO,gBAAgB,CAAC,OAAO,eAAe;EAKnD,MAAM,SAAS,iBAAiB;GAAE;GAAO,aAFtB,MADO,gBAAgB,EACZ,CAAC,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,CAAC,CAAC,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,CAAC,CAAC,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
|
+
{"version":3,"file":"crashreport-DFq-vsU0.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?.id ?? null,\n userEmail: currentUser?.email ?? null,\n };\n}\n\ntype CurrentUser = {\n id: string;\n email: string | null;\n};\n\n/**\n * Read current_user from Tailor Platform config without side effects.\n * Unlike readPlatformConfig(), this never triggers migration or logs warnings.\n * @returns The current user ID and email, or null if unavailable\n */\nfunction readCurrentUser(): CurrentUser | null {\n try {\n if (!xdgConfig) return null;\n const configPath = path.join(xdgConfig, \"tailor-platform\", \"config.yaml\");\n if (!fs.existsSync(configPath)) return null;\n const raw = parseYAML(fs.readFileSync(configPath, \"utf-8\")) as {\n current_user?: string | null;\n users?: Record<string, { email?: unknown } | undefined>;\n };\n // parseYAML returns null for empty documents\n // oxlint-disable-next-line typescript/no-unnecessary-condition\n const currentUser = raw?.current_user ?? null;\n if (!currentUser) return null;\n const email = raw.users?.[currentUser]?.email;\n return {\n id: currentUser,\n email: typeof email === \"string\" ? email : legacyEmail(currentUser),\n };\n } catch {\n return null;\n }\n}\n\nfunction legacyEmail(user: string): string | null {\n return user.includes(\"@\") ? user : null;\n}\n","import { logger } from \"@/cli/shared/logger\";\nimport { readPackageJson } from \"@/cli/shared/package-json\";\nimport { userAgentFromVersion } from \"@/cli/shared/user-agent\";\nimport { parseCrashReportConfig } from \"./config\";\nimport { buildCrashReport, type ErrorType } from \"./report\";\nimport { sendCrashReport } from \"./sender\";\nimport { writeCrashReport } from \"./writer\";\n\n/**\n * Report an unexpected crash. Writes a local crash log file and optionally\n * sends the report to a remote endpoint. Displays a user-facing message\n * with the crash log path and a command to submit the report.\n *\n * Never throws - all errors are silently caught.\n * @param error - The error that caused the crash\n * @param errorType - How the error was caught\n */\nexport async function reportCrash(error: unknown, errorType: ErrorType): Promise<void> {\n try {\n const config = parseCrashReportConfig();\n if (!config.localEnabled && !config.remoteEnabled) return;\n\n const packageJson = await readPackageJson();\n const sdkVersion = packageJson.version ?? \"unknown\";\n\n const report = buildCrashReport({ error, sdkVersion, errorType });\n\n if (config.localEnabled) {\n const filePath = writeCrashReport(report, config.localDir);\n if (filePath) {\n logger.log(\n [\n \"\",\n \"An unexpected error occurred. A crash report has been saved to:\",\n ` ${filePath}`,\n \"\",\n \"To submit this report:\",\n ` tailor-sdk crashreport send --file \"${filePath}\"`,\n ].join(\"\\n\"),\n );\n }\n }\n\n if (config.remoteEnabled) {\n const ua = userAgentFromVersion(sdkVersion);\n await sendCrashReport(report, ua);\n }\n } catch {\n // Never throw from crash reporting\n }\n}\n\n/**\n * Register global uncaughtException and unhandledRejection handlers.\n * These catch errors outside the normal cleanup flow (e.g., during\n * argument parsing). Should be called once at CLI startup before runMain.\n */\nexport function initCrashReporting(): void {\n const config = parseCrashReportConfig();\n if (!config.localEnabled && !config.remoteEnabled) return;\n\n const handleFatal = (error: unknown, errorType: ErrorType) => {\n const message = error instanceof Error ? error.message : String(error);\n logger.error(message);\n void reportCrash(error, errorType).finally(() => {\n process.exit(1);\n });\n };\n\n process.on(\"uncaughtException\", (error) => handleFatal(error, \"uncaughtException\"));\n process.on(\"unhandledRejection\", (reason) => handleFatal(reason, \"unhandledRejection\"));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAiBA,SAAgB,yBAA4C;CAC1D,IAAI,MACF,OA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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,CAAC,CAAC,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,4 +1,3 @@
|
|
|
1
|
-
|
|
2
1
|
//#region src/plugin/builtin/enum-constants/generate-enum-constants.ts
|
|
3
2
|
/**
|
|
4
3
|
* Generate enum constant definitions from collected metadata.
|
|
@@ -114,4 +113,4 @@ function enumConstantsPlugin(options) {
|
|
|
114
113
|
|
|
115
114
|
//#endregion
|
|
116
115
|
export { enumConstantsPlugin as n, EnumConstantsGeneratorID as t };
|
|
117
|
-
//# sourceMappingURL=enum-constants-
|
|
116
|
+
//# sourceMappingURL=enum-constants-j9QBF0cB.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"enum-constants-j9QBF0cB.mjs","names":[],"sources":["../src/plugin/builtin/enum-constants/generate-enum-constants.ts","../src/plugin/builtin/enum-constants/process-enum-type.ts","../src/plugin/builtin/enum-constants/index.ts"],"sourcesContent":["import type { EnumDefinition } from \"./types\";\n\n/**\n * Generate enum constant definitions from collected metadata.\n * @param allEnums - All collected enum definitions\n * @returns Generated enum constant definitions\n */\nexport function generateUnifiedEnumConstants(allEnums: EnumDefinition[]): string {\n if (allEnums.length === 0) {\n return \"\";\n }\n\n const enumMap = new Map<string, EnumDefinition>();\n for (const enumDef of allEnums) {\n enumMap.set(enumDef.name, enumDef);\n }\n\n const enumDefs = Array.from(enumMap.values())\n .map((e) => {\n const members = e.values\n .map((v) => {\n const key = v.value.replace(/[-\\s]/g, \"_\");\n return ` \"${key}\": \"${v.value}\"`;\n })\n .join(\",\\n\");\n\n const hasDescriptions = e.values.some((v) => v.description);\n let jsDoc = \"\";\n if (e.fieldDescription || hasDescriptions) {\n const lines: string[] = [];\n\n if (e.fieldDescription) {\n lines.push(` * ${e.fieldDescription}`);\n if (hasDescriptions) {\n lines.push(\" *\");\n }\n }\n\n if (hasDescriptions) {\n const propertyDocs = e.values.map((v) => {\n const key = v.value.replace(/[-\\s]/g, \"_\");\n return ` * @property ${[key, v.description].filter(Boolean).join(\" - \")}`;\n });\n lines.push(...propertyDocs);\n }\n\n if (lines.length > 0) {\n jsDoc = `/**\\n${lines.join(\"\\n\")}\\n */\\n`;\n }\n }\n\n const constDef = `${jsDoc}export const ${e.name} = {\\n${members}\\n} as const;`;\n const typeDef = `export type ${e.name} = (typeof ${e.name})[keyof typeof ${e.name}];`;\n return `${constDef}\\n${typeDef}`;\n })\n .join(\"\\n\\n\");\n\n if (!enumDefs) {\n return \"\";\n }\n\n return enumDefs + \"\\n\";\n}\n","import type { EnumConstantMetadata } from \"./types\";\nimport type { TailorDBType } from \"@/parser/service/tailordb/types\";\n\nfunction capitalizeFirst(str: string): string {\n return str.charAt(0).toUpperCase() + str.slice(1);\n}\n\nfunction collectEnums(type: TailorDBType): EnumConstantMetadata[\"enums\"] {\n const enums: EnumConstantMetadata[\"enums\"] = [];\n\n for (const [fieldName, parsedField] of Object.entries(type.fields)) {\n if (parsedField.config.type === \"enum\" && parsedField.config.allowedValues) {\n const enumTypeName = `${type.name}${capitalizeFirst(fieldName)}`;\n enums.push({\n name: enumTypeName,\n values: parsedField.config.allowedValues,\n fieldDescription: parsedField.config.description,\n });\n }\n\n // Process nested fields\n if (parsedField.config.type === \"nested\" && parsedField.config.fields) {\n for (const [nestedFieldName, nestedFieldConfig] of Object.entries(\n parsedField.config.fields,\n )) {\n if (nestedFieldConfig.type === \"enum\" && nestedFieldConfig.allowedValues) {\n const fullFieldName = `${fieldName}${capitalizeFirst(nestedFieldName)}`;\n const enumTypeName = `${type.name}${capitalizeFirst(fullFieldName)}`;\n enums.push({\n name: enumTypeName,\n values: nestedFieldConfig.allowedValues,\n fieldDescription: nestedFieldConfig.description,\n });\n }\n }\n }\n }\n\n return enums;\n}\n\n/**\n * Process a TailorDB type and extract enum metadata.\n * @param type - The parsed TailorDB type to process\n * @returns Enum constant metadata for the type\n */\nexport async function processEnumType(type: TailorDBType): Promise<EnumConstantMetadata> {\n const enums = collectEnums(type);\n\n return {\n name: type.name,\n enums,\n };\n}\n","import { generateUnifiedEnumConstants } from \"./generate-enum-constants\";\nimport { processEnumType } from \"./process-enum-type\";\nimport type { EnumDefinition } from \"./types\";\nimport type { Plugin, GeneratorResult, TailorDBReadyContext } from \"@/plugin/types\";\n\n/** Unique identifier for the enum constants generator plugin. */\nexport const EnumConstantsGeneratorID = \"@tailor-platform/enum-constants\";\n\ntype EnumConstantsPluginOptions = {\n distPath: string;\n};\n\n/**\n * Plugin that generates enum constants from TailorDB type definitions.\n * @param options - Plugin options\n * @param options.distPath - Output file path for generated constants\n * @returns Plugin instance with onTailorDBReady hook\n */\nexport function enumConstantsPlugin(\n options: EnumConstantsPluginOptions,\n): Plugin<unknown, EnumConstantsPluginOptions> {\n return {\n id: EnumConstantsGeneratorID,\n description: \"Generates enum constants from TailorDB type definitions\",\n pluginConfig: options,\n\n async onTailorDBReady(\n ctx: TailorDBReadyContext<EnumConstantsPluginOptions>,\n ): Promise<GeneratorResult> {\n const allEnums: EnumDefinition[] = [];\n\n for (const ns of ctx.tailordb) {\n for (const type of Object.values(ns.types)) {\n const metadata = await processEnumType(type);\n allEnums.push(...metadata.enums);\n }\n }\n\n const files: GeneratorResult[\"files\"] = [];\n if (allEnums.length > 0) {\n const content = generateUnifiedEnumConstants(allEnums);\n files.push({\n path: ctx.pluginConfig.distPath,\n content,\n });\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GAGF,MAAM,QAAkC,CAAC;GACzC,IAAI,SAAS,SAAS,GAAG;IACvB,MAAM,UAAU,6BAA6B,QAAQ;IACrD,MAAM,KAAK;KACT,MAAM,IAAI,aAAa;KACvB;IACF,CAAC;GACH;GAEA,OAAO,EAAE,MAAM;EACjB;CACF;AACF"}
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
|
|
2
1
|
import chalk from "chalk";
|
|
3
2
|
|
|
4
3
|
//#region src/cli/shared/errors.ts
|
|
@@ -40,4 +39,4 @@ function isCLIError(error) {
|
|
|
40
39
|
|
|
41
40
|
//#endregion
|
|
42
41
|
export { isCLIError as n, createCLIError as t };
|
|
43
|
-
//# sourceMappingURL=errors-
|
|
42
|
+
//# sourceMappingURL=errors-Dtf2WPaW.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors-
|
|
1
|
+
{"version":3,"file":"errors-Dtf2WPaW.mjs","names":[],"sources":["../src/cli/shared/errors.ts"],"sourcesContent":["import chalk from \"chalk\";\n\n/**\n * Options for creating a CLI error\n */\nexport interface CLIErrorOptions {\n message: string;\n details?: string;\n suggestion?: string;\n command?: string;\n code?: string;\n}\n\n/**\n * CLI error interface with formatted output\n */\nexport interface CLIError extends Error {\n readonly code?: string;\n readonly details?: string;\n readonly suggestion?: string;\n readonly command?: string;\n format(): string;\n}\n\ntype CLIErrorInternal = Error & {\n code?: string;\n details?: string;\n suggestion?: string;\n command?: string;\n format(): string;\n};\n\n/**\n * Format CLI error for output\n * @param error - CLIError instance to format\n * @returns Formatted error message\n */\nfunction formatError(error: CLIError): string {\n const parts: string[] = [\n chalk.red(`Error${error.code ? ` [${error.code}]` : \"\"}: ${error.message}`),\n ];\n\n if (error.details) {\n parts.push(`\\n ${chalk.gray(\"Details:\")} ${error.details}`);\n }\n\n if (error.suggestion) {\n parts.push(`\\n ${chalk.cyan(\"Suggestion:\")} ${error.suggestion}`);\n }\n\n if (error.command) {\n parts.push(\n `\\n ${chalk.gray(\"Help:\")} Run \\`tailor-sdk ${error.command} --help\\` for usage information.`,\n );\n }\n\n return parts.join(\"\");\n}\n\n/**\n * Create a CLI error with formatted output\n * @param options - Options to construct a CLIError\n * @returns Constructed CLIError instance\n */\nfunction createCLIError(options: CLIErrorOptions): CLIError {\n const error = new Error(options.message) as CLIErrorInternal;\n error.name = \"CLIError\";\n error.code = options.code;\n error.details = options.details;\n error.suggestion = options.suggestion;\n error.command = options.command;\n error.format = () => formatError(error);\n return error;\n}\n\n/**\n * Type guard to check if an error is a CLIError\n * @param error - Error to check\n * @returns True if the error is a CLIError\n */\nexport function isCLIError(error: unknown): error is CLIError {\n return error instanceof Error && error.name === \"CLIError\";\n}\n\n// Re-export createCLIError as CLIError for backward compatibility\nexport { createCLIError as CLIError };\n"],"mappings":";;;;;;;;AAqCA,SAAS,YAAY,OAAyB;CAC5C,MAAM,QAAkB,CACtB,MAAM,IAAI,QAAQ,MAAM,OAAO,KAAK,MAAM,KAAK,KAAK,GAAG,IAAI,MAAM,SAAS,CAC5E;CAEA,IAAI,MAAM,SACR,MAAM,KAAK,OAAO,MAAM,KAAK,UAAU,EAAE,GAAG,MAAM,SAAS;CAG7D,IAAI,MAAM,YACR,MAAM,KAAK,OAAO,MAAM,KAAK,aAAa,EAAE,GAAG,MAAM,YAAY;CAGnE,IAAI,MAAM,SACR,MAAM,KACJ,OAAO,MAAM,KAAK,OAAO,EAAE,oBAAoB,MAAM,QAAQ,iCAC/D;CAGF,OAAO,MAAM,KAAK,EAAE;AACtB;;;;;;AAOA,SAAS,eAAe,SAAoC;CAC1D,MAAM,QAAQ,IAAI,MAAM,QAAQ,OAAO;CACvC,MAAM,OAAO;CACb,MAAM,OAAO,QAAQ;CACrB,MAAM,UAAU,QAAQ;CACxB,MAAM,aAAa,QAAQ;CAC3B,MAAM,UAAU,QAAQ;CACxB,MAAM,eAAe,YAAY,KAAK;CACtC,OAAO;AACT;;;;;;AAOA,SAAgB,WAAW,OAAmC;CAC5D,OAAO,iBAAiB,SAAS,MAAM,SAAS;AAClD"}
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
|
|
2
1
|
//#region src/configure/types/field.ts
|
|
3
2
|
/**
|
|
4
3
|
* Normalize allowed values into EnumValue objects with descriptions.
|
|
@@ -20,4 +19,4 @@ function mapAllowedValues(values) {
|
|
|
20
19
|
|
|
21
20
|
//#endregion
|
|
22
21
|
export { mapAllowedValues as t };
|
|
23
|
-
//# sourceMappingURL=field-
|
|
22
|
+
//# sourceMappingURL=field-DOsJCPFa.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"field-DOsJCPFa.mjs","names":[],"sources":["../src/configure/types/field.ts"],"sourcesContent":["import type { EnumValue } from \"@/configure/types/field.types\";\n\nexport type AllowedValues = readonly [string | EnumValue, ...(string | EnumValue)[]];\n\n/**\n * Normalize allowed values into EnumValue objects with descriptions.\n * @param values - Allowed values as strings or EnumValue objects\n * @returns Normalized allowed values\n */\nexport function mapAllowedValues(values: AllowedValues): EnumValue[] {\n return values.map((value) => {\n if (typeof value === \"string\") {\n return { value, description: \"\" };\n }\n return { ...value, description: value.description ?? \"\" };\n });\n}\n\nexport type AllowedValuesOutput<V extends AllowedValues> = V[number] extends infer T\n ? T extends string\n ? T\n : T extends { value: infer K }\n ? K\n : never\n : never;\n"],"mappings":";;;;;;AASA,SAAgB,iBAAiB,QAAoC;CACnE,OAAO,OAAO,KAAK,UAAU;EAC3B,IAAI,OAAO,UAAU,UACnB,OAAO;GAAE;GAAO,aAAa;EAAG;EAElC,OAAO;GAAE,GAAG;GAAO,aAAa,MAAM,eAAe;EAAG;CAC1D,CAAC;AACH"}
|
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
|
|
2
|
-
import { t as __exportAll } from "./chunk-BkoGK1jX.mjs";
|
|
1
|
+
import { t as __exportAll } from "./rolldown-runtime-DXywRVcq.mjs";
|
|
3
2
|
|
|
4
3
|
//#region src/runtime/file.ts
|
|
5
4
|
var file_exports = /* @__PURE__ */ __exportAll({
|
|
@@ -9,7 +8,6 @@ var file_exports = /* @__PURE__ */ __exportAll({
|
|
|
9
8
|
downloadAsBase64: () => downloadAsBase64,
|
|
10
9
|
downloadStream: () => downloadStream,
|
|
11
10
|
getMetadata: () => getMetadata,
|
|
12
|
-
openDownloadStream: () => openDownloadStream,
|
|
13
11
|
upload: () => upload,
|
|
14
12
|
uploadStream: () => uploadStream
|
|
15
13
|
});
|
|
@@ -45,13 +43,6 @@ const deleteFile = (...args) => api().delete(...args);
|
|
|
45
43
|
*/
|
|
46
44
|
const getMetadata = (...args) => api().getMetadata(...args);
|
|
47
45
|
/**
|
|
48
|
-
* See {@link TailorDBFileAPI.openDownloadStream}.
|
|
49
|
-
* @deprecated Use {@link downloadStream} instead.
|
|
50
|
-
* @param args - Forwarded to {@link TailorDBFileAPI.openDownloadStream}
|
|
51
|
-
* @returns Async iterator yielding file chunks; call `close()` to release resources
|
|
52
|
-
*/
|
|
53
|
-
const openDownloadStream = (...args) => api().openDownloadStream(...args);
|
|
54
|
-
/**
|
|
55
46
|
* See {@link TailorDBFileAPI.downloadStream}.
|
|
56
47
|
* @param args - Forwarded to {@link TailorDBFileAPI.downloadStream}
|
|
57
48
|
* @returns ReadableStream body and metadata for the file
|
|
@@ -65,5 +56,5 @@ const downloadStream = (...args) => api().downloadStream(...args);
|
|
|
65
56
|
const uploadStream = (...args) => api().uploadStream(...args);
|
|
66
57
|
|
|
67
58
|
//#endregion
|
|
68
|
-
export { file_exports as a,
|
|
69
|
-
//# sourceMappingURL=file-
|
|
59
|
+
export { file_exports as a, uploadStream as c, downloadStream as i, download as n, getMetadata as o, downloadAsBase64 as r, upload as s, deleteFile as t };
|
|
60
|
+
//# sourceMappingURL=file-BbdFGdMV.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"file-BbdFGdMV.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/** 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/** 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 * 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.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":";;;;;;;;;;;;;AAgOA,MAAM,YACH,WAAuD,SAAS;;;;;;AAOnE,MAAa,UAAqC,GAAG,SAAS,IAAI,CAAC,CAAC,OAAO,GAAG,IAAI;;;;;;AAOlF,MAAa,YAAyC,GAAG,SAAS,IAAI,CAAC,CAAC,SAAS,GAAG,IAAI;;;;;;AAOxF,MAAa,oBAAyD,GAAG,SACvE,IAAI,CAAC,CAAC,iBAAiB,GAAG,IAAI;;;;;;AAOhC,MAAa,cAAyC,GAAG,SAAS,IAAI,CAAC,CAAC,OAAO,GAAG,IAAI;;;;;;AAOtF,MAAa,eAA+C,GAAG,SAAS,IAAI,CAAC,CAAC,YAAY,GAAG,IAAI;;;;;;AAOjG,MAAa,kBAAqD,GAAG,SACnE,IAAI,CAAC,CAAC,eAAe,GAAG,IAAI;;;;;;AAO9B,MAAa,gBAAiD,GAAG,SAC/D,IAAI,CAAC,CAAC,aAAa,GAAG,IAAI"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
declare namespace file_d_exports {
|
|
2
|
-
export { DownloadMetadata, FileDownloadAsBase64Response, FileDownloadResponse, FileDownloadStreamResponse, FileMetadata,
|
|
2
|
+
export { DownloadMetadata, FileDownloadAsBase64Response, FileDownloadResponse, FileDownloadStreamResponse, FileMetadata, FileUploadOptions, FileUploadResponse, FileUploadStreamOptions, TailorDBFileAPI, TailorDBFileError, TailorDBFileErrorCode, UploadMetadata, deleteFile as delete, deleteFile, download, downloadAsBase64, downloadStream, getMetadata, upload, uploadStream };
|
|
3
3
|
}
|
|
4
4
|
/**
|
|
5
5
|
* TailorDB file (BLOB) utilities.
|
|
@@ -38,12 +38,6 @@ interface FileMetadata {
|
|
|
38
38
|
urlPath: string;
|
|
39
39
|
lastUploadedAt?: string;
|
|
40
40
|
}
|
|
41
|
-
/** Stream metadata (first chunk emitted by {@link openDownloadStream}). */
|
|
42
|
-
interface StreamMetadata {
|
|
43
|
-
contentType: string;
|
|
44
|
-
fileSize: number;
|
|
45
|
-
sha256sum: string;
|
|
46
|
-
}
|
|
47
41
|
/** Upload options. */
|
|
48
42
|
interface FileUploadOptions {
|
|
49
43
|
contentType?: string;
|
|
@@ -72,22 +66,6 @@ interface FileDownloadStreamResponse {
|
|
|
72
66
|
body: ReadableStream<Uint8Array>;
|
|
73
67
|
metadata: DownloadMetadata;
|
|
74
68
|
}
|
|
75
|
-
/** Stream chunk types emitted by {@link FileStreamIterator}. */
|
|
76
|
-
type StreamValue = {
|
|
77
|
-
type: "metadata";
|
|
78
|
-
metadata: StreamMetadata;
|
|
79
|
-
} | {
|
|
80
|
-
type: "chunk";
|
|
81
|
-
data: Uint8Array;
|
|
82
|
-
position: number;
|
|
83
|
-
} | {
|
|
84
|
-
type: "complete";
|
|
85
|
-
};
|
|
86
|
-
/** Stream iterator returned by {@link openDownloadStream}. */
|
|
87
|
-
interface FileStreamIterator extends AsyncIterableIterator<StreamValue> {
|
|
88
|
-
next(): Promise<IteratorResult<StreamValue>>;
|
|
89
|
-
close(): Promise<void>;
|
|
90
|
-
}
|
|
91
69
|
/** Error code emitted by {@link TailorDBFileError}. */
|
|
92
70
|
type TailorDBFileErrorCode = "INVALID_PARAMS" | "INVALID_DATA_TYPE" | "OPERATION_FAILED" | "DELETE_FAILED" | "STREAM_OPEN_FAILED" | "STREAM_READ_ERROR" | "STREAM_ERROR" | "FILE_TOO_LARGE";
|
|
93
71
|
/**
|
|
@@ -165,16 +143,6 @@ interface TailorDBFileAPI {
|
|
|
165
143
|
* @returns Metadata for the stored file
|
|
166
144
|
*/
|
|
167
145
|
getMetadata(namespace: string, typeName: string, fieldName: string, recordId: string): Promise<FileMetadata>;
|
|
168
|
-
/**
|
|
169
|
-
* Open a download stream for large files.
|
|
170
|
-
* @deprecated Use {@link downloadStream} instead.
|
|
171
|
-
* @param namespace - TailorDB namespace
|
|
172
|
-
* @param typeName - TailorDB type name
|
|
173
|
-
* @param fieldName - File field name on the type
|
|
174
|
-
* @param recordId - Record ID owning the field
|
|
175
|
-
* @returns Async iterator yielding file chunks; call `close()` to release resources
|
|
176
|
-
*/
|
|
177
|
-
openDownloadStream(namespace: string, typeName: string, fieldName: string, recordId: string): Promise<FileStreamIterator>;
|
|
178
146
|
/**
|
|
179
147
|
* Download a file as a ReadableStream.
|
|
180
148
|
* @param namespace - TailorDB namespace
|
|
@@ -226,13 +194,6 @@ declare const deleteFile: TailorDBFileAPI["delete"];
|
|
|
226
194
|
* @returns Metadata for the stored file
|
|
227
195
|
*/
|
|
228
196
|
declare const getMetadata: TailorDBFileAPI["getMetadata"];
|
|
229
|
-
/**
|
|
230
|
-
* See {@link TailorDBFileAPI.openDownloadStream}.
|
|
231
|
-
* @deprecated Use {@link downloadStream} instead.
|
|
232
|
-
* @param args - Forwarded to {@link TailorDBFileAPI.openDownloadStream}
|
|
233
|
-
* @returns Async iterator yielding file chunks; call `close()` to release resources
|
|
234
|
-
*/
|
|
235
|
-
declare const openDownloadStream: TailorDBFileAPI["openDownloadStream"];
|
|
236
197
|
/**
|
|
237
198
|
* See {@link TailorDBFileAPI.downloadStream}.
|
|
238
199
|
* @param args - Forwarded to {@link TailorDBFileAPI.downloadStream}
|
|
@@ -246,5 +207,5 @@ declare const downloadStream: TailorDBFileAPI["downloadStream"];
|
|
|
246
207
|
*/
|
|
247
208
|
declare const uploadStream: TailorDBFileAPI["uploadStream"];
|
|
248
209
|
//#endregion
|
|
249
|
-
export {
|
|
250
|
-
//# sourceMappingURL=file-
|
|
210
|
+
export { file_d_exports as _, FileMetadata as a, uploadStream as b, FileUploadStreamOptions as c, TailorDBFileErrorCode as d, UploadMetadata as f, downloadStream as g, downloadAsBase64 as h, FileDownloadStreamResponse as i, TailorDBFileAPI as l, download as m, FileDownloadAsBase64Response as n, FileUploadOptions as o, deleteFile as p, FileDownloadResponse as r, FileUploadResponse as s, DownloadMetadata as t, TailorDBFileError as u, getMetadata as v, upload as y };
|
|
211
|
+
//# sourceMappingURL=file-Dq3NIt_F.d.mts.map
|
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
|
|
2
|
-
import { t as multiline } from "./multiline-Cf9ODpr1.mjs";
|
|
1
|
+
import { t as multiline } from "./multiline-sfHpTZZK.mjs";
|
|
3
2
|
|
|
4
3
|
//#region src/plugin/builtin/file-utils/generate-file-utils.ts
|
|
5
4
|
/**
|
|
@@ -26,7 +25,7 @@ function generateUnifiedFileUtils(namespaceData) {
|
|
|
26
25
|
FileUploadOptions,
|
|
27
26
|
FileUploadResponse,
|
|
28
27
|
FileMetadata,
|
|
29
|
-
|
|
28
|
+
FileDownloadStreamResponse,
|
|
30
29
|
} from "@tailor-platform/sdk/runtime/file";
|
|
31
30
|
` + "\n",
|
|
32
31
|
multiline`
|
|
@@ -78,12 +77,12 @@ function generateUnifiedFileUtils(namespaceData) {
|
|
|
78
77
|
}
|
|
79
78
|
` + "\n",
|
|
80
79
|
multiline`
|
|
81
|
-
export async function
|
|
80
|
+
export async function downloadFileStream<T extends keyof TypeWithFiles>(
|
|
82
81
|
type: T,
|
|
83
82
|
field: TypeWithFiles[T]["fields"],
|
|
84
83
|
recordId: string,
|
|
85
|
-
): Promise<
|
|
86
|
-
return await file.
|
|
84
|
+
): Promise<FileDownloadStreamResponse> {
|
|
85
|
+
return await file.downloadStream(namespaces[type], type, field, recordId);
|
|
87
86
|
}
|
|
88
87
|
` + "\n"
|
|
89
88
|
].join("\n");
|
|
@@ -148,4 +147,4 @@ function fileUtilsPlugin(options) {
|
|
|
148
147
|
|
|
149
148
|
//#endregion
|
|
150
149
|
export { fileUtilsPlugin as n, FileUtilsGeneratorID as t };
|
|
151
|
-
//# sourceMappingURL=file-utils-
|
|
150
|
+
//# sourceMappingURL=file-utils-CYZnO1pX.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"file-utils-CYZnO1pX.mjs","names":[],"sources":["../src/plugin/builtin/file-utils/generate-file-utils.ts","../src/plugin/builtin/file-utils/process-file-type.ts","../src/plugin/builtin/file-utils/index.ts"],"sourcesContent":["import multiline from \"@/utils/multiline\";\nimport type { FileUtilMetadata } from \"./types\";\n\n/**\n * Generate unified file utility functions from collected metadata.\n * @param namespaceData - Namespace data with file utility metadata\n * @returns Generated file utility code\n */\nexport function generateUnifiedFileUtils(\n namespaceData: { namespace: string; types: FileUtilMetadata[] }[],\n): string {\n if (namespaceData.length === 0) {\n return \"\";\n }\n\n // Collect all types with their namespace\n const typeNamespaceMap = new Map<string, string>();\n const typeFieldsMap = new Map<string, string[]>();\n\n for (const { namespace, types } of namespaceData) {\n for (const type of types) {\n typeNamespaceMap.set(type.name, namespace);\n typeFieldsMap.set(type.name, type.fileFields);\n }\n }\n\n if (typeNamespaceMap.size === 0) {\n return \"\";\n }\n\n // Generate interface fields\n const interfaceFields = Array.from(typeFieldsMap.entries())\n .map(([typeName, fields]) => {\n const fieldNamesUnion = fields.map((field) => `\"${field}\"`).join(\" | \");\n return ` ${typeName}: {\\n fields: ${fieldNamesUnion};\\n };`;\n })\n .join(\"\\n\");\n\n const importStatement =\n multiline /* ts */ `\n import * as file from \"@tailor-platform/sdk/runtime/file\";\n import type {\n FileUploadOptions,\n FileUploadResponse,\n FileMetadata,\n FileDownloadStreamResponse,\n } from \"@tailor-platform/sdk/runtime/file\";\n ` + \"\\n\";\n\n const interfaceDefinition =\n multiline /* ts */ `\n export interface TypeWithFiles {\n ${interfaceFields}\n }\n ` + \"\\n\";\n\n // Generate namespaces object\n const namespaceEntries = Array.from(typeNamespaceMap.entries())\n .map(([typeName, namespace]) => ` ${typeName}: \"${namespace}\"`)\n .join(\",\\n\");\n\n const namespacesDefinition =\n multiline /* ts */ `\n const namespaces: Record<keyof TypeWithFiles, string> = {\n ${namespaceEntries},\n };\n ` + \"\\n\";\n\n // Generate downloadFile helper function\n const downloadFunction =\n multiline /* ts */ `\n export async function downloadFile<T extends keyof TypeWithFiles>(\n type: T,\n field: TypeWithFiles[T][\"fields\"],\n recordId: string,\n ) {\n return await file.download(namespaces[type], type, field, recordId);\n }\n ` + \"\\n\";\n\n // Generate uploadFile helper function\n const uploadFunction =\n multiline /* ts */ `\n export async function uploadFile<T extends keyof TypeWithFiles>(\n type: T,\n field: TypeWithFiles[T][\"fields\"],\n recordId: string,\n data: string | ArrayBuffer | Uint8Array<ArrayBufferLike> | number[],\n options?: FileUploadOptions,\n ): Promise<FileUploadResponse> {\n return await file.upload(namespaces[type], type, field, recordId, data, options);\n }\n ` + \"\\n\";\n\n // Generate deleteFile helper function\n const deleteFunction =\n multiline /* ts */ `\n export async function deleteFile<T extends keyof TypeWithFiles>(\n type: T,\n field: TypeWithFiles[T][\"fields\"],\n recordId: string,\n ): Promise<void> {\n return await file.delete(namespaces[type], type, field, recordId);\n }\n ` + \"\\n\";\n\n // Generate getFileMetadata helper function\n const getMetadataFunction =\n multiline /* ts */ `\n export async function getFileMetadata<T extends keyof TypeWithFiles>(\n type: T,\n field: TypeWithFiles[T][\"fields\"],\n recordId: string,\n ): Promise<FileMetadata> {\n return await file.getMetadata(namespaces[type], type, field, recordId);\n }\n ` + \"\\n\";\n\n // Generate downloadFileStream helper function\n const downloadStreamFunction =\n multiline /* ts */ `\n export async function downloadFileStream<T extends keyof TypeWithFiles>(\n type: T,\n field: TypeWithFiles[T][\"fields\"],\n recordId: string,\n ): Promise<FileDownloadStreamResponse> {\n return await file.downloadStream(namespaces[type], type, field, recordId);\n }\n ` + \"\\n\";\n\n return [\n importStatement,\n interfaceDefinition,\n namespacesDefinition,\n downloadFunction,\n uploadFunction,\n deleteFunction,\n getMetadataFunction,\n downloadStreamFunction,\n ].join(\"\\n\");\n}\n","import type { FileUtilMetadata } from \"./types\";\nimport type { TailorDBType } from \"@/parser/service/tailordb/types\";\n\n/**\n * Process a TailorDB type and extract file field metadata.\n * @param type - The parsed TailorDB type to process\n * @returns File utility metadata for the type\n */\nexport async function processFileType(type: TailorDBType): Promise<FileUtilMetadata> {\n const fileFields: string[] = [];\n\n if (type.files) {\n for (const fileFieldName of Object.keys(type.files)) {\n fileFields.push(fileFieldName);\n }\n }\n\n return {\n name: type.name,\n fileFields,\n };\n}\n","import { generateUnifiedFileUtils } from \"./generate-file-utils\";\nimport { processFileType } from \"./process-file-type\";\nimport type { FileUtilMetadata } from \"./types\";\nimport type { Plugin, GeneratorResult, TailorDBReadyContext } from \"@/plugin/types\";\n\n/** Unique identifier for the file utilities generator plugin. */\nexport const FileUtilsGeneratorID = \"@tailor-platform/file-utils\";\n\ntype FileUtilsPluginOptions = {\n distPath: string;\n};\n\n/**\n * Plugin that generates TypeWithFiles interface from TailorDB type definitions.\n * @param options - Plugin options\n * @param options.distPath - Output file path for generated file utilities\n * @returns Plugin instance with onTailorDBReady hook\n */\nexport function fileUtilsPlugin(\n options: FileUtilsPluginOptions,\n): Plugin<unknown, FileUtilsPluginOptions> {\n return {\n id: FileUtilsGeneratorID,\n description: \"Generates TypeWithFiles interface from TailorDB type definitions\",\n pluginConfig: options,\n\n async onTailorDBReady(\n ctx: TailorDBReadyContext<FileUtilsPluginOptions>,\n ): Promise<GeneratorResult> {\n const namespaceData: { namespace: string; types: FileUtilMetadata[] }[] = [];\n\n for (const ns of ctx.tailordb) {\n const typesWithFiles: FileUtilMetadata[] = [];\n\n for (const type of Object.values(ns.types)) {\n const metadata = await processFileType(type);\n if (metadata.fileFields.length > 0) {\n typesWithFiles.push(metadata);\n }\n }\n\n if (typesWithFiles.length > 0) {\n namespaceData.push({\n namespace: ns.namespace,\n types: typesWithFiles,\n });\n }\n }\n\n const files: GeneratorResult[\"files\"] = [];\n if (namespaceData.length > 0) {\n const content = generateUnifiedFileUtils(namespaceData);\n if (content) {\n files.push({\n path: ctx.pluginConfig.distPath,\n content,\n });\n }\n }\n\n return { files };\n },\n };\n}\n"],"mappings":";;;;;;;;AAQA,SAAgB,yBACd,eACQ;CACR,IAAI,cAAc,WAAW,GAC3B,OAAO;CAIT,MAAM,mCAAmB,IAAI,IAAoB;CACjD,MAAM,gCAAgB,IAAI,IAAsB;CAEhD,KAAK,MAAM,EAAE,WAAW,WAAW,eACjC,KAAK,MAAM,QAAQ,OAAO;EACxB,iBAAiB,IAAI,KAAK,MAAM,SAAS;EACzC,cAAc,IAAI,KAAK,MAAM,KAAK,UAAU;CAC9C;CAGF,IAAI,iBAAiB,SAAS,GAC5B,OAAO;CAIT,MAAM,kBAAkB,MAAM,KAAK,cAAc,QAAQ,CAAC,CAAC,CACxD,KAAK,CAAC,UAAU,YAAY;EAE3B,OAAO,KAAK,SAAS,mBADG,OAAO,KAAK,UAAU,IAAI,MAAM,EAAE,CAAC,CAAC,KAAK,KACX,EAAE;CAC1D,CAAC,CAAC,CACD,KAAK,IAAI;CA8FZ,OAAO;EA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ACF,CAAC;GAEL;GAEA,OAAO,EAAE,MAAM;EACjB;CACF;AACF"}
|
|
@@ -1,11 +1,59 @@
|
|
|
1
|
+
import { t as TRIGGER_DEFAULT } from "./registry-DH4m7eYo.mjs";
|
|
1
2
|
|
|
2
|
-
|
|
3
|
+
//#region src/utils/test/platform-serialize.ts
|
|
4
|
+
/**
|
|
5
|
+
* Validate and serialize a value as it would cross the Platform JSON boundary.
|
|
6
|
+
*
|
|
7
|
+
* Mirrors the runtime checks the platform performs on workflow arguments,
|
|
8
|
+
* wait payloads, and trigger inputs so that local tests fail in the same
|
|
9
|
+
* places production fails.
|
|
10
|
+
*
|
|
11
|
+
* Throws on:
|
|
12
|
+
* - `NaN` / `Infinity` / `-Infinity` (`JSON.stringify` would silently emit `null`)
|
|
13
|
+
* - `BigInt` (TypeError is thrown by `JSON.stringify`; we emit a clearer message)
|
|
14
|
+
* - Non-plain objects (class instances, including `Date`, `Map`, `Set`, `Error`,
|
|
15
|
+
* and user-defined DTOs whose prototype is not `Object.prototype`)
|
|
16
|
+
*
|
|
17
|
+
* The replacer reads `this[key]` so the check sees the original value before
|
|
18
|
+
* any `toJSON` conversion (e.g. `Date.prototype.toJSON`).
|
|
19
|
+
* @param value - Value to validate and round-trip
|
|
20
|
+
* @returns The JSON-normalized value (undefined/function properties stripped, etc.)
|
|
21
|
+
*/
|
|
22
|
+
function platformSerialize(value) {
|
|
23
|
+
if (value === void 0) return void 0;
|
|
24
|
+
if (typeof value === "function") throw new TypeError("platformSerialize: function is not JSON-serializable at <root>");
|
|
25
|
+
if (typeof value === "symbol") throw new TypeError("platformSerialize: Symbol is not JSON-serializable at <root>");
|
|
26
|
+
const serialized = JSON.stringify(value, function(key, val) {
|
|
27
|
+
if (typeof val === "number" && !Number.isFinite(val)) throw new TypeError(`platformSerialize: non-finite number at ${formatPath(key)}: ${String(val)}`);
|
|
28
|
+
if (typeof val === "bigint") throw new TypeError(`platformSerialize: BigInt is not JSON-serializable at ${formatPath(key)}`);
|
|
29
|
+
const raw = this[key];
|
|
30
|
+
if (raw !== null && typeof raw === "object" && !Array.isArray(raw)) {
|
|
31
|
+
const proto = Object.getPrototypeOf(raw);
|
|
32
|
+
if (proto !== Object.prototype && proto !== null) {
|
|
33
|
+
const ctor = raw.constructor?.name ?? "anonymous";
|
|
34
|
+
throw new TypeError(`platformSerialize: non-plain object at ${formatPath(key)} (${ctor} instance)`);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
return val;
|
|
38
|
+
});
|
|
39
|
+
if (serialized === void 0) throw new TypeError("platformSerialize: value is not JSON-serializable at <root>");
|
|
40
|
+
return JSON.parse(serialized);
|
|
41
|
+
}
|
|
42
|
+
function formatPath(key) {
|
|
43
|
+
return key === "" ? "<root>" : `"${key}"`;
|
|
44
|
+
}
|
|
3
45
|
|
|
46
|
+
//#endregion
|
|
4
47
|
//#region src/vitest/workflow-runtime.ts
|
|
5
48
|
function createDefaultWorkflowRuntime() {
|
|
6
49
|
return {
|
|
7
|
-
triggerJobFunction: (name
|
|
8
|
-
|
|
50
|
+
triggerJobFunction: (name) => {
|
|
51
|
+
throw new Error(`No workflow job mock for "${name}". Acquire mockWorkflow() and call setJobHandler(...) or enqueueResult(...), or use runWorkflowLocally() for local workflow execution.`);
|
|
52
|
+
},
|
|
53
|
+
triggerWorkflow: async (_name, args) => {
|
|
54
|
+
platformSerialize(args);
|
|
55
|
+
return TRIGGER_DEFAULT;
|
|
56
|
+
},
|
|
9
57
|
wait: (key) => {
|
|
10
58
|
throw new Error(`No wait handler for "${key}". Acquire mockWorkflow() and call setWaitHandler(...).`);
|
|
11
59
|
},
|
|
@@ -105,5 +153,5 @@ function cleanupPlatformGlobals(global) {
|
|
|
105
153
|
}
|
|
106
154
|
|
|
107
155
|
//#endregion
|
|
108
|
-
export { cleanupPlatformGlobals as n, installPlatformGlobals as r, RUNTIME_FLAG_KEY as t };
|
|
109
|
-
//# sourceMappingURL=globals-
|
|
156
|
+
export { platformSerialize as i, cleanupPlatformGlobals as n, installPlatformGlobals as r, RUNTIME_FLAG_KEY as t };
|
|
157
|
+
//# sourceMappingURL=globals-Cf0sxIt8.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"globals-Cf0sxIt8.mjs","names":[],"sources":["../src/utils/test/platform-serialize.ts","../src/vitest/workflow-runtime.ts","../src/vitest/globals.ts"],"sourcesContent":["/**\n * Validate and serialize a value as it would cross the Platform JSON boundary.\n *\n * Mirrors the runtime checks the platform performs on workflow arguments,\n * wait payloads, and trigger inputs so that local tests fail in the same\n * places production fails.\n *\n * Throws on:\n * - `NaN` / `Infinity` / `-Infinity` (`JSON.stringify` would silently emit `null`)\n * - `BigInt` (TypeError is thrown by `JSON.stringify`; we emit a clearer message)\n * - Non-plain objects (class instances, including `Date`, `Map`, `Set`, `Error`,\n * and user-defined DTOs whose prototype is not `Object.prototype`)\n *\n * The replacer reads `this[key]` so the check sees the original value before\n * any `toJSON` conversion (e.g. `Date.prototype.toJSON`).\n * @param value - Value to validate and round-trip\n * @returns The JSON-normalized value (undefined/function properties stripped, etc.)\n */\nexport function platformSerialize<T>(value: T): T {\n // Top-level undefined is allowed (jobs may take no input).\n if (value === undefined) return undefined as T;\n\n // Root function/symbol stringify to `undefined`; throw a specific message here.\n if (typeof value === \"function\") {\n throw new TypeError(\"platformSerialize: function is not JSON-serializable at <root>\");\n }\n if (typeof value === \"symbol\") {\n throw new TypeError(\"platformSerialize: Symbol is not JSON-serializable at <root>\");\n }\n\n const serialized = JSON.stringify(value, function (key, val) {\n if (typeof val === \"number\" && !Number.isFinite(val)) {\n throw new TypeError(\n `platformSerialize: non-finite number at ${formatPath(key)}: ${String(val)}`,\n );\n }\n if (typeof val === \"bigint\") {\n throw new TypeError(\n `platformSerialize: BigInt is not JSON-serializable at ${formatPath(key)}`,\n );\n }\n // Look at the pre-toJSON value so Date/Map/Set/etc. can be detected.\n const raw = (this as Record<string, unknown>)[key];\n if (raw !== null && typeof raw === \"object\" && !Array.isArray(raw)) {\n const proto = Object.getPrototypeOf(raw);\n if (proto !== Object.prototype && proto !== null) {\n const ctor = (raw as { constructor?: { name?: string } }).constructor?.name ?? \"anonymous\";\n throw new TypeError(\n `platformSerialize: non-plain object at ${formatPath(key)} (${ctor} instance)`,\n );\n }\n }\n return val;\n });\n\n // `JSON.stringify` returns `undefined` when the root collapses (e.g. a `toJSON`\n // returning `undefined`); parsing that would throw opaquely.\n // JSON.stringify returns undefined for non-serializable values\n // oxlint-disable-next-line typescript/no-unnecessary-condition\n if (serialized === undefined) {\n throw new TypeError(\"platformSerialize: value is not JSON-serializable at <root>\");\n }\n\n return JSON.parse(serialized) as T;\n}\n\nfunction formatPath(key: string): string {\n return key === \"\" ? \"<root>\" : `\"${key}\"`;\n}\n","// 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 { TRIGGER_DEFAULT } from \"../configure/services/workflow/registry\";\nimport { platformSerialize } from \"../utils/test/platform-serialize\";\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) => {\n throw new Error(\n `No workflow job mock for \"${name}\". Acquire mockWorkflow() and call setJobHandler(...) or enqueueResult(...), or use runWorkflowLocally() for local workflow execution.`,\n );\n },\n triggerWorkflow: async (_name, args) => {\n platformSerialize(args);\n return TRIGGER_DEFAULT;\n },\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"],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