@burdenoff/be-sdk 2026.527.3 → 2026.528.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.
@@ -0,0 +1,449 @@
1
+ import { logger } from './chunk-CBZNP6RF.js';
2
+ import { __name } from './chunk-XE4OXN2W.js';
3
+ import { GraphQLError } from 'graphql';
4
+
5
+ var DEFAULT_ERROR_CODE = "INTERNAL_SERVER_ERROR";
6
+ var DEFAULT_HTTP_STATUS = 500;
7
+ var DEFAULT_USER_MESSAGES = {
8
+ BAD_REQUEST: "Please check the request and try again.",
9
+ BAD_USER_INPUT: "Please check the information and try again.",
10
+ CAPTCHA_FAILED: "The verification failed. Please try again.",
11
+ CAPTCHA_REQUIRED: "Please complete the verification to continue.",
12
+ COMPLEXITY_TOO_HIGH: "This request is too large to process. Please simplify it and try again.",
13
+ CONFLICT: "This change conflicts with existing data. Please refresh and try again.",
14
+ FORBIDDEN: "You do not have permission to do that.",
15
+ INTERNAL_SERVER_ERROR: "Something went wrong. Please try again.",
16
+ INVALID_PASSWORD: "The password you entered is incorrect.",
17
+ NOT_FOUND: "We could not find the requested item.",
18
+ PERMISSION_DENIED: "You do not have permission to do that.",
19
+ QUOTA_EXCEEDED: "You've reached your usage limit.",
20
+ QUOTA_EXHAUSTED: "You've reached your usage limit.",
21
+ RATE_LIMITED: "Too many requests. Please wait a moment and try again.",
22
+ RESOURCE_CAP_EXCEEDED: "You've reached your plan limit. Upgrade your plan to continue.",
23
+ STORAGE_QUOTA_EXCEEDED: "You've reached your storage limit. Upgrade your plan to continue.",
24
+ TIMEOUT: "The request took too long. Please try again.",
25
+ UNAUTHENTICATED: "Please sign in to continue.",
26
+ VALIDATION_ERROR: "Please check the information and try again.",
27
+ WORKSPACE_REQUIRED: "Please choose a workspace and try again."
28
+ };
29
+ var DEFAULT_STATUS_BY_CODE = {
30
+ BAD_REQUEST: 400,
31
+ BAD_USER_INPUT: 400,
32
+ CAPTCHA_FAILED: 400,
33
+ CAPTCHA_REQUIRED: 400,
34
+ COMPLEXITY_TOO_HIGH: 400,
35
+ CONFLICT: 409,
36
+ FORBIDDEN: 403,
37
+ INVALID_PASSWORD: 400,
38
+ NOT_FOUND: 404,
39
+ PERMISSION_DENIED: 403,
40
+ QUOTA_EXCEEDED: 429,
41
+ QUOTA_EXHAUSTED: 429,
42
+ RATE_LIMITED: 429,
43
+ RESOURCE_CAP_EXCEEDED: 429,
44
+ STORAGE_QUOTA_EXCEEDED: 429,
45
+ TIMEOUT: 504,
46
+ UNAUTHENTICATED: 401,
47
+ VALIDATION_ERROR: 400,
48
+ WORKSPACE_REQUIRED: 403
49
+ };
50
+ var SENSITIVE_EXTENSION_KEYS = /* @__PURE__ */ new Set([
51
+ "exception",
52
+ "originalError",
53
+ "stack",
54
+ "stacktrace"
55
+ ]);
56
+ var TECHNICAL_MESSAGE_PATTERNS = [
57
+ /\bprisma\b/i,
58
+ /\bsql\b/i,
59
+ /\bconstraint\b/i,
60
+ /\bstack\b/i,
61
+ /\bundefined\b/i,
62
+ /\bnull\b/i,
63
+ /\bECONN[A-Z_]*\b/,
64
+ /\bETIMEDOUT\b/,
65
+ /\bENOTFOUND\b/,
66
+ /\bP\d{4}\b/,
67
+ /Cannot (read|set|find|access)/i,
68
+ /Build failed \(exit \d+\)/i,
69
+ /JSON\.stringify/i
70
+ ];
71
+ function isRecord(value) {
72
+ return typeof value === "object" && value !== null && !Array.isArray(value);
73
+ }
74
+ __name(isRecord, "isRecord");
75
+ function readString(record, key) {
76
+ const value = record[key];
77
+ return typeof value === "string" && value.trim().length > 0 ? value : null;
78
+ }
79
+ __name(readString, "readString");
80
+ function readExtensions(error) {
81
+ if (!isRecord(error)) return {};
82
+ const extensions = error["extensions"];
83
+ return isRecord(extensions) ? extensions : {};
84
+ }
85
+ __name(readExtensions, "readExtensions");
86
+ function readOriginalError(error) {
87
+ if (error instanceof GraphQLError && error.originalError instanceof Error) {
88
+ return error.originalError;
89
+ }
90
+ return void 0;
91
+ }
92
+ __name(readOriginalError, "readOriginalError");
93
+ function sanitizeExtensions(extensions) {
94
+ const sanitized = {};
95
+ for (const [key, value] of Object.entries(extensions)) {
96
+ if (!SENSITIVE_EXTENSION_KEYS.has(key)) {
97
+ sanitized[key] = value;
98
+ }
99
+ }
100
+ return sanitized;
101
+ }
102
+ __name(sanitizeExtensions, "sanitizeExtensions");
103
+ function normalizeCode(code) {
104
+ if (!code) return DEFAULT_ERROR_CODE;
105
+ return code.trim().replace(/[\s-]+/g, "_").toUpperCase();
106
+ }
107
+ __name(normalizeCode, "normalizeCode");
108
+ function inferCodeFromMessage(message) {
109
+ const lower = message.toLowerCase();
110
+ if (lower.includes("unauthenticated") || lower.includes("not authenticated") || lower.includes("authentication required") || lower.includes("unauthorized") || lower.includes("please sign in") || lower.includes("sign in to")) {
111
+ return "UNAUTHENTICATED";
112
+ }
113
+ if (lower.includes("workspace context") || lower.includes("switch to a workspace")) {
114
+ return "WORKSPACE_REQUIRED";
115
+ }
116
+ if (lower.includes("forbidden") || lower.includes("access denied") || lower.includes("permission denied") || lower.includes("not authorized")) {
117
+ return "FORBIDDEN";
118
+ }
119
+ if (lower.includes("not found") || lower.includes("disappeared")) {
120
+ return "NOT_FOUND";
121
+ }
122
+ if (lower.includes("already exists") || lower.includes("already taken") || lower.includes("conflict")) {
123
+ return "CONFLICT";
124
+ }
125
+ if (lower.includes("quota") || lower.includes("cap exceeded") || lower.includes("limit reached")) {
126
+ return "QUOTA_EXCEEDED";
127
+ }
128
+ if (lower.includes("timeout") || lower.includes("timed out")) {
129
+ return "TIMEOUT";
130
+ }
131
+ if (lower.includes("required") || lower.includes("invalid") || lower.includes("missing") || lower.includes("unsupported")) {
132
+ return "BAD_USER_INPUT";
133
+ }
134
+ return DEFAULT_ERROR_CODE;
135
+ }
136
+ __name(inferCodeFromMessage, "inferCodeFromMessage");
137
+ function inferCode(error, extensions, originalError) {
138
+ const extensionCode = typeof extensions["code"] === "string" ? extensions["code"] : null;
139
+ if (extensionCode) return normalizeCode(extensionCode);
140
+ if (isRecord(originalError)) {
141
+ const originalCode = readString(originalError, "code");
142
+ if (originalCode) return normalizeCode(originalCode);
143
+ }
144
+ if (isRecord(error)) {
145
+ const directCode = readString(error, "code");
146
+ if (directCode) return normalizeCode(directCode);
147
+ }
148
+ const message = readErrorMessage(error);
149
+ return inferCodeFromMessage(message);
150
+ }
151
+ __name(inferCode, "inferCode");
152
+ function readErrorMessage(error) {
153
+ if (error instanceof Error && error.message.trim().length > 0) {
154
+ return error.message;
155
+ }
156
+ if (isRecord(error)) {
157
+ const message = readString(error, "message");
158
+ if (message) return message;
159
+ }
160
+ return DEFAULT_USER_MESSAGES[DEFAULT_ERROR_CODE];
161
+ }
162
+ __name(readErrorMessage, "readErrorMessage");
163
+ function isLikelyTechnicalMessage(message) {
164
+ if (message.length > 220) return true;
165
+ if (message.includes("\n")) return true;
166
+ if (message.includes("{") && message.includes("}")) return true;
167
+ return TECHNICAL_MESSAGE_PATTERNS.some((pattern) => pattern.test(message));
168
+ }
169
+ __name(isLikelyTechnicalMessage, "isLikelyTechnicalMessage");
170
+ function readExplicitUserMessage(extensions) {
171
+ return readString(extensions, "userMessage") ?? readString(extensions, "humanMessage") ?? readString(extensions, "displayMessage");
172
+ }
173
+ __name(readExplicitUserMessage, "readExplicitUserMessage");
174
+ function resolveUserMessage(code, message, extensions) {
175
+ const explicit = readExplicitUserMessage(extensions);
176
+ if (explicit) return explicit;
177
+ const fallback = DEFAULT_USER_MESSAGES[code] ?? DEFAULT_USER_MESSAGES[DEFAULT_ERROR_CODE] ?? "Something went wrong. Please try again.";
178
+ if (code === DEFAULT_ERROR_CODE) {
179
+ return fallback;
180
+ }
181
+ if (!isLikelyTechnicalMessage(message)) {
182
+ return message;
183
+ }
184
+ return fallback;
185
+ }
186
+ __name(resolveUserMessage, "resolveUserMessage");
187
+ function resolveTechnicalMessage(code, message, extensions, options) {
188
+ const explicit = readString(extensions, "technicalMessage");
189
+ if (explicit) return explicit;
190
+ if (options.environment === "production" && code === DEFAULT_ERROR_CODE) {
191
+ return options.serviceName ? `${options.serviceName} returned ${DEFAULT_ERROR_CODE}` : DEFAULT_ERROR_CODE;
192
+ }
193
+ return message;
194
+ }
195
+ __name(resolveTechnicalMessage, "resolveTechnicalMessage");
196
+ function readHttpStatus(extensions, code) {
197
+ const http = extensions["http"];
198
+ if (isRecord(http) && typeof http["status"] === "number") {
199
+ return http["status"];
200
+ }
201
+ return DEFAULT_STATUS_BY_CODE[code] ?? DEFAULT_HTTP_STATUS;
202
+ }
203
+ __name(readHttpStatus, "readHttpStatus");
204
+ function normalizeError(error, options = {}) {
205
+ const originalError = readOriginalError(error);
206
+ const originalExtensions = readExtensions(originalError);
207
+ const directExtensions = readExtensions(error);
208
+ const mergedExtensions = sanitizeExtensions({
209
+ ...originalExtensions,
210
+ ...directExtensions
211
+ });
212
+ const message = readErrorMessage(error);
213
+ const code = inferCode(error, mergedExtensions, originalError);
214
+ const userMessage = resolveUserMessage(code, message, mergedExtensions);
215
+ const technicalMessage = resolveTechnicalMessage(code, message, mergedExtensions, options);
216
+ const status = readHttpStatus(mergedExtensions, code);
217
+ const extensions = {
218
+ ...mergedExtensions,
219
+ code,
220
+ userMessage,
221
+ technicalMessage
222
+ };
223
+ if (options.serviceName) {
224
+ extensions["serviceName"] = options.serviceName;
225
+ }
226
+ if (!isRecord(extensions["http"])) {
227
+ extensions["http"] = {
228
+ status
229
+ };
230
+ }
231
+ return {
232
+ code,
233
+ userMessage,
234
+ technicalMessage,
235
+ extensions,
236
+ status
237
+ };
238
+ }
239
+ __name(normalizeError, "normalizeError");
240
+ var UserFacingGraphQLError = class extends GraphQLError {
241
+ static {
242
+ __name(this, "UserFacingGraphQLError");
243
+ }
244
+ constructor(options) {
245
+ const extensions = {
246
+ code: normalizeCode(options.code),
247
+ userMessage: options.userMessage,
248
+ technicalMessage: options.technicalMessage ?? options.userMessage
249
+ };
250
+ if (options.details) {
251
+ extensions["details"] = options.details;
252
+ }
253
+ if (options.httpStatus) {
254
+ extensions["http"] = {
255
+ status: options.httpStatus
256
+ };
257
+ }
258
+ super(options.userMessage, {
259
+ originalError: options.cause,
260
+ extensions
261
+ });
262
+ this.name = "UserFacingGraphQLError";
263
+ }
264
+ };
265
+ function toUserFacingGraphQLError(error, options = {}) {
266
+ const normalized = normalizeError(error, options);
267
+ if (error instanceof GraphQLError) {
268
+ return new GraphQLError(normalized.userMessage, {
269
+ nodes: error.nodes,
270
+ source: error.source,
271
+ positions: error.positions,
272
+ path: error.path,
273
+ originalError: error.originalError,
274
+ extensions: normalized.extensions
275
+ });
276
+ }
277
+ return new GraphQLError(normalized.userMessage, {
278
+ originalError: error instanceof Error ? error : void 0,
279
+ extensions: normalized.extensions
280
+ });
281
+ }
282
+ __name(toUserFacingGraphQLError, "toUserFacingGraphQLError");
283
+ function normalizeExecutionResultErrors(result, options = {}) {
284
+ if (!isRecord(result)) return;
285
+ const errors = result["errors"];
286
+ if (!Array.isArray(errors) || errors.length === 0) return;
287
+ result["errors"] = errors.map((error) => toUserFacingGraphQLError(error, options));
288
+ }
289
+ __name(normalizeExecutionResultErrors, "normalizeExecutionResultErrors");
290
+ function createHumanReadableErrorPlugin(options = {}) {
291
+ return {
292
+ onExecute() {
293
+ return {
294
+ onExecuteDone({ result }) {
295
+ normalizeExecutionResultErrors(result, options);
296
+ }
297
+ };
298
+ }
299
+ };
300
+ }
301
+ __name(createHumanReadableErrorPlugin, "createHumanReadableErrorPlugin");
302
+ function formatHttpError(error, options = {}) {
303
+ const normalized = normalizeError(error, options);
304
+ return {
305
+ status: normalized.status,
306
+ body: {
307
+ error: normalized.userMessage,
308
+ message: normalized.userMessage,
309
+ userMessage: normalized.userMessage,
310
+ technicalMessage: normalized.technicalMessage,
311
+ code: normalized.code,
312
+ extensions: normalized.extensions
313
+ }
314
+ };
315
+ }
316
+ __name(formatHttpError, "formatHttpError");
317
+ function createHttpErrorResponse(error, options = {}) {
318
+ const formatted = formatHttpError(error, options);
319
+ return new Response(JSON.stringify(formatted.body), {
320
+ status: formatted.status,
321
+ headers: {
322
+ "Content-Type": "application/json"
323
+ }
324
+ });
325
+ }
326
+ __name(createHttpErrorResponse, "createHttpErrorResponse");
327
+
328
+ // src/server/workspace-guard.ts
329
+ var WorkspaceRequiredError = class WorkspaceRequiredError2 extends UserFacingGraphQLError {
330
+ static {
331
+ __name(this, "WorkspaceRequiredError");
332
+ }
333
+ constructor(message) {
334
+ super({
335
+ code: "WORKSPACE_REQUIRED",
336
+ userMessage: "Please choose a workspace and try again.",
337
+ technicalMessage: message,
338
+ httpStatus: 403
339
+ });
340
+ this.name = "WorkspaceRequiredError";
341
+ }
342
+ };
343
+ function isFieldPublic(field) {
344
+ const directives = field?.astNode?.directives;
345
+ if (!directives || directives.length === 0) return false;
346
+ for (const dir of directives) {
347
+ const name = dir.name?.value;
348
+ if (name === "public") return true;
349
+ if (name === "rbac") {
350
+ const args = dir.arguments ?? [];
351
+ for (const arg of args) {
352
+ if (arg.name?.value === "public" && arg.value?.kind === "BooleanValue" && arg.value.value === true) {
353
+ return true;
354
+ }
355
+ }
356
+ }
357
+ }
358
+ return false;
359
+ }
360
+ __name(isFieldPublic, "isFieldPublic");
361
+ function resolveOperationType(document, operationName) {
362
+ const defs = document?.definitions ?? [];
363
+ for (const def of defs) {
364
+ if (def.kind !== "OperationDefinition") ;
365
+ if (def.operation && (!operationName || def.name?.value === operationName)) {
366
+ return def.operation;
367
+ }
368
+ }
369
+ return "query";
370
+ }
371
+ __name(resolveOperationType, "resolveOperationType");
372
+ function allRootFieldsPublic(schema, document, operationName) {
373
+ if (!schema || !document) return false;
374
+ const opType = resolveOperationType(document, operationName);
375
+ let rootType;
376
+ if (opType === "mutation") {
377
+ rootType = schema.getMutationType?.();
378
+ } else if (opType === "subscription") {
379
+ rootType = schema.getSubscriptionType?.();
380
+ } else {
381
+ rootType = schema.getQueryType?.();
382
+ }
383
+ if (!rootType) return false;
384
+ const fields = rootType.getFields();
385
+ const defs = document.definitions ?? [];
386
+ const opDef = defs.find((d) => d.operation && (!operationName || d.name?.value === operationName));
387
+ const selections = opDef?.selectionSet?.selections ?? [];
388
+ if (selections.length === 0) return false;
389
+ for (const sel of selections) {
390
+ if (sel.kind && sel.kind !== "Field") return false;
391
+ const fieldName = sel.name?.value;
392
+ if (!fieldName) return false;
393
+ if (fieldName.startsWith("__")) continue;
394
+ const fieldDef = fields[fieldName];
395
+ if (!isFieldPublic(fieldDef)) return false;
396
+ }
397
+ return true;
398
+ }
399
+ __name(allRootFieldsPublic, "allRootFieldsPublic");
400
+ function createWorkspaceGuardPlugin(config) {
401
+ const enabled = config?.enabled ?? true;
402
+ const whitelistedOperations = new Set(config?.whitelistedOperations ?? []);
403
+ const allowPublicDirective = config?.allowPublicDirective ?? true;
404
+ const errorMessage = config?.errorMessage ?? "Workspace context required. Ensure the request includes a valid workspace context (x-workspace-id header).";
405
+ if (!enabled) {
406
+ logger.info("[WorkspaceGuard] Workspace guard disabled");
407
+ return {};
408
+ }
409
+ logger.info("[WorkspaceGuard] Workspace guard enabled", {
410
+ whitelistedOperations: [
411
+ ...whitelistedOperations
412
+ ],
413
+ allowPublicDirective
414
+ });
415
+ return {
416
+ onExecute({ args }) {
417
+ let operationName = args.operationName;
418
+ if (!operationName && args.document?.definitions) {
419
+ for (const def of args.document.definitions) {
420
+ if (def.operation && def.name?.value) {
421
+ operationName = def.name.value;
422
+ break;
423
+ }
424
+ }
425
+ }
426
+ if (operationName && whitelistedOperations.has(operationName)) {
427
+ return void 0;
428
+ }
429
+ if (allowPublicDirective && allRootFieldsPublic(args.schema, args.document, operationName)) {
430
+ return void 0;
431
+ }
432
+ const context = args.contextValue;
433
+ const workspaceId = context?.workspace?.id;
434
+ const headerWorkspaceId = context?.request?.headers?.get?.("x-workspace-id");
435
+ if (!workspaceId && !headerWorkspaceId) {
436
+ logger.warn("[WorkspaceGuard] Blocked operation without workspace context", {
437
+ operationName: operationName ?? "<anonymous>"
438
+ });
439
+ throw new WorkspaceRequiredError(errorMessage);
440
+ }
441
+ return void 0;
442
+ }
443
+ };
444
+ }
445
+ __name(createWorkspaceGuardPlugin, "createWorkspaceGuardPlugin");
446
+
447
+ export { UserFacingGraphQLError, createHttpErrorResponse, createHumanReadableErrorPlugin, createWorkspaceGuardPlugin, formatHttpError, normalizeError, normalizeExecutionResultErrors, toUserFacingGraphQLError };
448
+ //# sourceMappingURL=chunk-XUU5IBVU.js.map
449
+ //# sourceMappingURL=chunk-XUU5IBVU.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/server/errors.ts","../src/server/workspace-guard.ts"],"names":["DEFAULT_ERROR_CODE","DEFAULT_HTTP_STATUS","DEFAULT_USER_MESSAGES","BAD_REQUEST","BAD_USER_INPUT","CAPTCHA_FAILED","CAPTCHA_REQUIRED","COMPLEXITY_TOO_HIGH","CONFLICT","FORBIDDEN","INTERNAL_SERVER_ERROR","INVALID_PASSWORD","NOT_FOUND","PERMISSION_DENIED","QUOTA_EXCEEDED","QUOTA_EXHAUSTED","RATE_LIMITED","RESOURCE_CAP_EXCEEDED","STORAGE_QUOTA_EXCEEDED","TIMEOUT","UNAUTHENTICATED","VALIDATION_ERROR","WORKSPACE_REQUIRED","DEFAULT_STATUS_BY_CODE","SENSITIVE_EXTENSION_KEYS","Set","TECHNICAL_MESSAGE_PATTERNS","isRecord","value","Array","isArray","readString","record","key","trim","length","readExtensions","error","extensions","readOriginalError","GraphQLError","originalError","Error","undefined","sanitizeExtensions","sanitized","Object","entries","has","normalizeCode","code","replace","toUpperCase","inferCodeFromMessage","message","lower","toLowerCase","includes","inferCode","extensionCode","originalCode","directCode","readErrorMessage","isLikelyTechnicalMessage","some","pattern","test","readExplicitUserMessage","resolveUserMessage","explicit","fallback","resolveTechnicalMessage","options","environment","serviceName","readHttpStatus","http","normalizeError","originalExtensions","directExtensions","mergedExtensions","userMessage","technicalMessage","status","UserFacingGraphQLError","details","httpStatus","cause","name","toUserFacingGraphQLError","normalized","nodes","source","positions","path","normalizeExecutionResultErrors","result","errors","map","createHumanReadableErrorPlugin","onExecute","onExecuteDone","formatHttpError","body","createHttpErrorResponse","formatted","Response","JSON","stringify","headers","WorkspaceRequiredError","isFieldPublic","field","directives","astNode","dir","args","arguments","arg","kind","resolveOperationType","document","operationName","defs","definitions","def","operation","allRootFieldsPublic","schema","opType","rootType","getMutationType","getSubscriptionType","getQueryType","fields","getFields","opDef","find","d","selections","selectionSet","sel","fieldName","startsWith","fieldDef","createWorkspaceGuardPlugin","config","enabled","whitelistedOperations","allowPublicDirective","errorMessage","logger","info","context","contextValue","workspaceId","workspace","id","headerWorkspaceId","request","get","warn"],"mappings":";;;;AAwCA,IAAMA,kBAAAA,GAAqB,uBAAA;AAC3B,IAAMC,mBAAAA,GAAsB,GAAA;AAE5B,IAAMC,qBAAAA,GAAgD;EACpDC,WAAAA,EAAa,yCAAA;EACbC,cAAAA,EAAgB,6CAAA;EAChBC,cAAAA,EAAgB,4CAAA;EAChBC,gBAAAA,EAAkB,+CAAA;EAClBC,mBAAAA,EAAqB,yEAAA;EACrBC,QAAAA,EAAU,yEAAA;EACVC,SAAAA,EAAW,wCAAA;EACXC,qBAAAA,EAAuB,yCAAA;EACvBC,gBAAAA,EAAkB,wCAAA;EAClBC,SAAAA,EAAW,uCAAA;EACXC,iBAAAA,EAAmB,wCAAA;EACnBC,cAAAA,EAAgB,kCAAA;EAChBC,eAAAA,EAAiB,kCAAA;EACjBC,YAAAA,EAAc,wDAAA;EACdC,qBAAAA,EAAuB,gEAAA;EACvBC,sBAAAA,EAAwB,mEAAA;EACxBC,OAAAA,EAAS,8CAAA;EACTC,eAAAA,EAAiB,6BAAA;EACjBC,gBAAAA,EAAkB,6CAAA;EAClBC,kBAAAA,EAAoB;AACtB,CAAA;AAEA,IAAMC,sBAAAA,GAAiD;EACrDpB,WAAAA,EAAa,GAAA;EACbC,cAAAA,EAAgB,GAAA;EAChBC,cAAAA,EAAgB,GAAA;EAChBC,gBAAAA,EAAkB,GAAA;EAClBC,mBAAAA,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AAMC,iBAAAA,GAAoBL,OAAAA,EAASM,OAAAA,EAASlD,OAAAA,EAASmD,MAAM,gBAAA,CAAA;AAE3D,MAAA,IAAI,CAACL,WAAAA,IAAe,CAACG,iBAAAA,EAAmB;AACtCP,QAAAA,MAAAA,CAAOU,KAAK,8DAAA,EAAgE;AAC1EvC,UAAAA,aAAAA,EAAeA,aAAAA,IAAiB;SAClC,CAAA;AACA,QAAA,MAAM,IAAIZ,uBAAuBwC,YAAAA,CAAAA;AACnC,MAAA;AAEA,MAAA,OAAO3G,MAAAA;AACT,IAAA;AACF,GAAA;AACF;AApEgBsG,MAAAA,CAAAA,0BAAAA,EAAAA,4BAAAA,CAAAA","file":"chunk-XUU5IBVU.js","sourcesContent":["import { GraphQLError } from 'graphql';\n\nimport type { YogaPlugin } from './types.js';\n\nexport interface UserFacingErrorOptions {\n code: string;\n userMessage: string;\n technicalMessage?: string;\n details?: Record<string, unknown>;\n httpStatus?: number;\n cause?: Error;\n}\n\nexport interface ErrorNormalizationOptions {\n serviceName?: string;\n environment?: string;\n}\n\nexport interface NormalizedErrorState {\n code: string;\n userMessage: string;\n technicalMessage: string;\n extensions: Record<string, unknown>;\n status: number;\n}\n\nexport interface HttpErrorPayload {\n error: string;\n message: string;\n userMessage: string;\n technicalMessage: string;\n code: string;\n extensions: Record<string, unknown>;\n}\n\nexport interface HttpErrorResult {\n status: number;\n body: HttpErrorPayload;\n}\n\nconst DEFAULT_ERROR_CODE = 'INTERNAL_SERVER_ERROR';\nconst DEFAULT_HTTP_STATUS = 500;\n\nconst DEFAULT_USER_MESSAGES: Record<string, string> = {\n BAD_REQUEST: 'Please check the request and try again.',\n BAD_USER_INPUT: 'Please check the information and try again.',\n CAPTCHA_FAILED: 'The verification failed. Please try again.',\n CAPTCHA_REQUIRED: 'Please complete the verification to continue.',\n COMPLEXITY_TOO_HIGH: 'This request is too large to process. Please simplify it and try again.',\n CONFLICT: 'This change conflicts with existing data. Please refresh and try again.',\n FORBIDDEN: 'You do not have permission to do that.',\n INTERNAL_SERVER_ERROR: 'Something went wrong. Please try again.',\n INVALID_PASSWORD: 'The password you entered is incorrect.',\n NOT_FOUND: 'We could not find the requested item.',\n PERMISSION_DENIED: 'You do not have permission to do that.',\n QUOTA_EXCEEDED: \"You've reached your usage limit.\",\n QUOTA_EXHAUSTED: \"You've reached your usage limit.\",\n RATE_LIMITED: 'Too many requests. Please wait a moment and try again.',\n RESOURCE_CAP_EXCEEDED: \"You've reached your plan limit. Upgrade your plan to continue.\",\n STORAGE_QUOTA_EXCEEDED: \"You've reached your storage limit. Upgrade your plan to continue.\",\n TIMEOUT: 'The request took too long. Please try again.',\n UNAUTHENTICATED: 'Please sign in to continue.',\n VALIDATION_ERROR: 'Please check the information and try again.',\n WORKSPACE_REQUIRED: 'Please choose a workspace and try again.',\n};\n\nconst DEFAULT_STATUS_BY_CODE: Record<string, number> = {\n BAD_REQUEST: 400,\n BAD_USER_INPUT: 400,\n CAPTCHA_FAILED: 400,\n CAPTCHA_REQUIRED: 400,\n COMPLEXITY_TOO_HIGH: 400,\n CONFLICT: 409,\n FORBIDDEN: 403,\n INVALID_PASSWORD: 400,\n NOT_FOUND: 404,\n PERMISSION_DENIED: 403,\n QUOTA_EXCEEDED: 429,\n QUOTA_EXHAUSTED: 429,\n RATE_LIMITED: 429,\n RESOURCE_CAP_EXCEEDED: 429,\n STORAGE_QUOTA_EXCEEDED: 429,\n TIMEOUT: 504,\n UNAUTHENTICATED: 401,\n VALIDATION_ERROR: 400,\n WORKSPACE_REQUIRED: 403,\n};\n\nconst SENSITIVE_EXTENSION_KEYS = new Set(['exception', 'originalError', 'stack', 'stacktrace']);\n\nconst TECHNICAL_MESSAGE_PATTERNS = [\n /\\bprisma\\b/i,\n /\\bsql\\b/i,\n /\\bconstraint\\b/i,\n /\\bstack\\b/i,\n /\\bundefined\\b/i,\n /\\bnull\\b/i,\n /\\bECONN[A-Z_]*\\b/,\n /\\bETIMEDOUT\\b/,\n /\\bENOTFOUND\\b/,\n /\\bP\\d{4}\\b/,\n /Cannot (read|set|find|access)/i,\n /Build failed \\(exit \\d+\\)/i,\n /JSON\\.stringify/i,\n];\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction readString(record: Record<string, unknown>, key: string): string | null {\n const value = record[key];\n return typeof value === 'string' && value.trim().length > 0 ? value : null;\n}\n\nfunction readExtensions(error: unknown): Record<string, unknown> {\n if (!isRecord(error)) return {};\n const extensions = error['extensions'];\n return isRecord(extensions) ? extensions : {};\n}\n\nfunction readOriginalError(error: unknown): Error | undefined {\n if (error instanceof GraphQLError && error.originalError instanceof Error) {\n return error.originalError;\n }\n return undefined;\n}\n\nfunction sanitizeExtensions(extensions: Record<string, unknown>): Record<string, unknown> {\n const sanitized: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(extensions)) {\n if (!SENSITIVE_EXTENSION_KEYS.has(key)) {\n sanitized[key] = value;\n }\n }\n return sanitized;\n}\n\nfunction normalizeCode(code: string | null): string {\n if (!code) return DEFAULT_ERROR_CODE;\n return code\n .trim()\n .replace(/[\\s-]+/g, '_')\n .toUpperCase();\n}\n\nfunction inferCodeFromMessage(message: string): string {\n const lower = message.toLowerCase();\n\n if (\n lower.includes('unauthenticated') ||\n lower.includes('not authenticated') ||\n lower.includes('authentication required') ||\n lower.includes('unauthorized') ||\n lower.includes('please sign in') ||\n lower.includes('sign in to')\n ) {\n return 'UNAUTHENTICATED';\n }\n\n if (lower.includes('workspace context') || lower.includes('switch to a workspace')) {\n return 'WORKSPACE_REQUIRED';\n }\n\n if (\n lower.includes('forbidden') ||\n lower.includes('access denied') ||\n lower.includes('permission denied') ||\n lower.includes('not authorized')\n ) {\n return 'FORBIDDEN';\n }\n\n if (lower.includes('not found') || lower.includes('disappeared')) {\n return 'NOT_FOUND';\n }\n\n if (lower.includes('already exists') || lower.includes('already taken') || lower.includes('conflict')) {\n return 'CONFLICT';\n }\n\n if (lower.includes('quota') || lower.includes('cap exceeded') || lower.includes('limit reached')) {\n return 'QUOTA_EXCEEDED';\n }\n\n if (lower.includes('timeout') || lower.includes('timed out')) {\n return 'TIMEOUT';\n }\n\n if (\n lower.includes('required') ||\n lower.includes('invalid') ||\n lower.includes('missing') ||\n lower.includes('unsupported')\n ) {\n return 'BAD_USER_INPUT';\n }\n\n return DEFAULT_ERROR_CODE;\n}\n\nfunction inferCode(error: unknown, extensions: Record<string, unknown>, originalError: Error | undefined): string {\n const extensionCode = typeof extensions['code'] === 'string' ? extensions['code'] : null;\n if (extensionCode) return normalizeCode(extensionCode);\n\n if (isRecord(originalError)) {\n const originalCode = readString(originalError, 'code');\n if (originalCode) return normalizeCode(originalCode);\n }\n\n if (isRecord(error)) {\n const directCode = readString(error, 'code');\n if (directCode) return normalizeCode(directCode);\n }\n\n const message = readErrorMessage(error);\n return inferCodeFromMessage(message);\n}\n\nfunction readErrorMessage(error: unknown): string {\n if (error instanceof Error && error.message.trim().length > 0) {\n return error.message;\n }\n if (isRecord(error)) {\n const message = readString(error, 'message');\n if (message) return message;\n }\n return DEFAULT_USER_MESSAGES[DEFAULT_ERROR_CODE] ?? 'Something went wrong. Please try again.';\n}\n\nfunction isLikelyTechnicalMessage(message: string): boolean {\n if (message.length > 220) return true;\n if (message.includes('\\n')) return true;\n if (message.includes('{') && message.includes('}')) return true;\n return TECHNICAL_MESSAGE_PATTERNS.some((pattern) => pattern.test(message));\n}\n\nfunction readExplicitUserMessage(extensions: Record<string, unknown>): string | null {\n return (\n readString(extensions, 'userMessage') ??\n readString(extensions, 'humanMessage') ??\n readString(extensions, 'displayMessage')\n );\n}\n\nfunction resolveUserMessage(code: string, message: string, extensions: Record<string, unknown>): string {\n const explicit = readExplicitUserMessage(extensions);\n if (explicit) return explicit;\n\n const fallback =\n DEFAULT_USER_MESSAGES[code] ??\n DEFAULT_USER_MESSAGES[DEFAULT_ERROR_CODE] ??\n 'Something went wrong. Please try again.';\n if (code === DEFAULT_ERROR_CODE) {\n return fallback;\n }\n\n if (!isLikelyTechnicalMessage(message)) {\n return message;\n }\n\n return fallback;\n}\n\nfunction resolveTechnicalMessage(\n code: string,\n message: string,\n extensions: Record<string, unknown>,\n options: ErrorNormalizationOptions\n): string {\n const explicit = readString(extensions, 'technicalMessage');\n if (explicit) return explicit;\n\n if (options.environment === 'production' && code === DEFAULT_ERROR_CODE) {\n return options.serviceName ? `${options.serviceName} returned ${DEFAULT_ERROR_CODE}` : DEFAULT_ERROR_CODE;\n }\n\n return message;\n}\n\nfunction readHttpStatus(extensions: Record<string, unknown>, code: string): number {\n const http = extensions['http'];\n if (isRecord(http) && typeof http['status'] === 'number') {\n return http['status'];\n }\n return DEFAULT_STATUS_BY_CODE[code] ?? DEFAULT_HTTP_STATUS;\n}\n\nexport function normalizeError(error: unknown, options: ErrorNormalizationOptions = {}): NormalizedErrorState {\n const originalError = readOriginalError(error);\n const originalExtensions = readExtensions(originalError);\n const directExtensions = readExtensions(error);\n const mergedExtensions = sanitizeExtensions({ ...originalExtensions, ...directExtensions });\n const message = readErrorMessage(error);\n const code = inferCode(error, mergedExtensions, originalError);\n const userMessage = resolveUserMessage(code, message, mergedExtensions);\n const technicalMessage = resolveTechnicalMessage(code, message, mergedExtensions, options);\n const status = readHttpStatus(mergedExtensions, code);\n\n const extensions: Record<string, unknown> = {\n ...mergedExtensions,\n code,\n userMessage,\n technicalMessage,\n };\n\n if (options.serviceName) {\n extensions['serviceName'] = options.serviceName;\n }\n\n if (!isRecord(extensions['http'])) {\n extensions['http'] = { status };\n }\n\n return {\n code,\n userMessage,\n technicalMessage,\n extensions,\n status,\n };\n}\n\nexport class UserFacingGraphQLError extends GraphQLError {\n constructor(options: UserFacingErrorOptions) {\n const extensions: Record<string, unknown> = {\n code: normalizeCode(options.code),\n userMessage: options.userMessage,\n technicalMessage: options.technicalMessage ?? options.userMessage,\n };\n\n if (options.details) {\n extensions['details'] = options.details;\n }\n\n if (options.httpStatus) {\n extensions['http'] = { status: options.httpStatus };\n }\n\n super(options.userMessage, {\n originalError: options.cause,\n extensions,\n });\n this.name = 'UserFacingGraphQLError';\n }\n}\n\nexport function toUserFacingGraphQLError(error: unknown, options: ErrorNormalizationOptions = {}): GraphQLError {\n const normalized = normalizeError(error, options);\n\n if (error instanceof GraphQLError) {\n return new GraphQLError(normalized.userMessage, {\n nodes: error.nodes,\n source: error.source,\n positions: error.positions,\n path: error.path,\n originalError: error.originalError,\n extensions: normalized.extensions,\n });\n }\n\n return new GraphQLError(normalized.userMessage, {\n originalError: error instanceof Error ? error : undefined,\n extensions: normalized.extensions,\n });\n}\n\nexport function normalizeExecutionResultErrors(result: unknown, options: ErrorNormalizationOptions = {}): void {\n if (!isRecord(result)) return;\n const errors = result['errors'];\n if (!Array.isArray(errors) || errors.length === 0) return;\n\n result['errors'] = errors.map((error) => toUserFacingGraphQLError(error, options));\n}\n\nexport function createHumanReadableErrorPlugin(options: ErrorNormalizationOptions = {}): YogaPlugin {\n return {\n onExecute() {\n return {\n onExecuteDone({ result }: { result: unknown }) {\n normalizeExecutionResultErrors(result, options);\n },\n };\n },\n };\n}\n\nexport function formatHttpError(error: unknown, options: ErrorNormalizationOptions = {}): HttpErrorResult {\n const normalized = normalizeError(error, options);\n return {\n status: normalized.status,\n body: {\n error: normalized.userMessage,\n message: normalized.userMessage,\n userMessage: normalized.userMessage,\n technicalMessage: normalized.technicalMessage,\n code: normalized.code,\n extensions: normalized.extensions,\n },\n };\n}\n\nexport function createHttpErrorResponse(error: unknown, options: ErrorNormalizationOptions = {}): Response {\n const formatted = formatHttpError(error, options);\n return new Response(JSON.stringify(formatted.body), {\n status: formatted.status,\n headers: { 'Content-Type': 'application/json' },\n });\n}\n","/**\n * Workspace Guard Plugin for GraphQL Yoga\n *\n * Blocks GraphQL operations that lack a valid workspace context (x-workspace-id header).\n * This provides defense-in-depth at the GraphQL layer — even if the gateway allows a request\n * through, the service itself will reject it if workspace context is missing.\n *\n * **Whitelisted operations** (e.g., workspace creation) can bypass the guard.\n *\n * **Public schema fields** marked with `@public` or `@rbac(public: true)` are auto-bypassed\n * when `allowPublicDirective` is enabled (default true). This lets anonymous public-link\n * resolvers (e.g. `accessShare`) be reached through the federation gateway without an\n * `x-workspace-id` header.\n *\n * @module server/workspace-guard\n * @category Security\n */\n\nimport { logger } from '../logger/index.js';\nimport { UserFacingGraphQLError } from './errors.js';\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * Configuration for the workspace guard plugin\n */\nexport interface WorkspaceGuardConfig {\n /**\n * Enable the workspace guard.\n * @default true\n */\n enabled?: boolean;\n\n /**\n * GraphQL operation names that can run without workspace context.\n * These are typically operations like `createWorkspace` that execute\n * before a workspace exists.\n *\n * Matching is case-sensitive against the operation name in the GraphQL document.\n *\n * @default []\n *\n * @example\n * ```typescript\n * whitelistedOperations: ['createWorkspace', 'validateTokens']\n * ```\n */\n whitelistedOperations?: string[];\n\n /**\n * Custom error message when workspace context is missing.\n * @default 'Workspace context required. Provide a valid X-Workspace-Authorization header.'\n */\n errorMessage?: string;\n\n /**\n * If true, fields whose schema definition carries the `@public` directive or\n * `@rbac(public: true)` are bypassed by the guard automatically — no need to\n * list them in `whitelistedOperations`. The check uses the GraphQL schema\n * passed to the executor at request time.\n *\n * Set to false to fall back to the legacy operation-name allowlist only.\n *\n * @default true\n */\n allowPublicDirective?: boolean;\n}\n\n// ============================================================================\n// GraphQL Error\n// ============================================================================\n\n/**\n * Workspace required error with proper GraphQL error extensions\n */\nclass WorkspaceRequiredError extends UserFacingGraphQLError {\n constructor(message: string) {\n super({\n code: 'WORKSPACE_REQUIRED',\n userMessage: 'Please choose a workspace and try again.',\n technicalMessage: message,\n httpStatus: 403,\n });\n this.name = 'WorkspaceRequiredError';\n }\n}\n\n// ============================================================================\n// Schema directive helpers\n// ============================================================================\n\n/**\n * Minimal structural typings for the bits of the GraphQL schema we look at.\n * We avoid importing the GraphQL types directly so the SDK keeps `graphql`\n * as a peer dep without a runtime hard dependency.\n */\ninterface FieldLikeDef {\n astNode?: {\n directives?: ReadonlyArray<{\n name: { value: string };\n arguments?: ReadonlyArray<{\n name: { value: string };\n value: { kind: string; value?: unknown };\n }>;\n }>;\n };\n}\n\ninterface SchemaLike {\n getQueryType?: () => { getFields: () => Record<string, FieldLikeDef> } | null | undefined;\n getMutationType?: () => { getFields: () => Record<string, FieldLikeDef> } | null | undefined;\n getSubscriptionType?: () => { getFields: () => Record<string, FieldLikeDef> } | null | undefined;\n}\n\n/**\n * Returns true iff the field carries either:\n * - `@public` directive, OR\n * - `@rbac(public: true)` directive (any arg-order)\n */\nfunction isFieldPublic(field: FieldLikeDef | undefined): boolean {\n const directives = field?.astNode?.directives;\n if (!directives || directives.length === 0) return false;\n\n for (const dir of directives) {\n const name = dir.name?.value;\n if (name === 'public') return true;\n if (name === 'rbac') {\n const args = dir.arguments ?? [];\n for (const arg of args) {\n if (arg.name?.value === 'public' && arg.value?.kind === 'BooleanValue' && arg.value.value === true) {\n return true;\n }\n }\n }\n }\n return false;\n}\n\ninterface DocumentLike {\n definitions?: ReadonlyArray<{\n kind?: string;\n operation?: string;\n name?: { value?: string };\n selectionSet?: {\n selections?: ReadonlyArray<{\n kind?: string;\n name?: { value?: string };\n }>;\n };\n }>;\n}\n\n/**\n * Resolve the operation type ('query' | 'mutation' | 'subscription') for the\n * primary operation in the document. Falls back to 'query'.\n */\nfunction resolveOperationType(\n document: DocumentLike | undefined,\n operationName: string | null | undefined\n): 'query' | 'mutation' | 'subscription' {\n const defs = document?.definitions ?? [];\n for (const def of defs) {\n if (def.kind !== 'OperationDefinition') {\n // Older parsers may not set kind; fall through to the operation property check below.\n }\n if (def.operation && (!operationName || def.name?.value === operationName)) {\n return def.operation as 'query' | 'mutation' | 'subscription';\n }\n }\n return 'query';\n}\n\n/**\n * Returns true iff every root field in the document selection set is marked\n * public on the schema. Empty selection sets return false (fail-closed).\n */\nfunction allRootFieldsPublic(\n schema: SchemaLike | undefined,\n document: DocumentLike | undefined,\n operationName: string | null | undefined\n): boolean {\n if (!schema || !document) return false;\n\n const opType = resolveOperationType(document, operationName);\n let rootType: ReturnType<NonNullable<SchemaLike['getQueryType']>> | undefined;\n if (opType === 'mutation') {\n rootType = schema.getMutationType?.();\n } else if (opType === 'subscription') {\n rootType = schema.getSubscriptionType?.();\n } else {\n rootType = schema.getQueryType?.();\n }\n\n if (!rootType) return false;\n\n const fields = rootType.getFields();\n const defs = document.definitions ?? [];\n\n // Find the operation definition matching operationName (or first one).\n const opDef = defs.find((d) => d.operation && (!operationName || d.name?.value === operationName));\n const selections = opDef?.selectionSet?.selections ?? [];\n if (selections.length === 0) return false;\n\n for (const sel of selections) {\n // Only consider plain Field selections (skip fragments — fragments at the root\n // shouldn't drive a public bypass; fail-closed there).\n if (sel.kind && sel.kind !== 'Field') return false;\n const fieldName = sel.name?.value;\n if (!fieldName) return false;\n // __schema / __type introspection is always allowed without workspace context;\n // treat them as public.\n if (fieldName.startsWith('__')) continue;\n const fieldDef = fields[fieldName];\n if (!isFieldPublic(fieldDef)) return false;\n }\n return true;\n}\n\n// ============================================================================\n// Plugin\n// ============================================================================\n\n/**\n * Create a GraphQL Yoga plugin that guards operations requiring workspace context.\n *\n * The plugin inspects the GraphQL context for workspace information (set by the SDK's\n * buildContext from the x-workspace-id header). If missing and the operation is not\n * whitelisted (and not all-public per directive), it throws a WORKSPACE_REQUIRED error.\n *\n * @param config - Guard configuration\n * @returns A Yoga-compatible plugin\n *\n * @example\n * ```typescript\n * import { createWorkspaceGuardPlugin } from '@burdenoff/be-sdk/server';\n *\n * const guardPlugin = createWorkspaceGuardPlugin({\n * whitelistedOperations: ['createWorkspace'],\n * allowPublicDirective: true, // default\n * });\n * ```\n */\nexport function createWorkspaceGuardPlugin(config?: WorkspaceGuardConfig) {\n const enabled = config?.enabled ?? true;\n const whitelistedOperations = new Set(config?.whitelistedOperations ?? []);\n const allowPublicDirective = config?.allowPublicDirective ?? true;\n const errorMessage =\n config?.errorMessage ??\n 'Workspace context required. Ensure the request includes a valid workspace context (x-workspace-id header).';\n\n if (!enabled) {\n logger.info('[WorkspaceGuard] Workspace guard disabled');\n return {};\n }\n\n logger.info('[WorkspaceGuard] Workspace guard enabled', {\n whitelistedOperations: [...whitelistedOperations],\n allowPublicDirective,\n });\n\n return {\n onExecute({\n args,\n }: {\n args: {\n schema?: SchemaLike;\n document?: DocumentLike;\n operationName?: string | null;\n contextValue?: { workspace?: { id?: string }; request?: Request };\n };\n }) {\n // Extract operation name from args or document\n let operationName = args.operationName;\n\n if (!operationName && args.document?.definitions) {\n for (const def of args.document.definitions) {\n if (def.operation && def.name?.value) {\n operationName = def.name.value;\n break;\n }\n }\n }\n\n // Check if operation is whitelisted by name\n if (operationName && whitelistedOperations.has(operationName)) {\n return undefined;\n }\n\n // Check schema-directive-based public bypass (Option C)\n if (allowPublicDirective && allRootFieldsPublic(args.schema, args.document, operationName)) {\n return undefined;\n }\n\n // Check for workspace context\n const context = args.contextValue;\n const workspaceId = context?.workspace?.id;\n\n // Also check the raw header as a fallback\n const headerWorkspaceId = context?.request?.headers?.get?.('x-workspace-id');\n\n if (!workspaceId && !headerWorkspaceId) {\n logger.warn('[WorkspaceGuard] Blocked operation without workspace context', {\n operationName: operationName ?? '<anonymous>',\n });\n throw new WorkspaceRequiredError(errorMessage);\n }\n\n return undefined;\n },\n };\n}\n"]}
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- export { prisma_exports as Prisma } from './chunk-BRYRHBAC.js';
2
- export { RESOURCE_CAP_DEFAULTS, ResourceCapExceededError, ResourceCapsModule, getResourceCaps } from './chunk-7BMKOD7N.js';
1
+ export { prisma_exports as Prisma } from './chunk-54BMP5OJ.js';
2
+ export { RESOURCE_CAP_DEFAULTS, ResourceCapExceededError, ResourceCapsModule, getResourceCaps } from './chunk-VDDOGIWY.js';
3
3
  import './chunk-GTEMQXCA.js';
