@tailor-platform/sdk 1.26.0 → 1.28.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +14 -0
- package/dist/application-CBJFUKrU.mjs +4701 -0
- package/dist/application-CBJFUKrU.mjs.map +1 -0
- package/dist/application-WyZetOky.mjs +11 -0
- package/dist/cli/index.mjs +240 -33
- package/dist/cli/index.mjs.map +1 -1
- package/dist/cli/lib.d.mts +6 -6
- package/dist/cli/lib.mjs +10 -8
- package/dist/cli/lib.mjs.map +1 -1
- package/dist/client-C2_wgujH.mjs +6 -0
- package/dist/{application-D9xahQRQ.mjs → client-bTbnbQbB.mjs} +8 -4877
- package/dist/{application-D9xahQRQ.mjs.map → client-bTbnbQbB.mjs.map} +1 -1
- package/dist/configure/index.d.mts +4 -4
- package/dist/crash-report-Cot_9Esm.mjs +6 -0
- package/dist/crash-report-Ju8cQF-l.mjs +414 -0
- package/dist/crash-report-Ju8cQF-l.mjs.map +1 -0
- package/dist/{enum-constants-6uK0VI_s.mjs → enum-constants-D1nfn0qD.mjs} +1 -1
- package/dist/{enum-constants-6uK0VI_s.mjs.map → enum-constants-D1nfn0qD.mjs.map} +1 -1
- package/dist/{env-CSsVESbH.d.mts → env-BuMbIknz.d.mts} +2 -2
- package/dist/{file-utils-2T9w20FP.mjs → file-utils-Bctuzn3x.mjs} +1 -1
- package/dist/{file-utils-2T9w20FP.mjs.map → file-utils-Bctuzn3x.mjs.map} +1 -1
- package/dist/{index-DgRShBpu.d.mts → index-B0Lrzywd.d.mts} +2 -2
- package/dist/{index-BtYPY8ya.d.mts → index-CbnLNm14.d.mts} +2 -2
- package/dist/{index-DkJbItB-.d.mts → index-CyapgSFI.d.mts} +2 -2
- package/dist/{index-BKy-OC5C.d.mts → index-D1AM_02Y.d.mts} +2 -2
- package/dist/{index-BJg0DTbR.d.mts → index-cD9sQLTh.d.mts} +15 -15
- package/dist/{interceptor-BPiIBTk_.mjs → interceptor-B0d_GrI5.mjs} +1 -1
- package/dist/{interceptor-BPiIBTk_.mjs.map → interceptor-B0d_GrI5.mjs.map} +1 -1
- package/dist/{kysely-type-cMNbsQ6k.mjs → kysely-type-B_IecdK9.mjs} +1 -1
- package/dist/{kysely-type-cMNbsQ6k.mjs.map → kysely-type-B_IecdK9.mjs.map} +1 -1
- package/dist/logger-CqezTedh.mjs +181 -0
- package/dist/logger-CqezTedh.mjs.map +1 -0
- package/dist/{package-json-CVUv8Y9T.mjs → package-json-D3x2nBPB.mjs} +1 -1
- package/dist/{package-json-CVUv8Y9T.mjs.map → package-json-D3x2nBPB.mjs.map} +1 -1
- package/dist/package-json-DHfTiUCS.mjs +4 -0
- package/dist/plugin/builtin/enum-constants/index.d.mts +1 -1
- package/dist/plugin/builtin/enum-constants/index.mjs +1 -1
- package/dist/plugin/builtin/file-utils/index.d.mts +1 -1
- package/dist/plugin/builtin/file-utils/index.mjs +1 -1
- package/dist/plugin/builtin/kysely-type/index.d.mts +1 -1
- package/dist/plugin/builtin/kysely-type/index.mjs +1 -1
- package/dist/plugin/builtin/seed/index.d.mts +1 -1
- package/dist/plugin/builtin/seed/index.mjs +1 -1
- package/dist/plugin/index.d.mts +2 -2
- package/dist/{plugin-B1hNwcCC.d.mts → plugin-D3a0-qe0.d.mts} +6 -2
- package/dist/{query-B8ml6ClT.mjs → query-WYq8RvYp.mjs} +10 -7
- package/dist/query-WYq8RvYp.mjs.map +1 -0
- package/dist/{seed-CCVRLibh.mjs → seed-CWkIDWMb.mjs} +1 -1
- package/dist/{seed-CCVRLibh.mjs.map → seed-CWkIDWMb.mjs.map} +1 -1
- package/dist/{telemetry-DDQZRqHK.mjs → telemetry-BevrwWwF.mjs} +1 -1
- package/dist/{telemetry-0w8OupuQ.mjs → telemetry-VvNfsyEE.mjs} +2 -2
- package/dist/{telemetry-0w8OupuQ.mjs.map → telemetry-VvNfsyEE.mjs.map} +1 -1
- package/dist/utils/test/index.d.mts +2 -2
- package/dist/{workflow.generated-Bm4b8hEk.d.mts → workflow.generated-BsgIlrH-.d.mts} +2 -2
- package/docs/cli/crash-report.md +107 -0
- package/docs/cli/secret.md +16 -14
- package/docs/cli-reference.md +11 -0
- package/docs/configuration.md +19 -0
- package/docs/services/resolver.md +32 -0
- package/docs/services/secret.md +81 -0
- package/package.json +1 -1
- package/dist/application-CxH6Yp54.mjs +0 -9
- package/dist/package-json-Bj76LPsV.mjs +0 -4
- package/dist/query-B8ml6ClT.mjs.map +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { A as DefinedAuth, At as BuiltinIdP, B as TailorDBField, Bt as SCIMResource, D as AuthOwnConfig, E as AuthExternalConfig, F as UserAttributeMap, Ft as SAML, G as TailorTypeGqlPermission, H as TailorDBType, I as UsernameFieldKey, It as SCIMAttribute, J as unsafeAllowAllTypePermission, K as TailorTypePermission, L as ValueOperand, Lt as SCIMAttributeMapping, M as SCIMAttributeType, Mt as IdProvider, N as UserAttributeKey, Nt as OAuth2ClientInput, O as AuthServiceInput, P as UserAttributeListKey, Pt as OIDC, R as TailorAnyDBField, Rt as SCIMAuthorization, T as AuthConfig, U as db, V as TailorDBInstance, Vt as TenantProvider, W as PermissionCondition, _ as GeneratorResult, a as PluginExecutorContext, b as TailorDBNamespaceData, c as PluginGeneratedExecutorWithFile, d as PluginNamespaceProcessContext, dt as unauthenticatedTailorUser, f as PluginOutput, g as ExecutorReadyContext, h as TypePluginOutput, i as PluginConfigs, j as OAuth2ClientGrantType, jt as IDToken, k as BeforeLoginHookArgs, l as PluginGeneratedResolver, m as TailorDBTypeForPlugin, mt as Resolver, n as Plugin, nt as TailorField, o as PluginExecutorContextBase, ot as AttributeList, p as PluginProcessContext, q as unsafeAllowAllGqlPermission, r as PluginAttachment, s as PluginGeneratedExecutor, st as AttributeMap, t as NamespacePluginOutput, u as PluginGeneratedType, ut as TailorUser, v as ResolverNamespaceData, x as TailorDBReadyContext, y as ResolverReadyContext, z as TailorAnyDBType, zt as SCIMConfig } from "../plugin-
|
|
2
|
-
import { t as Env } from "../env-
|
|
3
|
-
import { _ as IdPGqlOperations, a as ResolverExternalConfig, c as WorkflowServiceConfig, d as defineStaticWebSite, f as SecretsConfig, h as IdPExternalConfig, i as ExecutorServiceInput, l as WorkflowServiceInput, m as IdPConfig, o as ResolverServiceConfig, p as defineSecretManager, r as ExecutorServiceConfig, s as ResolverServiceInput, t as RetryPolicy, u as StaticWebsiteConfig, v as IdPGqlOperationsInput } from "../workflow.generated-
|
|
4
|
-
import { $ as AuthInvoker, A as idpUserCreatedTrigger, B as WebhookOperation, C as RecordTrigger, D as authAccessTokenIssuedTrigger, E as ResolverExecutedTrigger, F as recordUpdatedTrigger, G as WORKFLOW_TEST_ENV_KEY, H as Workflow, I as resolverExecutedTrigger, J as WorkflowJobInput, K as WorkflowJob, L as FunctionOperation, M as idpUserUpdatedTrigger, N as recordCreatedTrigger, O as authAccessTokenRefreshedTrigger, P as recordDeletedTrigger, Q as createResolver, R as GqlOperation, S as RecordDeletedArgs, T as ResolverExecutedArgs, U as WorkflowConfig, V as WorkflowOperation, W as createWorkflow, X as createWorkflowJob, Y as WorkflowJobOutput, Z as QueryType, _ as AuthAccessTokenArgs, a as defineGenerators, b as IdpUserTrigger, c as createExecutor, d as IncomingWebhookRequest, et as defineAuth, f as IncomingWebhookTrigger, g as scheduleTrigger, h as ScheduleTrigger, i as defineConfig, j as idpUserDeletedTrigger, k as authAccessTokenRevokedTrigger, l as Trigger, m as ScheduleArgs, n as output, o as definePlugins, p as incomingWebhookTrigger, q as WorkflowJobContext, r as t, s as defineIdp, t as __Infer, u as IncomingWebhookArgs, v as AuthAccessTokenTrigger, w as RecordUpdatedArgs, x as RecordCreatedArgs, y as IdpUserArgs, z as Operation } from "../index-
|
|
1
|
+
import { A as DefinedAuth, At as BuiltinIdP, B as TailorDBField, Bt as SCIMResource, D as AuthOwnConfig, E as AuthExternalConfig, F as UserAttributeMap, Ft as SAML, G as TailorTypeGqlPermission, H as TailorDBType, I as UsernameFieldKey, It as SCIMAttribute, J as unsafeAllowAllTypePermission, K as TailorTypePermission, L as ValueOperand, Lt as SCIMAttributeMapping, M as SCIMAttributeType, Mt as IdProvider, N as UserAttributeKey, Nt as OAuth2ClientInput, O as AuthServiceInput, P as UserAttributeListKey, Pt as OIDC, R as TailorAnyDBField, Rt as SCIMAuthorization, T as AuthConfig, U as db, V as TailorDBInstance, Vt as TenantProvider, W as PermissionCondition, _ as GeneratorResult, a as PluginExecutorContext, b as TailorDBNamespaceData, c as PluginGeneratedExecutorWithFile, d as PluginNamespaceProcessContext, dt as unauthenticatedTailorUser, f as PluginOutput, g as ExecutorReadyContext, h as TypePluginOutput, i as PluginConfigs, j as OAuth2ClientGrantType, jt as IDToken, k as BeforeLoginHookArgs, l as PluginGeneratedResolver, m as TailorDBTypeForPlugin, mt as Resolver, n as Plugin, nt as TailorField, o as PluginExecutorContextBase, ot as AttributeList, p as PluginProcessContext, q as unsafeAllowAllGqlPermission, r as PluginAttachment, s as PluginGeneratedExecutor, st as AttributeMap, t as NamespacePluginOutput, u as PluginGeneratedType, ut as TailorUser, v as ResolverNamespaceData, x as TailorDBReadyContext, y as ResolverReadyContext, z as TailorAnyDBType, zt as SCIMConfig } from "../plugin-D3a0-qe0.mjs";
|
|
2
|
+
import { t as Env } from "../env-BuMbIknz.mjs";
|
|
3
|
+
import { _ as IdPGqlOperations, a as ResolverExternalConfig, c as WorkflowServiceConfig, d as defineStaticWebSite, f as SecretsConfig, h as IdPExternalConfig, i as ExecutorServiceInput, l as WorkflowServiceInput, m as IdPConfig, o as ResolverServiceConfig, p as defineSecretManager, r as ExecutorServiceConfig, s as ResolverServiceInput, t as RetryPolicy, u as StaticWebsiteConfig, v as IdPGqlOperationsInput } from "../workflow.generated-BsgIlrH-.mjs";
|
|
4
|
+
import { $ as AuthInvoker, A as idpUserCreatedTrigger, B as WebhookOperation, C as RecordTrigger, D as authAccessTokenIssuedTrigger, E as ResolverExecutedTrigger, F as recordUpdatedTrigger, G as WORKFLOW_TEST_ENV_KEY, H as Workflow, I as resolverExecutedTrigger, J as WorkflowJobInput, K as WorkflowJob, L as FunctionOperation, M as idpUserUpdatedTrigger, N as recordCreatedTrigger, O as authAccessTokenRefreshedTrigger, P as recordDeletedTrigger, Q as createResolver, R as GqlOperation, S as RecordDeletedArgs, T as ResolverExecutedArgs, U as WorkflowConfig, V as WorkflowOperation, W as createWorkflow, X as createWorkflowJob, Y as WorkflowJobOutput, Z as QueryType, _ as AuthAccessTokenArgs, a as defineGenerators, b as IdpUserTrigger, c as createExecutor, d as IncomingWebhookRequest, et as defineAuth, f as IncomingWebhookTrigger, g as scheduleTrigger, h as ScheduleTrigger, i as defineConfig, j as idpUserDeletedTrigger, k as authAccessTokenRevokedTrigger, l as Trigger, m as ScheduleArgs, n as output, o as definePlugins, p as incomingWebhookTrigger, q as WorkflowJobContext, r as t, s as defineIdp, t as __Infer, u as IncomingWebhookArgs, v as AuthAccessTokenTrigger, w as RecordUpdatedArgs, x as RecordCreatedArgs, y as IdpUserArgs, z as Operation } from "../index-cD9sQLTh.mjs";
|
|
5
5
|
export { AttributeList, AttributeMap, AuthAccessTokenArgs, AuthAccessTokenTrigger, AuthConfig, AuthExternalConfig, AuthInvoker, AuthOwnConfig, AuthServiceInput, BeforeLoginHookArgs, BuiltinIdP, DefinedAuth, Env, ExecutorReadyContext, ExecutorServiceConfig, ExecutorServiceInput, FunctionOperation, GeneratorResult, GqlOperation, IDToken, IdPConfig, IdPExternalConfig, IdPGqlOperations, IdPGqlOperationsInput as IdPGqlOperationsConfig, IdProvider as IdProviderConfig, IdpUserArgs, IdpUserTrigger, IncomingWebhookArgs, IncomingWebhookRequest, IncomingWebhookTrigger, NamespacePluginOutput, OAuth2ClientInput as OAuth2Client, OAuth2ClientGrantType, OIDC, Operation, PermissionCondition, Plugin, PluginAttachment, PluginConfigs, PluginExecutorContext, PluginExecutorContextBase, PluginGeneratedExecutor, PluginGeneratedExecutorWithFile, PluginGeneratedResolver, PluginGeneratedType, PluginNamespaceProcessContext, PluginOutput, PluginProcessContext, QueryType, RecordCreatedArgs, RecordDeletedArgs, RecordTrigger, RecordUpdatedArgs, Resolver, ResolverExecutedArgs, ResolverExecutedTrigger, ResolverExternalConfig, ResolverNamespaceData, ResolverReadyContext, ResolverServiceConfig, ResolverServiceInput, RetryPolicy, SAML, SCIMAttribute, SCIMAttributeMapping, SCIMAttributeType, SCIMAuthorization, SCIMConfig, SCIMResource, ScheduleArgs, ScheduleTrigger, SecretsConfig, StaticWebsiteConfig, TailorAnyDBField, TailorAnyDBType, TailorDBField, TailorDBInstance, TailorDBNamespaceData, TailorDBReadyContext, TailorDBType, TailorDBTypeForPlugin, TailorField, TailorTypeGqlPermission, TailorTypePermission, TailorUser, TenantProvider as TenantProviderConfig, Trigger, TypePluginOutput, UserAttributeKey, UserAttributeListKey, UserAttributeMap, UsernameFieldKey, ValueOperand, WORKFLOW_TEST_ENV_KEY, WebhookOperation, Workflow, WorkflowConfig, WorkflowJob, WorkflowJobContext, WorkflowJobInput, WorkflowJobOutput, WorkflowOperation, WorkflowServiceConfig, WorkflowServiceInput, authAccessTokenIssuedTrigger, authAccessTokenRefreshedTrigger, authAccessTokenRevokedTrigger, createExecutor, createResolver, createWorkflow, createWorkflowJob, db, defineAuth, defineConfig, defineGenerators, defineIdp, definePlugins, defineSecretManager, defineStaticWebSite, idpUserCreatedTrigger, idpUserDeletedTrigger, idpUserUpdatedTrigger, incomingWebhookTrigger, infer, output, recordCreatedTrigger, recordDeletedTrigger, recordUpdatedTrigger, resolverExecutedTrigger, scheduleTrigger, t, unauthenticatedTailorUser, unsafeAllowAllGqlPermission, unsafeAllowAllTypePermission };
|
|
@@ -0,0 +1,414 @@
|
|
|
1
|
+
import { n as logger } from "./logger-CqezTedh.mjs";
|
|
2
|
+
import { t as readPackageJson } from "./package-json-D3x2nBPB.mjs";
|
|
3
|
+
import * as fs from "node:fs";
|
|
4
|
+
import * as path from "pathe";
|
|
5
|
+
import * as os from "node:os";
|
|
6
|
+
import { parseYAML } from "confbox";
|
|
7
|
+
import { xdgConfig } from "xdg-basedir";
|
|
8
|
+
import * as crypto from "node:crypto";
|
|
9
|
+
import { isCI } from "std-env";
|
|
10
|
+
|
|
11
|
+
//#region src/cli/crash-report/config.ts
|
|
12
|
+
/**
|
|
13
|
+
* Parse crash report configuration from environment variables.
|
|
14
|
+
* Local crash log writing is enabled by default (opt-out via TAILOR_CRASH_REPORTS_LOCAL=off).
|
|
15
|
+
* Remote sending is disabled by default (opt-in via TAILOR_CRASH_REPORTS_REMOTE=on).
|
|
16
|
+
* Both are auto-disabled in CI environments.
|
|
17
|
+
* @returns Crash report configuration
|
|
18
|
+
*/
|
|
19
|
+
function parseCrashReportConfig() {
|
|
20
|
+
if (isCI) return {
|
|
21
|
+
localEnabled: false,
|
|
22
|
+
remoteEnabled: false,
|
|
23
|
+
localDir: ""
|
|
24
|
+
};
|
|
25
|
+
const localEnabled = (process.env.TAILOR_CRASH_REPORTS_LOCAL ?? "on").toLowerCase() !== "off";
|
|
26
|
+
const remoteEnabled = (process.env.TAILOR_CRASH_REPORTS_REMOTE ?? "off").toLowerCase() === "on";
|
|
27
|
+
const localDir = xdgConfig ? path.join(xdgConfig, "tailor-platform", "crash-reports") : "";
|
|
28
|
+
return {
|
|
29
|
+
localEnabled: localEnabled && localDir !== "",
|
|
30
|
+
remoteEnabled,
|
|
31
|
+
localDir
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
//#endregion
|
|
36
|
+
//#region src/cli/crash-report/writer.ts
|
|
37
|
+
const MAX_CRASH_FILES = 10;
|
|
38
|
+
/** Marker line that separates human-readable content from the JSON footer. */
|
|
39
|
+
const JSON_FOOTER_MARKER = "--- JSON ---";
|
|
40
|
+
/** File extension for crash log files. */
|
|
41
|
+
const CRASH_LOG_EXTENSION = ".crash.log";
|
|
42
|
+
/**
|
|
43
|
+
* Format a CrashReport as human-readable text for local crash log files.
|
|
44
|
+
* @param report - Crash report to format
|
|
45
|
+
* @returns Formatted text content
|
|
46
|
+
*/
|
|
47
|
+
function formatCrashReport(report) {
|
|
48
|
+
return [
|
|
49
|
+
`Crash Report: ${report.id}`,
|
|
50
|
+
`Timestamp: ${report.timestamp}`,
|
|
51
|
+
`Error Type: ${report.errorType}`,
|
|
52
|
+
"",
|
|
53
|
+
"--- Environment ---",
|
|
54
|
+
`SDK Version: ${report.sdkVersion}`,
|
|
55
|
+
`Node Version: ${report.nodeVersion}`,
|
|
56
|
+
`OS: ${report.osPlatform} ${report.osRelease}`,
|
|
57
|
+
`Arch: ${report.arch}`,
|
|
58
|
+
"",
|
|
59
|
+
"--- Command ---",
|
|
60
|
+
`Command: ${report.command}`,
|
|
61
|
+
`Arguments: ${JSON.stringify(report.argv)}`,
|
|
62
|
+
"",
|
|
63
|
+
"--- Error ---",
|
|
64
|
+
`Name: ${report.errorName}`,
|
|
65
|
+
`Message: ${report.errorMessage}`,
|
|
66
|
+
"",
|
|
67
|
+
"--- Stack Trace ---",
|
|
68
|
+
report.stackTrace || "(no stack trace available)",
|
|
69
|
+
"",
|
|
70
|
+
JSON_FOOTER_MARKER,
|
|
71
|
+
JSON.stringify(report),
|
|
72
|
+
""
|
|
73
|
+
].join("\n");
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Generate a filename for a crash log file.
|
|
77
|
+
* Format: {timestamp}-{shortId}.crash.log
|
|
78
|
+
* @param report - Crash report to generate filename for
|
|
79
|
+
* @returns Filename string
|
|
80
|
+
*/
|
|
81
|
+
function generateFilename(report) {
|
|
82
|
+
return `${report.timestamp.replace(/[:.]/g, "-")}-${report.id.slice(0, 8)}${CRASH_LOG_EXTENSION}`;
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Remove old crash log files, keeping only the most recent ones.
|
|
86
|
+
* @param dir - Crash log directory
|
|
87
|
+
*/
|
|
88
|
+
function cleanupOldFiles(dir) {
|
|
89
|
+
try {
|
|
90
|
+
const files = fs.readdirSync(dir).filter((f) => f.endsWith(CRASH_LOG_EXTENSION)).sort().reverse();
|
|
91
|
+
for (const file of files.slice(MAX_CRASH_FILES)) fs.unlinkSync(path.join(dir, file));
|
|
92
|
+
} catch {}
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Write a crash report to a local file.
|
|
96
|
+
* Creates the directory if it doesn't exist. Keeps only the last 10 crash files.
|
|
97
|
+
* Never throws - returns the file path on success or undefined on failure.
|
|
98
|
+
* @param report - Crash report to write
|
|
99
|
+
* @param dir - Directory to write the crash log file to
|
|
100
|
+
* @returns File path on success, undefined on failure
|
|
101
|
+
*/
|
|
102
|
+
function writeCrashReport(report, dir) {
|
|
103
|
+
try {
|
|
104
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
105
|
+
const filename = generateFilename(report);
|
|
106
|
+
const filePath = path.join(dir, filename);
|
|
107
|
+
const content = formatCrashReport(report);
|
|
108
|
+
fs.writeFileSync(filePath, content, "utf-8");
|
|
109
|
+
cleanupOldFiles(dir);
|
|
110
|
+
return filePath;
|
|
111
|
+
} catch {
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
//#endregion
|
|
117
|
+
//#region src/cli/crash-report/sender.ts
|
|
118
|
+
const SEND_TIMEOUT_MS = 5e3;
|
|
119
|
+
const PRODUCTION_ENDPOINT = "https://sdk-error-tracking-926vh9t4cl.erp.dev/query";
|
|
120
|
+
const SUBMIT_MUTATION = `
|
|
121
|
+
mutation SubmitCrashReport(
|
|
122
|
+
$id: String!
|
|
123
|
+
$timestamp: String!
|
|
124
|
+
$sdkVersion: String!
|
|
125
|
+
$nodeVersion: String!
|
|
126
|
+
$osPlatform: String!
|
|
127
|
+
$osRelease: String!
|
|
128
|
+
$arch: String!
|
|
129
|
+
$command: String!
|
|
130
|
+
$argv: [String]
|
|
131
|
+
$errorName: String!
|
|
132
|
+
$errorMessage: String!
|
|
133
|
+
$stackTrace: String
|
|
134
|
+
$errorType: String!
|
|
135
|
+
$userId: String
|
|
136
|
+
$userEmail: String
|
|
137
|
+
) {
|
|
138
|
+
submitCrashReport(
|
|
139
|
+
id: $id
|
|
140
|
+
timestamp: $timestamp
|
|
141
|
+
sdkVersion: $sdkVersion
|
|
142
|
+
nodeVersion: $nodeVersion
|
|
143
|
+
osPlatform: $osPlatform
|
|
144
|
+
osRelease: $osRelease
|
|
145
|
+
arch: $arch
|
|
146
|
+
command: $command
|
|
147
|
+
argv: $argv
|
|
148
|
+
errorName: $errorName
|
|
149
|
+
errorMessage: $errorMessage
|
|
150
|
+
stackTrace: $stackTrace
|
|
151
|
+
errorType: $errorType
|
|
152
|
+
userId: $userId
|
|
153
|
+
userEmail: $userEmail
|
|
154
|
+
) {
|
|
155
|
+
success
|
|
156
|
+
}
|
|
157
|
+
}`;
|
|
158
|
+
/**
|
|
159
|
+
* Send a crash report to the remote endpoint via GraphQL mutation.
|
|
160
|
+
* Best-effort: never throws, returns boolean success.
|
|
161
|
+
* @param report - Crash report to send
|
|
162
|
+
* @param ua - User-Agent header value
|
|
163
|
+
* @returns true if the request succeeded, false otherwise
|
|
164
|
+
*/
|
|
165
|
+
async function sendCrashReport(report, ua) {
|
|
166
|
+
try {
|
|
167
|
+
const endpoint = process.env.TAILOR_CRASH_REPORT_ENDPOINT || PRODUCTION_ENDPOINT;
|
|
168
|
+
const response = await fetch(endpoint, {
|
|
169
|
+
method: "POST",
|
|
170
|
+
headers: {
|
|
171
|
+
"Content-Type": "application/json",
|
|
172
|
+
"User-Agent": ua
|
|
173
|
+
},
|
|
174
|
+
body: JSON.stringify({
|
|
175
|
+
query: SUBMIT_MUTATION,
|
|
176
|
+
variables: report
|
|
177
|
+
}),
|
|
178
|
+
signal: AbortSignal.timeout(SEND_TIMEOUT_MS)
|
|
179
|
+
});
|
|
180
|
+
if (!response.ok) return false;
|
|
181
|
+
const data = await response.json();
|
|
182
|
+
if (data.errors?.length) return false;
|
|
183
|
+
return data.data?.submitCrashReport.success === true;
|
|
184
|
+
} catch {
|
|
185
|
+
return false;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
//#endregion
|
|
190
|
+
//#region src/cli/crash-report/sanitize.ts
|
|
191
|
+
const HOME_DIR = os.homedir();
|
|
192
|
+
const 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;
|
|
193
|
+
const LONG_HEX_PATTERN = /\b[0-9a-fA-F]{32,}\b/g;
|
|
194
|
+
const EMAIL_PATTERN = /\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}\b/g;
|
|
195
|
+
const ABSOLUTE_PATH_PATTERN = /(?:\/(?:[\w.@\- ]+\/)+[\w.@\- ]+)/g;
|
|
196
|
+
const WINDOWS_PATH_PATTERN = /(?:[A-Za-z]:\\(?:[\w.@\- ]+\\)+[\w.@\- ]+)/g;
|
|
197
|
+
const URL_QUERY_PATTERN = /[?&][^?\s]*/g;
|
|
198
|
+
const EMAIL_TEST_PATTERN = /\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}\b/;
|
|
199
|
+
const WINDOWS_DRIVE_TEST_PATTERN = /^[A-Za-z]:\\/;
|
|
200
|
+
const SDK_PACKAGE_MARKER = "packages/sdk/";
|
|
201
|
+
function lastSegment(filePath, separator) {
|
|
202
|
+
return filePath.split(separator).pop() ?? filePath;
|
|
203
|
+
}
|
|
204
|
+
/**
|
|
205
|
+
* Sanitize a stack trace by replacing absolute paths with relative SDK paths.
|
|
206
|
+
* External paths are replaced with `<external>/filename.ext`.
|
|
207
|
+
* Home directories are replaced with `~/<redacted>/`.
|
|
208
|
+
* @param stack - Raw stack trace string
|
|
209
|
+
* @returns Sanitized stack trace
|
|
210
|
+
*/
|
|
211
|
+
function sanitizeStackTrace(stack) {
|
|
212
|
+
const firstFrameIndex = stack.search(/\n\s+at /);
|
|
213
|
+
let result;
|
|
214
|
+
if (firstFrameIndex !== -1) result = sanitizeMessage(stack.slice(0, firstFrameIndex)) + stack.slice(firstFrameIndex);
|
|
215
|
+
else result = sanitizeMessage(stack);
|
|
216
|
+
result = result.replace(ABSOLUTE_PATH_PATTERN, (match) => {
|
|
217
|
+
const sdkIndex = match.indexOf(SDK_PACKAGE_MARKER);
|
|
218
|
+
if (sdkIndex !== -1) return match.slice(sdkIndex);
|
|
219
|
+
if (match.startsWith(HOME_DIR)) return `~/<redacted>/${lastSegment(match, "/")}`;
|
|
220
|
+
return `<external>/${lastSegment(match, "/")}`;
|
|
221
|
+
});
|
|
222
|
+
result = result.replace(WINDOWS_PATH_PATTERN, (match) => {
|
|
223
|
+
const normalized = match.replace(/\\/g, "/");
|
|
224
|
+
const sdkIndex = normalized.indexOf(SDK_PACKAGE_MARKER);
|
|
225
|
+
if (sdkIndex !== -1) return normalized.slice(sdkIndex);
|
|
226
|
+
return `<external>/${lastSegment(match, "\\")}`;
|
|
227
|
+
});
|
|
228
|
+
return result;
|
|
229
|
+
}
|
|
230
|
+
/**
|
|
231
|
+
* Sanitize an error message by redacting sensitive information.
|
|
232
|
+
* Redacts: UUIDs, long hex tokens, email addresses, absolute paths, URL query strings.
|
|
233
|
+
* @param message - Raw error message
|
|
234
|
+
* @returns Sanitized error message
|
|
235
|
+
*/
|
|
236
|
+
function sanitizeMessage(message) {
|
|
237
|
+
let result = message;
|
|
238
|
+
result = result.replace(/\nRequest:\s*[\s\S]*$/, "\nRequest: <redacted>");
|
|
239
|
+
result = result.replace(UUID_PATTERN, "<uuid>");
|
|
240
|
+
result = result.replace(LONG_HEX_PATTERN, "<redacted>");
|
|
241
|
+
result = result.replace(EMAIL_PATTERN, "<email>");
|
|
242
|
+
result = result.replace(URL_QUERY_PATTERN, "?<redacted>");
|
|
243
|
+
result = result.replace(ABSOLUTE_PATH_PATTERN, (match) => `<path>/${lastSegment(match, "/")}`);
|
|
244
|
+
result = result.replace(WINDOWS_PATH_PATTERN, (match) => `<path>/${lastSegment(match, "\\")}`);
|
|
245
|
+
return result;
|
|
246
|
+
}
|
|
247
|
+
/**
|
|
248
|
+
* Sanitize process.argv by keeping command/subcommand names and redacting
|
|
249
|
+
* values of sensitive flags.
|
|
250
|
+
* @param argv - Raw process.argv array
|
|
251
|
+
* @returns Sanitized argv array
|
|
252
|
+
*/
|
|
253
|
+
function sanitizeArgv(argv) {
|
|
254
|
+
const result = [];
|
|
255
|
+
let redactNext = false;
|
|
256
|
+
for (const arg of argv) {
|
|
257
|
+
if (redactNext) {
|
|
258
|
+
if (!arg.startsWith("-")) {
|
|
259
|
+
result.push("<redacted>");
|
|
260
|
+
redactNext = false;
|
|
261
|
+
continue;
|
|
262
|
+
}
|
|
263
|
+
redactNext = false;
|
|
264
|
+
}
|
|
265
|
+
if (arg.startsWith("-")) {
|
|
266
|
+
const eqIndex = arg.indexOf("=");
|
|
267
|
+
if (eqIndex !== -1) {
|
|
268
|
+
result.push(`${arg.slice(0, eqIndex)}=<redacted>`);
|
|
269
|
+
continue;
|
|
270
|
+
}
|
|
271
|
+
result.push(arg);
|
|
272
|
+
redactNext = true;
|
|
273
|
+
continue;
|
|
274
|
+
}
|
|
275
|
+
if (arg.startsWith("/") && arg.includes("/", 1)) {
|
|
276
|
+
result.push("<path>");
|
|
277
|
+
continue;
|
|
278
|
+
}
|
|
279
|
+
if (WINDOWS_DRIVE_TEST_PATTERN.test(arg)) {
|
|
280
|
+
result.push("<path>");
|
|
281
|
+
continue;
|
|
282
|
+
}
|
|
283
|
+
if (EMAIL_TEST_PATTERN.test(arg)) {
|
|
284
|
+
result.push("<email>");
|
|
285
|
+
continue;
|
|
286
|
+
}
|
|
287
|
+
result.push(arg);
|
|
288
|
+
}
|
|
289
|
+
return result;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
//#endregion
|
|
293
|
+
//#region src/cli/crash-report/report.ts
|
|
294
|
+
const MAX_COMMAND_TOKENS = 3;
|
|
295
|
+
/**
|
|
296
|
+
* Parse the command name from process.argv.
|
|
297
|
+
* Extracts up to MAX_COMMAND_TOKENS non-flag arguments after the script name.
|
|
298
|
+
* @returns Parsed command string
|
|
299
|
+
*/
|
|
300
|
+
function parseCommand() {
|
|
301
|
+
const args = process.argv.slice(2);
|
|
302
|
+
const commandParts = [];
|
|
303
|
+
for (const arg of args) {
|
|
304
|
+
if (arg.startsWith("-") || commandParts.length >= MAX_COMMAND_TOKENS) break;
|
|
305
|
+
commandParts.push(arg);
|
|
306
|
+
}
|
|
307
|
+
return commandParts.join(" ") || "<unknown>";
|
|
308
|
+
}
|
|
309
|
+
/**
|
|
310
|
+
* Build a CrashReport data structure from an error and context.
|
|
311
|
+
* All sensitive data is sanitized before inclusion.
|
|
312
|
+
* @param options - Error, SDK version, and crash type
|
|
313
|
+
* @returns Sanitized crash report
|
|
314
|
+
*/
|
|
315
|
+
function buildCrashReport(options) {
|
|
316
|
+
const { error, sdkVersion, errorType } = options;
|
|
317
|
+
const isError = error instanceof Error;
|
|
318
|
+
const rawMessage = isError ? error.message : String(error);
|
|
319
|
+
const rawStack = isError && error.stack ? error.stack : "";
|
|
320
|
+
const errorName = isError ? error.name : "UnknownError";
|
|
321
|
+
const currentUser = readCurrentUser();
|
|
322
|
+
return {
|
|
323
|
+
id: crypto.randomUUID(),
|
|
324
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
325
|
+
sdkVersion,
|
|
326
|
+
nodeVersion: process.version,
|
|
327
|
+
osPlatform: process.platform,
|
|
328
|
+
osRelease: os.release(),
|
|
329
|
+
arch: process.arch,
|
|
330
|
+
command: sanitizeMessage(parseCommand()),
|
|
331
|
+
argv: sanitizeArgv(process.argv),
|
|
332
|
+
errorName,
|
|
333
|
+
errorMessage: sanitizeMessage(rawMessage),
|
|
334
|
+
stackTrace: sanitizeStackTrace(rawStack),
|
|
335
|
+
errorType,
|
|
336
|
+
userId: currentUser,
|
|
337
|
+
userEmail: currentUser
|
|
338
|
+
};
|
|
339
|
+
}
|
|
340
|
+
/**
|
|
341
|
+
* Read current_user from Tailor Platform config without side effects.
|
|
342
|
+
* Unlike readPlatformConfig(), this never triggers migration or logs warnings.
|
|
343
|
+
* @returns The current user email, or null if unavailable
|
|
344
|
+
*/
|
|
345
|
+
function readCurrentUser() {
|
|
346
|
+
try {
|
|
347
|
+
if (!xdgConfig) return null;
|
|
348
|
+
const configPath = path.join(xdgConfig, "tailor-platform", "config.yaml");
|
|
349
|
+
if (!fs.existsSync(configPath)) return null;
|
|
350
|
+
return parseYAML(fs.readFileSync(configPath, "utf-8"))?.current_user ?? null;
|
|
351
|
+
} catch {
|
|
352
|
+
return null;
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
//#endregion
|
|
357
|
+
//#region src/cli/crash-report/index.ts
|
|
358
|
+
/**
|
|
359
|
+
* Report an unexpected crash. Writes a local crash log file and optionally
|
|
360
|
+
* sends the report to a remote endpoint. Displays a user-facing message
|
|
361
|
+
* with the crash log path and a command to submit the report.
|
|
362
|
+
*
|
|
363
|
+
* Never throws - all errors are silently caught.
|
|
364
|
+
* @param error - The error that caused the crash
|
|
365
|
+
* @param errorType - How the error was caught
|
|
366
|
+
*/
|
|
367
|
+
async function reportCrash(error, errorType) {
|
|
368
|
+
try {
|
|
369
|
+
const config = parseCrashReportConfig();
|
|
370
|
+
if (!config.localEnabled && !config.remoteEnabled) return;
|
|
371
|
+
const report = buildCrashReport({
|
|
372
|
+
error,
|
|
373
|
+
sdkVersion: (await readPackageJson()).version ?? "unknown",
|
|
374
|
+
errorType
|
|
375
|
+
});
|
|
376
|
+
if (config.localEnabled) {
|
|
377
|
+
const filePath = writeCrashReport(report, config.localDir);
|
|
378
|
+
if (filePath) logger.log([
|
|
379
|
+
"",
|
|
380
|
+
"An unexpected error occurred. A crash report has been saved to:",
|
|
381
|
+
` ${filePath}`,
|
|
382
|
+
"",
|
|
383
|
+
"To submit this report:",
|
|
384
|
+
` tailor-sdk crash-report send --file "${filePath}"`
|
|
385
|
+
].join("\n"));
|
|
386
|
+
}
|
|
387
|
+
if (config.remoteEnabled) {
|
|
388
|
+
const { userAgent } = await import("./client-C2_wgujH.mjs");
|
|
389
|
+
await sendCrashReport(report, await userAgent());
|
|
390
|
+
}
|
|
391
|
+
} catch {}
|
|
392
|
+
}
|
|
393
|
+
/**
|
|
394
|
+
* Register global uncaughtException and unhandledRejection handlers.
|
|
395
|
+
* These catch errors outside the normal cleanup flow (e.g., during
|
|
396
|
+
* argument parsing). Should be called once at CLI startup before runMain.
|
|
397
|
+
*/
|
|
398
|
+
function initCrashReporting() {
|
|
399
|
+
const config = parseCrashReportConfig();
|
|
400
|
+
if (!config.localEnabled && !config.remoteEnabled) return;
|
|
401
|
+
const handleFatal = (error, errorType) => {
|
|
402
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
403
|
+
logger.error(message);
|
|
404
|
+
reportCrash(error, errorType).finally(() => {
|
|
405
|
+
process.exit(1);
|
|
406
|
+
});
|
|
407
|
+
};
|
|
408
|
+
process.on("uncaughtException", (error) => handleFatal(error, "uncaughtException"));
|
|
409
|
+
process.on("unhandledRejection", (reason) => handleFatal(reason, "unhandledRejection"));
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
//#endregion
|
|
413
|
+
export { JSON_FOOTER_MARKER as a, CRASH_LOG_EXTENSION as i, reportCrash as n, parseCrashReportConfig as o, sendCrashReport as r, initCrashReporting as t };
|
|
414
|
+
//# sourceMappingURL=crash-report-Ju8cQF-l.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"crash-report-Ju8cQF-l.mjs","names":[],"sources":["../src/cli/crash-report/config.ts","../src/cli/crash-report/writer.ts","../src/cli/crash-report/sender.ts","../src/cli/crash-report/sanitize.ts","../src/cli/crash-report/report.ts","../src/cli/crash-report/index.ts"],"sourcesContent":["import * as path from \"pathe\";\nimport { isCI } from \"std-env\";\nimport { xdgConfig } from \"xdg-basedir\";\n\nexport interface CrashReportConfig {\n readonly localEnabled: boolean;\n readonly remoteEnabled: boolean;\n readonly localDir: string;\n}\n\n/**\n * Parse crash report configuration from environment variables.\n * Local crash log writing is enabled by default (opt-out via TAILOR_CRASH_REPORTS_LOCAL=off).\n * Remote sending is disabled by default (opt-in via TAILOR_CRASH_REPORTS_REMOTE=on).\n * Both are auto-disabled in CI environments.\n * @returns Crash report configuration\n */\nexport function parseCrashReportConfig(): CrashReportConfig {\n if (isCI) {\n return {\n localEnabled: false,\n remoteEnabled: false,\n localDir: \"\",\n };\n }\n\n const localEnabled = (process.env.TAILOR_CRASH_REPORTS_LOCAL ?? \"on\").toLowerCase() !== \"off\";\n const remoteEnabled = (process.env.TAILOR_CRASH_REPORTS_REMOTE ?? \"off\").toLowerCase() === \"on\";\n const localDir = xdgConfig ? path.join(xdgConfig, \"tailor-platform\", \"crash-reports\") : \"\";\n\n return {\n localEnabled: localEnabled && localDir !== \"\",\n remoteEnabled,\n localDir,\n };\n}\n","import * as fs from \"node:fs\";\nimport * as path from \"pathe\";\nimport type { CrashReport } from \"./report\";\n\nconst MAX_CRASH_FILES = 10;\n\n/** Marker line that separates human-readable content from the JSON footer. */\nexport const JSON_FOOTER_MARKER = \"--- JSON ---\";\n\n/** File extension for crash log files. */\nexport const CRASH_LOG_EXTENSION = \".crash.log\";\n\n/**\n * Format a CrashReport as human-readable text for local crash log files.\n * @param report - Crash report to format\n * @returns Formatted text content\n */\nexport function formatCrashReport(report: CrashReport): string {\n const lines = [\n `Crash Report: ${report.id}`,\n `Timestamp: ${report.timestamp}`,\n `Error Type: ${report.errorType}`,\n \"\",\n \"--- Environment ---\",\n `SDK Version: ${report.sdkVersion}`,\n `Node Version: ${report.nodeVersion}`,\n `OS: ${report.osPlatform} ${report.osRelease}`,\n `Arch: ${report.arch}`,\n \"\",\n \"--- Command ---\",\n `Command: ${report.command}`,\n `Arguments: ${JSON.stringify(report.argv)}`,\n \"\",\n \"--- Error ---\",\n `Name: ${report.errorName}`,\n `Message: ${report.errorMessage}`,\n \"\",\n \"--- Stack Trace ---\",\n report.stackTrace || \"(no stack trace available)\",\n \"\",\n JSON_FOOTER_MARKER,\n JSON.stringify(report),\n \"\",\n ];\n return lines.join(\"\\n\");\n}\n\n/**\n * Generate a filename for a crash log file.\n * Format: {timestamp}-{shortId}.crash.log\n * @param report - Crash report to generate filename for\n * @returns Filename string\n */\nfunction generateFilename(report: CrashReport): string {\n const safeTimestamp = report.timestamp.replace(/[:.]/g, \"-\");\n const shortId = report.id.slice(0, 8);\n return `${safeTimestamp}-${shortId}${CRASH_LOG_EXTENSION}`;\n}\n\n/**\n * Remove old crash log files, keeping only the most recent ones.\n * @param dir - Crash log directory\n */\nfunction cleanupOldFiles(dir: string): void {\n try {\n const files = fs\n .readdirSync(dir)\n .filter((f) => f.endsWith(CRASH_LOG_EXTENSION))\n .sort()\n .reverse();\n\n for (const file of files.slice(MAX_CRASH_FILES)) {\n fs.unlinkSync(path.join(dir, file));\n }\n } catch {\n // Best-effort cleanup, ignore errors\n }\n}\n\n/**\n * Write a crash report to a local file.\n * Creates the directory if it doesn't exist. Keeps only the last 10 crash files.\n * Never throws - returns the file path on success or undefined on failure.\n * @param report - Crash report to write\n * @param dir - Directory to write the crash log file to\n * @returns File path on success, undefined on failure\n */\nexport function writeCrashReport(report: CrashReport, dir: string): string | undefined {\n try {\n fs.mkdirSync(dir, { recursive: true });\n\n const filename = generateFilename(report);\n const filePath = path.join(dir, filename);\n const content = formatCrashReport(report);\n\n fs.writeFileSync(filePath, content, \"utf-8\");\n cleanupOldFiles(dir);\n\n return filePath;\n } catch {\n return undefined;\n }\n}\n","import type { CrashReport } from \"./report\";\n\nconst SEND_TIMEOUT_MS = 5000;\nconst PRODUCTION_ENDPOINT = \"https://sdk-error-tracking-926vh9t4cl.erp.dev/query\";\n\nconst SUBMIT_MUTATION = `\nmutation SubmitCrashReport(\n $id: String!\n $timestamp: String!\n $sdkVersion: String!\n $nodeVersion: String!\n $osPlatform: String!\n $osRelease: String!\n $arch: String!\n $command: String!\n $argv: [String]\n $errorName: String!\n $errorMessage: String!\n $stackTrace: String\n $errorType: String!\n $userId: String\n $userEmail: String\n) {\n submitCrashReport(\n id: $id\n timestamp: $timestamp\n sdkVersion: $sdkVersion\n nodeVersion: $nodeVersion\n osPlatform: $osPlatform\n osRelease: $osRelease\n arch: $arch\n command: $command\n argv: $argv\n errorName: $errorName\n errorMessage: $errorMessage\n stackTrace: $stackTrace\n errorType: $errorType\n userId: $userId\n userEmail: $userEmail\n ) {\n success\n }\n}`;\n\n/**\n * Send a crash report to the remote endpoint via GraphQL mutation.\n * Best-effort: never throws, returns boolean success.\n * @param report - Crash report to send\n * @param ua - User-Agent header value\n * @returns true if the request succeeded, false otherwise\n */\nexport async function sendCrashReport(report: CrashReport, ua: string): Promise<boolean> {\n try {\n const endpoint = process.env.TAILOR_CRASH_REPORT_ENDPOINT || PRODUCTION_ENDPOINT;\n const response = await fetch(endpoint, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"User-Agent\": ua,\n },\n body: JSON.stringify({\n query: SUBMIT_MUTATION,\n variables: report,\n }),\n signal: AbortSignal.timeout(SEND_TIMEOUT_MS),\n });\n\n if (!response.ok) return false;\n\n const data = (await response.json()) as {\n errors?: unknown[];\n data?: { submitCrashReport: { success: boolean } };\n };\n if (data.errors?.length) return false;\n return data.data?.submitCrashReport.success === true;\n } catch {\n return false;\n }\n}\n","import * as os from \"node:os\";\n\nconst HOME_DIR = os.homedir();\n\n// Patterns for sanitization (global variants for use with .replace())\nconst UUID_PATTERN = /\\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\\b/gi;\nconst LONG_HEX_PATTERN = /\\b[0-9a-fA-F]{32,}\\b/g;\nconst EMAIL_PATTERN = /\\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}\\b/g;\nconst ABSOLUTE_PATH_PATTERN = /(?:\\/(?:[\\w.@\\- ]+\\/)+[\\w.@\\- ]+)/g;\nconst WINDOWS_PATH_PATTERN = /(?:[A-Za-z]:\\\\(?:[\\w.@\\- ]+\\\\)+[\\w.@\\- ]+)/g;\nconst URL_QUERY_PATTERN = /[?&][^?\\s]*/g;\n\n// Non-global variants for single-match .test() calls (avoids lastIndex state issues)\nconst EMAIL_TEST_PATTERN = /\\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}\\b/;\nconst WINDOWS_DRIVE_TEST_PATTERN = /^[A-Za-z]:\\\\/;\n\n// SDK package path marker for relative paths\nconst SDK_PACKAGE_MARKER = \"packages/sdk/\";\n\nfunction lastSegment(filePath: string, separator: string): string {\n return filePath.split(separator).pop() ?? filePath;\n}\n\n/**\n * Sanitize a stack trace by replacing absolute paths with relative SDK paths.\n * External paths are replaced with `<external>/filename.ext`.\n * Home directories are replaced with `~/<redacted>/`.\n * @param stack - Raw stack trace string\n * @returns Sanitized stack trace\n */\nexport function sanitizeStackTrace(stack: string): string {\n // V8 stack traces start with \"ErrorType: message\\n at ...\".\n // The error message may span multiple lines before the first \" at \" frame.\n // Apply message sanitization to all message lines so secrets embedded in\n // multiline error messages are redacted consistently with errorMessage.\n const firstFrameIndex = stack.search(/\\n\\s+at /);\n let result: string;\n if (firstFrameIndex !== -1) {\n result = sanitizeMessage(stack.slice(0, firstFrameIndex)) + stack.slice(firstFrameIndex);\n } else {\n result = sanitizeMessage(stack);\n }\n\n result = result.replace(ABSOLUTE_PATH_PATTERN, (match) => {\n const sdkIndex = match.indexOf(SDK_PACKAGE_MARKER);\n if (sdkIndex !== -1) {\n return match.slice(sdkIndex);\n }\n\n if (match.startsWith(HOME_DIR)) {\n return `~/<redacted>/${lastSegment(match, \"/\")}`;\n }\n\n return `<external>/${lastSegment(match, \"/\")}`;\n });\n result = result.replace(WINDOWS_PATH_PATTERN, (match) => {\n const normalized = match.replace(/\\\\/g, \"/\");\n const sdkIndex = normalized.indexOf(SDK_PACKAGE_MARKER);\n if (sdkIndex !== -1) {\n return normalized.slice(sdkIndex);\n }\n return `<external>/${lastSegment(match, \"\\\\\")}`;\n });\n return result;\n}\n\n/**\n * Sanitize an error message by redacting sensitive information.\n * Redacts: UUIDs, long hex tokens, email addresses, absolute paths, URL query strings.\n * @param message - Raw error message\n * @returns Sanitized error message\n */\nexport function sanitizeMessage(message: string): string {\n let result = message;\n // Strip serialized request/response bodies that may contain secrets\n result = result.replace(/\\nRequest:\\s*[\\s\\S]*$/, \"\\nRequest: <redacted>\");\n result = result.replace(UUID_PATTERN, \"<uuid>\");\n result = result.replace(LONG_HEX_PATTERN, \"<redacted>\");\n result = result.replace(EMAIL_PATTERN, \"<email>\");\n result = result.replace(URL_QUERY_PATTERN, \"?<redacted>\");\n result = result.replace(ABSOLUTE_PATH_PATTERN, (match) => `<path>/${lastSegment(match, \"/\")}`);\n result = result.replace(WINDOWS_PATH_PATTERN, (match) => `<path>/${lastSegment(match, \"\\\\\")}`);\n\n return result;\n}\n\n/**\n * Sanitize process.argv by keeping command/subcommand names and redacting\n * values of sensitive flags.\n * @param argv - Raw process.argv array\n * @returns Sanitized argv array\n */\nexport function sanitizeArgv(argv: string[]): string[] {\n const result: string[] = [];\n let redactNext = false;\n\n for (const arg of argv) {\n if (redactNext) {\n // If the next token is itself a flag, treat it as a new flag rather\n // than consuming it as the previous flag's value. This avoids leaking\n // the *next* flag's value (e.g., `--verbose --workspace-id secret`\n // would otherwise expose `secret`).\n if (!arg.startsWith(\"-\")) {\n result.push(\"<redacted>\");\n redactNext = false;\n continue;\n }\n redactNext = false;\n }\n\n if (arg.startsWith(\"-\")) {\n // --flag=value: keep flag name, redact value\n const eqIndex = arg.indexOf(\"=\");\n if (eqIndex !== -1) {\n result.push(`${arg.slice(0, eqIndex)}=<redacted>`);\n continue;\n }\n\n // --flag / -f: keep flag name, redact next arg as its value\n result.push(arg);\n redactNext = true;\n continue;\n }\n\n // Redact absolute paths\n if (arg.startsWith(\"/\") && arg.includes(\"/\", 1)) {\n result.push(\"<path>\");\n continue;\n }\n\n // Redact Windows-style absolute paths\n if (WINDOWS_DRIVE_TEST_PATTERN.test(arg)) {\n result.push(\"<path>\");\n continue;\n }\n\n // Redact email addresses\n if (EMAIL_TEST_PATTERN.test(arg)) {\n result.push(\"<email>\");\n continue;\n }\n\n result.push(arg);\n }\n\n return result;\n}\n","import * as crypto from \"node:crypto\";\nimport * as fs from \"node:fs\";\nimport * as os from \"node:os\";\nimport { parseYAML } from \"confbox\";\nimport * as path from \"pathe\";\nimport { xdgConfig } from \"xdg-basedir\";\nimport { sanitizeArgv, sanitizeMessage, sanitizeStackTrace } from \"./sanitize\";\n\nexport type ErrorType = \"uncaughtException\" | \"unhandledRejection\" | \"handledError\";\n\nexport interface CrashReport {\n id: string;\n timestamp: string;\n sdkVersion: string;\n nodeVersion: string;\n osPlatform: string;\n osRelease: string;\n arch: string;\n command: string;\n argv: string[];\n errorName: string;\n errorMessage: string;\n stackTrace: string;\n errorType: ErrorType;\n userId: string | null;\n userEmail: string | null;\n}\n\ninterface BuildCrashReportOptions {\n error: unknown;\n sdkVersion: string;\n errorType: ErrorType;\n}\n\n// Maximum subcommand depth to keep (e.g., \"tailordb migrate generate\" = 3 tokens).\n// Positional arguments beyond this are potentially sensitive user input.\n// Accepted trade-off: plain-text positional args that don't match known patterns\n// (UUIDs, hex tokens, emails, paths) pass through to `command` and `argv`.\n// Full redaction would require embedding the CLI command tree here, which is fragile.\nconst MAX_COMMAND_TOKENS = 3;\n\n/**\n * Parse the command name from process.argv.\n * Extracts up to MAX_COMMAND_TOKENS non-flag arguments after the script name.\n * @returns Parsed command string\n */\nfunction parseCommand(): string {\n const args = process.argv.slice(2);\n const commandParts: string[] = [];\n for (const arg of args) {\n if (arg.startsWith(\"-\") || commandParts.length >= MAX_COMMAND_TOKENS) break;\n commandParts.push(arg);\n }\n return commandParts.join(\" \") || \"<unknown>\";\n}\n\n/**\n * Build a CrashReport data structure from an error and context.\n * All sensitive data is sanitized before inclusion.\n * @param options - Error, SDK version, and crash type\n * @returns Sanitized crash report\n */\nexport function buildCrashReport(options: BuildCrashReportOptions): CrashReport {\n const { error, sdkVersion, errorType } = options;\n\n const isError = error instanceof Error;\n const rawMessage = isError ? error.message : String(error);\n const rawStack = isError && error.stack ? error.stack : \"\";\n const errorName = isError ? error.name : \"UnknownError\";\n\n const currentUser = readCurrentUser();\n\n return {\n id: crypto.randomUUID(),\n timestamp: new Date().toISOString(),\n sdkVersion,\n nodeVersion: process.version,\n osPlatform: process.platform,\n osRelease: os.release(),\n arch: process.arch,\n command: sanitizeMessage(parseCommand()),\n argv: sanitizeArgv(process.argv),\n errorName,\n errorMessage: sanitizeMessage(rawMessage),\n stackTrace: sanitizeStackTrace(rawStack),\n errorType,\n userId: currentUser,\n userEmail: currentUser,\n };\n}\n\n/**\n * Read current_user from Tailor Platform config without side effects.\n * Unlike readPlatformConfig(), this never triggers migration or logs warnings.\n * @returns The current user email, or null if unavailable\n */\nfunction readCurrentUser(): string | null {\n try {\n if (!xdgConfig) return null;\n const configPath = path.join(xdgConfig, \"tailor-platform\", \"config.yaml\");\n if (!fs.existsSync(configPath)) return null;\n const raw = parseYAML(fs.readFileSync(configPath, \"utf-8\")) as { current_user?: string | null };\n return raw?.current_user ?? null;\n } catch {\n return null;\n }\n}\n","import { logger } from \"@/cli/shared/logger\";\nimport { readPackageJson } from \"@/cli/shared/package-json\";\nimport { parseCrashReportConfig } from \"./config\";\nimport { buildCrashReport, type ErrorType } from \"./report\";\nimport { sendCrashReport } from \"./sender\";\nimport { writeCrashReport } from \"./writer\";\n\n/**\n * Report an unexpected crash. Writes a local crash log file and optionally\n * sends the report to a remote endpoint. Displays a user-facing message\n * with the crash log path and a command to submit the report.\n *\n * Never throws - all errors are silently caught.\n * @param error - The error that caused the crash\n * @param errorType - How the error was caught\n */\nexport async function reportCrash(error: unknown, errorType: ErrorType): Promise<void> {\n try {\n const config = parseCrashReportConfig();\n if (!config.localEnabled && !config.remoteEnabled) return;\n\n const packageJson = await readPackageJson();\n const sdkVersion = packageJson.version ?? \"unknown\";\n\n const report = buildCrashReport({ error, sdkVersion, errorType });\n\n if (config.localEnabled) {\n const filePath = writeCrashReport(report, config.localDir);\n if (filePath) {\n logger.log(\n [\n \"\",\n \"An unexpected error occurred. A crash report has been saved to:\",\n ` ${filePath}`,\n \"\",\n \"To submit this report:\",\n ` tailor-sdk crash-report send --file \"${filePath}\"`,\n ].join(\"\\n\"),\n );\n }\n }\n\n if (config.remoteEnabled) {\n // Lazy import: client.ts pulls in heavy dependencies (OAuth2, Connect, Protobuf)\n // that should not be loaded on the startup critical path via initCrashReporting().\n const { userAgent } = await import(\"@/cli/shared/client\");\n const ua = await userAgent();\n await sendCrashReport(report, ua);\n }\n } catch {\n // Never throw from crash reporting\n }\n}\n\n/**\n * Register global uncaughtException and unhandledRejection handlers.\n * These catch errors outside the normal cleanup flow (e.g., during\n * argument parsing). Should be called once at CLI startup before runMain.\n */\nexport function initCrashReporting(): void {\n const config = parseCrashReportConfig();\n if (!config.localEnabled && !config.remoteEnabled) return;\n\n const handleFatal = (error: unknown, errorType: ErrorType) => {\n const message = error instanceof Error ? error.message : String(error);\n logger.error(message);\n void reportCrash(error, errorType).finally(() => {\n process.exit(1);\n });\n };\n\n process.on(\"uncaughtException\", (error) => handleFatal(error, \"uncaughtException\"));\n process.on(\"unhandledRejection\", (reason) => handleFatal(reason, \"unhandledRejection\"));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAiBA,SAAgB,yBAA4C;AAC1D,KAAI,KACF,QAAO;EACL,cAAc;EACd,eAAe;EACf,UAAU;EACX;CAGH,MAAM,gBAAgB,QAAQ,IAAI,8BAA8B,MAAM,aAAa,KAAK;CACxF,MAAM,iBAAiB,QAAQ,IAAI,+BAA+B,OAAO,aAAa,KAAK;CAC3F,MAAM,WAAW,YAAY,KAAK,KAAK,WAAW,mBAAmB,gBAAgB,GAAG;AAExF,QAAO;EACL,cAAc,gBAAgB,aAAa;EAC3C;EACA;EACD;;;;;AC9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,gBAAgB;SACtB;AACN,SAAO;;;;;;;;;;;;;;;ACxFX,eAAsB,YAAY,OAAgB,WAAqC;AACrF,KAAI;EACF,MAAM,SAAS,wBAAwB;AACvC,MAAI,CAAC,OAAO,gBAAgB,CAAC,OAAO,cAAe;EAKnD,MAAM,SAAS,iBAAiB;GAAE;GAAO,aAHrB,MAAM,iBAAiB,EACZ,WAAW;GAEW;GAAW,CAAC;AAEjE,MAAI,OAAO,cAAc;GACvB,MAAM,WAAW,iBAAiB,QAAQ,OAAO,SAAS;AAC1D,OAAI,SACF,QAAO,IACL;IACE;IACA;IACA,KAAK;IACL;IACA;IACA,0CAA0C,SAAS;IACpD,CAAC,KAAK,KAAK,CACb;;AAIL,MAAI,OAAO,eAAe;GAGxB,MAAM,EAAE,cAAc,MAAM,OAAO;AAEnC,SAAM,gBAAgB,QADX,MAAM,WAAW,CACK;;SAE7B;;;;;;;AAUV,SAAgB,qBAA2B;CACzC,MAAM,SAAS,wBAAwB;AACvC,KAAI,CAAC,OAAO,gBAAgB,CAAC,OAAO,cAAe;CAEnD,MAAM,eAAe,OAAgB,cAAyB;EAC5D,MAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;AACtE,SAAO,MAAM,QAAQ;AACrB,EAAK,YAAY,OAAO,UAAU,CAAC,cAAc;AAC/C,WAAQ,KAAK,EAAE;IACf;;AAGJ,SAAQ,GAAG,sBAAsB,UAAU,YAAY,OAAO,oBAAoB,CAAC;AACnF,SAAQ,GAAG,uBAAuB,WAAW,YAAY,QAAQ,qBAAqB,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"enum-constants-
|
|
1
|
+
{"version":3,"file":"enum-constants-D1nfn0qD.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 \"@/types/tailordb\";\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 } from \"@/types/plugin\";\nimport type { GeneratorResult, TailorDBReadyContext } from \"@/types/plugin-generation\";\n\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 });\n }\n\n return { files };\n },\n };\n}\n"],"mappings":";;;;;;AAOA,SAAgB,6BAA6B,UAAoC;AAC/E,KAAI,SAAS,WAAW,EACtB,QAAO;CAGT,MAAM,0BAAU,IAAI,KAA6B;AACjD,MAAK,MAAM,WAAW,SACpB,SAAQ,IAAI,QAAQ,MAAM,QAAQ;CAGpC,MAAM,WAAW,MAAM,KAAK,QAAQ,QAAQ,CAAC,CAC1C,KAAK,MAAM;EACV,MAAM,UAAU,EAAE,OACf,KAAK,MAAM;AAEV,UAAO,MADK,EAAE,MAAM,QAAQ,UAAU,IAAI,CACzB,MAAM,EAAE,MAAM;IAC/B,CACD,KAAK,MAAM;EAEd,MAAM,kBAAkB,EAAE,OAAO,MAAM,MAAM,EAAE,YAAY;EAC3D,IAAI,QAAQ;AACZ,MAAI,EAAE,oBAAoB,iBAAiB;GACzC,MAAM,QAAkB,EAAE;AAE1B,OAAI,EAAE,kBAAkB;AACtB,UAAM,KAAK,MAAM,EAAE,mBAAmB;AACtC,QAAI,gBACF,OAAM,KAAK,KAAK;;AAIpB,OAAI,iBAAiB;IACnB,MAAM,eAAe,EAAE,OAAO,KAAK,MAAM;AAEvC,YAAO,gBAAgB,CADX,EAAE,MAAM,QAAQ,UAAU,IAAI,EACb,EAAE,YAAY,CAAC,OAAO,QAAQ,CAAC,KAAK,MAAM;MACvE;AACF,UAAM,KAAK,GAAG,aAAa;;AAG7B,OAAI,MAAM,SAAS,EACjB,SAAQ,QAAQ,MAAM,KAAK,KAAK,CAAC;;AAMrC,SAAO,GAFU,GAAG,MAAM,eAAe,EAAE,KAAK,QAAQ,QAAQ,eAE7C,IADH,eAAe,EAAE,KAAK,aAAa,EAAE,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,MAAM,EAAE;IAC1C,MAAM,WAAW,MAAM,gBAAgB,KAAK;AAC5C,aAAS,KAAK,GAAG,SAAS,MAAM;;GAIpC,MAAM,QAAkC,EAAE;AAC1C,OAAI,SAAS,SAAS,GAAG;IACvB,MAAM,UAAU,6BAA6B,SAAS;AACtD,UAAM,KAAK;KACT,MAAM,IAAI,aAAa;KACvB;KACD,CAAC;;AAGJ,UAAO,EAAE,OAAO;;EAEnB"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ct as InferredAttributeList, lt as InferredAttributeMap } from "./plugin-
|
|
1
|
+
import { ct as InferredAttributeList, lt as InferredAttributeMap } from "./plugin-D3a0-qe0.mjs";
|
|
2
2
|
|
|
3
3
|
//#region src/configure/types/actor.d.ts
|
|
4
4
|
/** User type enum values from the Tailor Platform server. */
|
|
@@ -26,4 +26,4 @@ interface Env {}
|
|
|
26
26
|
type TailorEnv = keyof Env extends never ? Record<string, string> : Env;
|
|
27
27
|
//#endregion
|
|
28
28
|
export { TailorEnv as n, TailorActor as r, Env as t };
|
|
29
|
-
//# sourceMappingURL=env-
|
|
29
|
+
//# sourceMappingURL=env-BuMbIknz.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"file-utils-
|
|
1
|
+
{"version":3,"file":"file-utils-Bctuzn3x.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 \"multiline-ts\";\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 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 tailordb.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 tailordb.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 tailordb.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 tailordb.file.getMetadata(namespaces[type], type, field, recordId);\n }\n ` + \"\\n\";\n\n // Generate openFileDownloadStream helper function\n const openDownloadStreamFunction =\n multiline /* ts */ `\n export async function openFileDownloadStream<T extends keyof TypeWithFiles>(\n type: T,\n field: TypeWithFiles[T][\"fields\"],\n recordId: string,\n ): Promise<FileStreamIterator> {\n return await tailordb.file.openDownloadStream(namespaces[type], type, field, recordId);\n }\n ` + \"\\n\";\n\n return [\n interfaceDefinition,\n namespacesDefinition,\n downloadFunction,\n uploadFunction,\n deleteFunction,\n getMetadataFunction,\n openDownloadStreamFunction,\n ].join(\"\\n\");\n}\n","import type { FileUtilMetadata } from \"./types\";\nimport type { TailorDBType } from \"@/types/tailordb\";\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 } from \"@/types/plugin\";\nimport type { GeneratorResult, TailorDBReadyContext } from \"@/types/plugin-generation\";\n\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;AACR,KAAI,cAAc,WAAW,EAC3B,QAAO;CAIT,MAAM,mCAAmB,IAAI,KAAqB;CAClD,MAAM,gCAAgB,IAAI,KAAuB;AAEjD,MAAK,MAAM,EAAE,WAAW,WAAW,cACjC,MAAK,MAAM,QAAQ,OAAO;AACxB,mBAAiB,IAAI,KAAK,MAAM,UAAU;AAC1C,gBAAc,IAAI,KAAK,MAAM,KAAK,WAAW;;AAIjD,KAAI,iBAAiB,SAAS,EAC5B,QAAO;AA4FT,QAAO;EAhFL,EAAmB;;QARG,MAAM,KAAK,cAAc,SAAS,CAAC,CACxD,KAAK,CAAC,UAAU,YAAY;AAE3B,UAAO,KAAK,SAAS,mBADG,OAAO,KAAK,UAAU,IAAI,MAAM,GAAG,CAAC,KAAK,MAAM,CACf;IACxD,CACD,KAAK,KAAK,CAKS;;QAEhB;EAQJ,EAAmB;;QALI,MAAM,KAAK,iBAAiB,SAAS,CAAC,CAC5D,KAAK,CAAC,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
|
//#region src/plugin/builtin/file-utils/index.d.ts
|
|
4
4
|
declare const FileUtilsGeneratorID = "@tailor-platform/file-utils";
|
|
@@ -14,4 +14,4 @@ type FileUtilsPluginOptions = {
|
|
|
14
14
|
declare function fileUtilsPlugin(options: FileUtilsPluginOptions): Plugin<unknown, FileUtilsPluginOptions>;
|
|
15
15
|
//#endregion
|
|
16
16
|
export { fileUtilsPlugin as n, FileUtilsGeneratorID as t };
|
|
17
|
-
//# sourceMappingURL=index-
|
|
17
|
+
//# sourceMappingURL=index-B0Lrzywd.d.mts.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as Plugin } from "./plugin-
|
|
1
|
+
import { n as Plugin } from "./plugin-D3a0-qe0.mjs";
|
|
2
2
|
|
|
3
3
|
//#region src/plugin/builtin/enum-constants/index.d.ts
|
|
4
4
|
declare const EnumConstantsGeneratorID = "@tailor-platform/enum-constants";
|
|
@@ -14,4 +14,4 @@ type EnumConstantsPluginOptions = {
|
|
|
14
14
|
declare function enumConstantsPlugin(options: EnumConstantsPluginOptions): Plugin<unknown, EnumConstantsPluginOptions>;
|
|
15
15
|
//#endregion
|
|
16
16
|
export { enumConstantsPlugin as n, EnumConstantsGeneratorID as t };
|
|
17
|
-
//# sourceMappingURL=index-
|
|
17
|
+
//# sourceMappingURL=index-CbnLNm14.d.mts.map
|