4
4
  export { TemporalClient, TemporalClientFactory, TemporalModule, TemporalWorker, TemporalWorkerFactory, TemporalWorkerManager } from './chunk-5SD7DU3L.js';
5
5
  import { ActivityModule, UsageModule, TrackerModule } from './chunk-PPIDJP2W.js';
@@ -34,8 +34,8 @@ import { AuthModule } from './chunk-7NUQXGA7.js';
34
34
  export { AuthModule } from './chunk-7NUQXGA7.js';
35
35
  export { utils_exports as Utils } from './chunk-B7I4TABG.js';
36
36
  export { cache_exports as Cache } from './chunk-PDSV3TFO.js';
37
- export { captcha_exports as Captcha, isCaptchaEnabled, verifyCaptcha, verifyCaptchaIfEnabled } from './chunk-YMZEUTD2.js';
38
37
  export { createInternalClient, createInternalClientForTenant, createInternalClientForWorkspaces } from './chunk-VI4VSNTI.js';
38
+ export { captcha_exports as Captcha, isCaptchaEnabled, verifyCaptcha, verifyCaptchaIfEnabled } from './chunk-YMZEUTD2.js';
39
39
  export { crypto_exports as Crypto } from './chunk-SBS4S2PJ.js';
40
40
  import { DatabaseModule } from './chunk-UFQQSQG6.js';
41
41
  export { DatabaseModule } from './chunk-UFQQSQG6.js';
@@ -1,4 +1,4 @@
1
- export { PrismaClientWrapper, buildContextWhereClause, buildContextWhereConditions, checkDatabaseHealth, configurePrismaLogging, contextMatches, createConnectionPool, createContextFromSDK, createDatabaseClient, createDatabaseClientFromEnv, createPrismaAdapter, createPrismaClient, extractFieldsFromModel, getAllModelNames, getDatabaseManager, getDatabaseProductName, getDatabaseStats, getDatabaseVersion, getDb, getModelFields, hasModel, initializeDatabase, initializeDatabaseWithConfig, isDatabaseInitialized, loadGeneratedFields, mergeContext, parseContext, resetDatabaseManager, testConnection, toContextJson } from '../chunk-BRYRHBAC.js';
1
+ export { PrismaClientWrapper, buildContextWhereClause, buildContextWhereConditions, checkDatabaseHealth, configurePrismaLogging, contextMatches, createConnectionPool, createContextFromSDK, createDatabaseClient, createDatabaseClientFromEnv, createPrismaAdapter, createPrismaClient, extractFieldsFromModel, getAllModelNames, getDatabaseManager, getDatabaseProductName, getDatabaseStats, getDatabaseVersion, getDb, getModelFields, hasModel, initializeDatabase, initializeDatabaseWithConfig, isDatabaseInitialized, loadGeneratedFields, mergeContext, parseContext, resetDatabaseManager, testConnection, toContextJson } from '../chunk-54BMP5OJ.js';
2
2
  export { addWorkspaceExtension, getWorkspaceContext, injectWhereWorkspaceId, setWorkspaceContext, withWorkspaceContext, withWorkspaceContextSync } from '../chunk-GTEMQXCA.js';
3
3
  import '../chunk-5CESUKWC.js';
4
4
  import '../chunk-QRWTLPW5.js';
@@ -1,4 +1,4 @@
1
- export { RESOURCE_CAP_DEFAULTS, ResourceCapExceededError, ResourceCapsModule, __resetResourceCapsForTests, getResourceCaps } from '../chunk-7BMKOD7N.js';
1
+ export { RESOURCE_CAP_DEFAULTS, ResourceCapExceededError, ResourceCapsModule, __resetResourceCapsForTests, getResourceCaps } from '../chunk-VDDOGIWY.js';
2
2
  import '../chunk-CBZNP6RF.js';
3
3
  import '../chunk-XE4OXN2W.js';
4
4
  //# sourceMappingURL=index.js.map
@@ -1,4 +1,4 @@
1
- import { GraphQLSchema } from 'graphql';
1
+ import { GraphQLSchema, GraphQLError } from 'graphql';
2
2
  import { PubSub } from 'graphql-yoga';
3
3
  import { P as PrismaClientBase, a as PrismaClientConstructorOptions } from '../client-CSjIrYKS.js';
4
4
  import { I as I18nContext, L as LocaleCode, d as I18n } from '../i18n-DA6IPnYy.js';
@@ -356,4 +356,45 @@ declare function createWorkspaceGuardPlugin(config?: WorkspaceGuardConfig): {
356
356
  }): undefined;
357
357
  };
358
358
 
359
- export { type AuthConfig, type ConsentContext, type ContextBuilderOptions, type ElysiaApp, type FetchWorkspaceSecretFn, type GraphQLContext, I18nContext, type IActor, type IContextFilterInput, type IOperationContext, type IOrganization, type IProduct, type IProject, type ITenant, type ITracking, type IWorkspace, type JWTPayload, LocaleCode, type ModuleGraphConfig, PrismaClientBase, type PrismaClientConstructor, type RESTEndpoint, type ServerConfig, type ServerDefinition, type ServerI18nConfig, type ServerInfo, type ServerInstance, type WorkspaceGuardConfig, type WorkspaceSecret, type WspaceGraphQLContext, type YogaPlugin, authCheck, buildContext, configureAuth, configureContext, configureDefaultAuth, configureServerAuth, createServer, createWorkspaceGuardPlugin, decodeJWT, fetchWorkspaceSecret, generateSymmetricSecret, getContextOptions, orgCheck, requireWorkspace, tenantCheck, verifyJWT, workspaceCheck };
359
+ interface UserFacingErrorOptions {
360
+ code: string;
361
+ userMessage: string;
362
+ technicalMessage?: string;
363
+ details?: Record<string, unknown>;
364
+ httpStatus?: number;
365
+ cause?: Error;
366
+ }
367
+ interface ErrorNormalizationOptions {
368
+ serviceName?: string;
369
+ environment?: string;
370
+ }
371
+ interface NormalizedErrorState {
372
+ code: string;
373
+ userMessage: string;
374
+ technicalMessage: string;
375
+ extensions: Record<string, unknown>;
376
+ status: number;
377
+ }
378
+ interface HttpErrorPayload {
379
+ error: string;
380
+ message: string;
381
+ userMessage: string;
382
+ technicalMessage: string;
383
+ code: string;
384
+ extensions: Record<string, unknown>;
385
+ }
386
+ interface HttpErrorResult {
387
+ status: number;
388
+ body: HttpErrorPayload;
389
+ }
390
+ declare function normalizeError(error: unknown, options?: ErrorNormalizationOptions): NormalizedErrorState;
391
+ declare class UserFacingGraphQLError extends GraphQLError {
392
+ constructor(options: UserFacingErrorOptions);
393
+ }
394
+ declare function toUserFacingGraphQLError(error: unknown, options?: ErrorNormalizationOptions): GraphQLError;
395
+ declare function normalizeExecutionResultErrors(result: unknown, options?: ErrorNormalizationOptions): void;
396
+ declare function createHumanReadableErrorPlugin(options?: ErrorNormalizationOptions): YogaPlugin;
397
+ declare function formatHttpError(error: unknown, options?: ErrorNormalizationOptions): HttpErrorResult;
398
+ declare function createHttpErrorResponse(error: unknown, options?: ErrorNormalizationOptions): Response;
399
+
400
+ export { type AuthConfig, type ConsentContext, type ContextBuilderOptions, type ElysiaApp, type ErrorNormalizationOptions, type FetchWorkspaceSecretFn, type GraphQLContext, type HttpErrorPayload, type HttpErrorResult, I18nContext, type IActor, type IContextFilterInput, type IOperationContext, type IOrganization, type IProduct, type IProject, type ITenant, type ITracking, type IWorkspace, type JWTPayload, LocaleCode, type ModuleGraphConfig, type NormalizedErrorState, PrismaClientBase, type PrismaClientConstructor, type RESTEndpoint, type ServerConfig, type ServerDefinition, type ServerI18nConfig, type ServerInfo, type ServerInstance, type UserFacingErrorOptions, UserFacingGraphQLError, type WorkspaceGuardConfig, type WorkspaceSecret, type WspaceGraphQLContext, type YogaPlugin, authCheck, buildContext, configureAuth, configureContext, configureDefaultAuth, configureServerAuth, createHttpErrorResponse, createHumanReadableErrorPlugin, createServer, createWorkspaceGuardPlugin, decodeJWT, fetchWorkspaceSecret, formatHttpError, generateSymmetricSecret, getContextOptions, normalizeError, normalizeExecutionResultErrors, orgCheck, requireWorkspace, tenantCheck, toUserFacingGraphQLError, verifyJWT, workspaceCheck };