@burdenoff/be-sdk 2026.1110.3 → 2026.1110.4
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/dist/activity/index.d.ts +165 -0
- package/dist/activity/index.js +389 -0
- package/dist/activity/index.js.map +1 -0
- package/dist/ai-credits/index.js +1 -1
- package/dist/{ai-credits-Ca-NNcVx.js → ai-credits-xxfwGpHS.js} +2 -2
- package/dist/{ai-credits-Ca-NNcVx.js.map → ai-credits-xxfwGpHS.js.map} +1 -1
- package/dist/auth/index.d.ts +1 -1
- package/dist/auth/index.js +1 -1
- package/dist/{auth-CEuBEBQN.js → auth-C5ctwSLp.js} +2 -2
- package/dist/{auth-CEuBEBQN.js.map → auth-C5ctwSLp.js.map} +1 -1
- package/dist/bootstrap/index.d.ts +74 -0
- package/dist/bootstrap/index.js +282 -0
- package/dist/bootstrap/index.js.map +1 -0
- package/dist/{client-DcZ3iGES.js → client-sAJTrb4i.js} +2 -2
- package/dist/{client-DcZ3iGES.js.map → client-sAJTrb4i.js.map} +1 -1
- package/dist/context/index.d.ts +35 -0
- package/dist/{context-CZnXf2yb.js → context/index.js} +38 -2
- package/dist/context/index.js.map +1 -0
- package/dist/database/index.js +1 -1
- package/dist/event-queue/index.d.ts +1 -1
- package/dist/explicit-activity-scope-DikJ7NAE.js +57 -0
- package/dist/explicit-activity-scope-DikJ7NAE.js.map +1 -0
- package/dist/export/index.js +1 -1
- package/dist/{export-B6fphx8a.js → export-DJXE3Osa.js} +3 -3
- package/dist/{export-B6fphx8a.js.map → export-DJXE3Osa.js.map} +1 -1
- package/dist/feature-flags/index.js +1 -1
- package/dist/{feature-flags-71oDkrUe.js → feature-flags-CP1KRgwD.js} +2 -2
- package/dist/{feature-flags-71oDkrUe.js.map → feature-flags-CP1KRgwD.js.map} +1 -1
- package/dist/files/index.js +1 -1
- package/dist/{files-DjH0099H.js → files-h5U-D2AF.js} +2 -2
- package/dist/{files-DjH0099H.js.map → files-h5U-D2AF.js.map} +1 -1
- package/dist/gateway/index.js +2 -2
- package/dist/{gateway-DBFmxWks.js → gateway-ByVo-n37.js} +2 -2
- package/dist/{gateway-DBFmxWks.js.map → gateway-ByVo-n37.js.map} +1 -1
- package/dist/graph/index.d.ts +1 -1
- package/dist/graph/index.js +1 -1
- package/dist/{graph-DDYgIryR.js → graph-CR7u4lpl.js} +2 -2
- package/dist/{graph-DDYgIryR.js.map → graph-CR7u4lpl.js.map} +1 -1
- package/dist/{graphql-DNkMkGBZ.d.ts → graphql-CUDyhibV.d.ts} +1 -1
- package/dist/{index-bZKZUvBu.d.ts → index-ADmsX0BI.d.ts} +3 -3
- package/dist/{index-BqYfCQSP.d.ts → index-B2LCaK0R.d.ts} +1 -1
- package/dist/{index-D6UeLAye.d.ts → index-CHwMhK6v.d.ts} +2 -2
- package/dist/{index-BQDsNAMR.d.ts → index-CTTwo9av.d.ts} +22 -1
- package/dist/{index-DZC-2o9R.d.ts → index-CVCyKzhB.d.ts} +2 -2
- package/dist/{index-CkT2aUr3.d.ts → index-C_GXXF32.d.ts} +2 -2
- package/dist/{index-BKwHQtHQ.d.ts → index-Cot73bdh.d.ts} +1 -1
- package/dist/{index-CnzbJZP7.d.ts → index-FRRaa6h2.d.ts} +2 -2
- package/dist/{index-N-huORcj.d.ts → index-U_tu3zUl.d.ts} +2 -2
- package/dist/index-cmR9k9ga.d.ts +26 -0
- package/dist/{index-CZTnQIRU.d.ts → index-zd_NPGJo.d.ts} +6 -141
- package/dist/index.d.ts +19 -479
- package/dist/index.js +22 -1492
- package/dist/index.js.map +1 -1
- package/dist/init/index.js +1 -1
- package/dist/{init-Dy3KhT6Y.js → init-CQPFmOOe.js} +3 -3
- package/dist/{init-Dy3KhT6Y.js.map → init-CQPFmOOe.js.map} +1 -1
- package/dist/instrumentation/index.d.ts +2 -2
- package/dist/logger/index.d.ts +1 -1
- package/dist/notifications/index.d.ts +1 -1
- package/dist/notifications/index.js +1 -1
- package/dist/{notifications-CdETrtFK.js → notifications-DY_i37WN.js} +2 -2
- package/dist/{notifications-CdETrtFK.js.map → notifications-DY_i37WN.js.map} +1 -1
- package/dist/payments/index.d.ts +144 -0
- package/dist/payments/index.js +404 -0
- package/dist/payments/index.js.map +1 -0
- package/dist/rate-limit-CBrK_U5H.js +142 -0
- package/dist/rate-limit-CBrK_U5H.js.map +1 -0
- package/dist/rbac/index.d.ts +1 -1
- package/dist/rbac/index.js +1 -1
- package/dist/{rbac-BB9l9Xph.js → rbac-Dvz0YzEt.js} +2 -2
- package/dist/{rbac-BB9l9Xph.js.map → rbac-Dvz0YzEt.js.map} +1 -1
- package/dist/resource-caps/index.d.ts +1 -1
- package/dist/search/index.d.ts +112 -0
- package/dist/search/index.js +266 -0
- package/dist/search/index.js.map +1 -0
- package/dist/security/index.d.ts +2 -0
- package/dist/security/index.js +4 -0
- package/dist/security/index.js.map +1 -0
- package/dist/security/rate-limit/index.d.ts +2 -0
- package/dist/security/rate-limit/index.js +4 -0
- package/dist/security/rate-limit/index.js.map +1 -0
- package/dist/server/index.js +3 -2
- package/dist/server/index.js.map +1 -1
- package/dist/{stub-BqwKn4eh.js → stub-BUnfMiAS.js} +3 -56
- package/dist/stub-BUnfMiAS.js.map +1 -0
- package/dist/tags/index.js +1 -1
- package/dist/{tags-B5xpbgsk.js → tags-CbijgoqR.js} +2 -2
- package/dist/{tags-B5xpbgsk.js.map → tags-CbijgoqR.js.map} +1 -1
- package/dist/telemetry/index.d.ts +2 -2
- package/dist/tracker/index.d.ts +2 -2
- package/dist/tracker/index.js +5 -3
- package/dist/{tracker-BQVoEFUo.js → tracker-PQztSlhJ.js} +9 -390
- package/dist/tracker-PQztSlhJ.js.map +1 -0
- package/dist/translation/index.d.ts +120 -0
- package/dist/translation/index.js +573 -0
- package/dist/translation/index.js.map +1 -0
- package/dist/types/index.d.ts +3 -0
- package/dist/{types-Cj2RWXbz.js → types/index.js} +3 -3
- package/dist/types/index.js.map +1 -0
- package/dist/usage/index.d.ts +1 -1
- package/dist/usage/index.js +1 -1
- package/dist/{usage-BKFZiWQn.js → usage-BRqVP3CJ.js} +4 -4
- package/dist/{usage-BKFZiWQn.js.map → usage-BRqVP3CJ.js.map} +1 -1
- package/package.json +1 -1
- package/dist/context-CZnXf2yb.js.map +0 -1
- package/dist/stub-BqwKn4eh.js.map +0 -1
- package/dist/tracker-BQVoEFUo.js.map +0 -1
- package/dist/types-Cj2RWXbz.js.map +0 -1
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
import { a as logger } from "../logger-B6rCpb7D.js";
|
|
2
|
+
import { DatabaseModule } from "../database/index.js";
|
|
3
|
+
import { ContextManager } from "../context/index.js";
|
|
4
|
+
import { n as disposeAll } from "../lifecycle-DeoLSX0U.js";
|
|
5
|
+
|
|
6
|
+
// src/bootstrap/index.ts
|
|
7
|
+
/**
|
|
8
|
+
* Bootstrap Module
|
|
9
|
+
* Helpers for bootstrapping server, loading modules, and setting up schemas
|
|
10
|
+
*/
|
|
11
|
+
/**
|
|
12
|
+
* Bootstrap Module
|
|
13
|
+
*/
|
|
14
|
+
var BootstrapModule = class {
|
|
15
|
+
config;
|
|
16
|
+
startTime;
|
|
17
|
+
healthCheckInterval;
|
|
18
|
+
constructor(config) {
|
|
19
|
+
this.config = config;
|
|
20
|
+
this.startTime = /* @__PURE__ */ new Date();
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Bootstrap the application
|
|
24
|
+
*/
|
|
25
|
+
async bootstrap() {
|
|
26
|
+
logger.info("[Bootstrap] Starting application bootstrap", {
|
|
27
|
+
serviceName: this.config.serviceName,
|
|
28
|
+
environment: this.config.environment || "development"
|
|
29
|
+
});
|
|
30
|
+
try {
|
|
31
|
+
await this.validateConfiguration();
|
|
32
|
+
const databaseConnected = await this.connectDatabase();
|
|
33
|
+
const loadedModules = await this.loadModules();
|
|
34
|
+
if (this.config.healthCheck) await this.setupHealthChecks();
|
|
35
|
+
this.setupSignalHandlers();
|
|
36
|
+
const result = {
|
|
37
|
+
success: true,
|
|
38
|
+
serviceName: this.config.serviceName || "burdenoff-service",
|
|
39
|
+
serviceVersion: this.config.serviceVersion || "1.0.0",
|
|
40
|
+
environment: this.config.environment || "development",
|
|
41
|
+
startedAt: this.startTime.toISOString(),
|
|
42
|
+
modules: loadedModules,
|
|
43
|
+
databaseConnected,
|
|
44
|
+
healthCheckEnabled: this.config.healthCheck || false
|
|
45
|
+
};
|
|
46
|
+
logger.info("[Bootstrap] Application bootstrapped successfully", result);
|
|
47
|
+
return result;
|
|
48
|
+
} catch (error) {
|
|
49
|
+
logger.error("[Bootstrap] Failed to bootstrap application", { error });
|
|
50
|
+
throw error;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Validate configuration
|
|
55
|
+
*/
|
|
56
|
+
async validateConfiguration() {
|
|
57
|
+
logger.debug("[Bootstrap] Validating configuration");
|
|
58
|
+
if (!this.config.workspacesApiUrl) throw new Error("Workspaces API URL is required");
|
|
59
|
+
if (this.config.database?.url && !DatabaseModule.validateDatabaseUrl(this.config.database.url)) throw new Error("Invalid database URL");
|
|
60
|
+
logger.debug("[Bootstrap] Configuration validated");
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Connect to database
|
|
64
|
+
*/
|
|
65
|
+
async connectDatabase() {
|
|
66
|
+
if (!this.config.database) {
|
|
67
|
+
logger.debug("[Bootstrap] No database configuration provided, skipping");
|
|
68
|
+
return false;
|
|
69
|
+
}
|
|
70
|
+
logger.info("[Bootstrap] Connecting to database");
|
|
71
|
+
try {
|
|
72
|
+
const sanitizedUrl = DatabaseModule.sanitizeDatabaseUrl(this.config.database.url);
|
|
73
|
+
logger.info("[Bootstrap] Database connection configured", { url: sanitizedUrl });
|
|
74
|
+
return true;
|
|
75
|
+
} catch (error) {
|
|
76
|
+
logger.error("[Bootstrap] Failed to connect to database", { error });
|
|
77
|
+
return false;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Load modules
|
|
82
|
+
*/
|
|
83
|
+
async loadModules() {
|
|
84
|
+
const modules = this.config.modules || [];
|
|
85
|
+
if (modules.length === 0) {
|
|
86
|
+
logger.debug("[Bootstrap] No modules to load");
|
|
87
|
+
return [];
|
|
88
|
+
}
|
|
89
|
+
logger.info("[Bootstrap] Loading modules", { modules });
|
|
90
|
+
const loadedModules = [];
|
|
91
|
+
for (const moduleName of modules) try {
|
|
92
|
+
logger.debug(`[Bootstrap] Loading module: ${moduleName}`);
|
|
93
|
+
loadedModules.push(moduleName);
|
|
94
|
+
} catch (error) {
|
|
95
|
+
logger.error(`[Bootstrap] Failed to load module: ${moduleName}`, { error });
|
|
96
|
+
}
|
|
97
|
+
logger.info("[Bootstrap] Modules loaded", { loaded: loadedModules });
|
|
98
|
+
return loadedModules;
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Setup health checks
|
|
102
|
+
*/
|
|
103
|
+
async setupHealthChecks() {
|
|
104
|
+
logger.info("[Bootstrap] Setting up health checks");
|
|
105
|
+
const interval = this.config.healthCheckInterval || 3e4;
|
|
106
|
+
this.healthCheckInterval = setInterval(() => {
|
|
107
|
+
(async () => {
|
|
108
|
+
const health = await this.performHealthCheck();
|
|
109
|
+
if (!health.healthy) logger.warn("[Bootstrap] Health check failed", health);
|
|
110
|
+
else logger.debug("[Bootstrap] Health check passed", health);
|
|
111
|
+
})();
|
|
112
|
+
}, interval);
|
|
113
|
+
logger.info("[Bootstrap] Health checks configured", { interval });
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Perform health check
|
|
117
|
+
*/
|
|
118
|
+
async performHealthCheck() {
|
|
119
|
+
const checks = {};
|
|
120
|
+
const memUsage = process.memoryUsage();
|
|
121
|
+
checks.memory = {
|
|
122
|
+
used: memUsage.heapUsed,
|
|
123
|
+
total: memUsage.heapTotal,
|
|
124
|
+
percentage: memUsage.heapUsed / memUsage.heapTotal * 100
|
|
125
|
+
};
|
|
126
|
+
checks.uptime = Math.floor((Date.now() - this.startTime.getTime()) / 1e3);
|
|
127
|
+
return {
|
|
128
|
+
healthy: checks.memory.percentage < 90 && checks.uptime > 0,
|
|
129
|
+
checks,
|
|
130
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Setup signal handlers for graceful shutdown
|
|
135
|
+
*/
|
|
136
|
+
setupSignalHandlers() {
|
|
137
|
+
logger.debug("[Bootstrap] Setting up signal handlers");
|
|
138
|
+
const gracefulShutdown = async (signal) => {
|
|
139
|
+
logger.info(`[Bootstrap] Received ${signal}, shutting down gracefully`);
|
|
140
|
+
if (this.healthCheckInterval) clearInterval(this.healthCheckInterval);
|
|
141
|
+
await this.cleanup();
|
|
142
|
+
process.exit(0);
|
|
143
|
+
};
|
|
144
|
+
process.on("SIGTERM", () => {
|
|
145
|
+
gracefulShutdown("SIGTERM");
|
|
146
|
+
});
|
|
147
|
+
process.on("SIGINT", () => {
|
|
148
|
+
gracefulShutdown("SIGINT");
|
|
149
|
+
});
|
|
150
|
+
process.on("unhandledRejection", (reason, promise) => {
|
|
151
|
+
logger.error("[Bootstrap] Unhandled rejection", {
|
|
152
|
+
reason,
|
|
153
|
+
promise
|
|
154
|
+
});
|
|
155
|
+
});
|
|
156
|
+
process.on("uncaughtException", (error) => {
|
|
157
|
+
logger.error("[Bootstrap] Uncaught exception", { error });
|
|
158
|
+
process.exit(1);
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* Cleanup on shutdown
|
|
163
|
+
*/
|
|
164
|
+
async cleanup() {
|
|
165
|
+
logger.info("[Bootstrap] Performing cleanup");
|
|
166
|
+
await disposeAll();
|
|
167
|
+
ContextManager.clearContext();
|
|
168
|
+
logger.info("[Bootstrap] Cleanup completed");
|
|
169
|
+
}
|
|
170
|
+
/**
|
|
171
|
+
* Get application info
|
|
172
|
+
*/
|
|
173
|
+
getInfo() {
|
|
174
|
+
return {
|
|
175
|
+
serviceName: this.config.serviceName || "burdenoff-service",
|
|
176
|
+
serviceVersion: this.config.serviceVersion || "1.0.0",
|
|
177
|
+
environment: this.config.environment || "development",
|
|
178
|
+
uptime: Math.floor((Date.now() - this.startTime.getTime()) / 1e3),
|
|
179
|
+
startedAt: this.startTime.toISOString()
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* Setup default context
|
|
184
|
+
*/
|
|
185
|
+
setupDefaultContext(context) {
|
|
186
|
+
logger.debug("[Bootstrap] Setting up default context", context);
|
|
187
|
+
ContextManager.setContext(context);
|
|
188
|
+
}
|
|
189
|
+
/**
|
|
190
|
+
* Create context middleware (for Elysia/HTTP frameworks)
|
|
191
|
+
*/
|
|
192
|
+
createContextMiddleware() {
|
|
193
|
+
return async (req, _res, next) => {
|
|
194
|
+
const context = this.extractContextFromRequest(req);
|
|
195
|
+
ContextManager.setContext(context);
|
|
196
|
+
next();
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
/**
|
|
200
|
+
* Extract context from request
|
|
201
|
+
*/
|
|
202
|
+
extractContextFromRequest(req) {
|
|
203
|
+
const context = {};
|
|
204
|
+
if (req.user) {
|
|
205
|
+
context.actorId = req.user.user_id;
|
|
206
|
+
context.workspaceId = req.user.workspace_id;
|
|
207
|
+
context.tenantId = req.user.tenant_endpoint;
|
|
208
|
+
}
|
|
209
|
+
const getHeader = (key) => {
|
|
210
|
+
const value = req.headers[key.toLowerCase()];
|
|
211
|
+
return Array.isArray(value) ? value[0] : value;
|
|
212
|
+
};
|
|
213
|
+
const authHeader = getHeader("authorization");
|
|
214
|
+
if (authHeader) context.token = authHeader.replace("Bearer ", "");
|
|
215
|
+
const workspaceId = getHeader("x-workspace-id");
|
|
216
|
+
if (workspaceId && !context.workspaceId) context.workspaceId = workspaceId;
|
|
217
|
+
const productId = getHeader("x-product-id");
|
|
218
|
+
if (productId) context.productId = productId;
|
|
219
|
+
const projectId = getHeader("x-project-id");
|
|
220
|
+
if (projectId) context.projectId = projectId;
|
|
221
|
+
const appId = getHeader("x-app-id");
|
|
222
|
+
if (appId) context.appId = appId;
|
|
223
|
+
const cfAccessClientId = getHeader("cf-access-client-id");
|
|
224
|
+
if (cfAccessClientId) context.cfAccessClientId = cfAccessClientId;
|
|
225
|
+
const cfAccessClientSecret = getHeader("cf-access-client-secret");
|
|
226
|
+
if (cfAccessClientSecret) context.cfAccessClientSecret = cfAccessClientSecret;
|
|
227
|
+
const cfAuthorization = getHeader("x-cf-authorization");
|
|
228
|
+
if (cfAuthorization) context.cfAuthorization = cfAuthorization;
|
|
229
|
+
return context;
|
|
230
|
+
}
|
|
231
|
+
/**
|
|
232
|
+
* Load GraphQL schema
|
|
233
|
+
*/
|
|
234
|
+
async loadSchema(schemaPath) {
|
|
235
|
+
logger.info("[Bootstrap] Loading GraphQL schema", { schemaPath });
|
|
236
|
+
try {
|
|
237
|
+
logger.info("[Bootstrap] Schema loaded successfully");
|
|
238
|
+
return true;
|
|
239
|
+
} catch (error) {
|
|
240
|
+
logger.error("[Bootstrap] Failed to load schema", { error });
|
|
241
|
+
return false;
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
/**
|
|
245
|
+
* Register shutdown hook
|
|
246
|
+
*/
|
|
247
|
+
onShutdown(callback) {
|
|
248
|
+
const originalHandler = process.listeners("SIGTERM")[0];
|
|
249
|
+
process.removeAllListeners("SIGTERM");
|
|
250
|
+
process.on("SIGTERM", () => {
|
|
251
|
+
(async () => {
|
|
252
|
+
await callback();
|
|
253
|
+
if (typeof originalHandler === "function") originalHandler();
|
|
254
|
+
})();
|
|
255
|
+
});
|
|
256
|
+
}
|
|
257
|
+
/**
|
|
258
|
+
* Check if application is ready
|
|
259
|
+
*/
|
|
260
|
+
async isReady() {
|
|
261
|
+
return (await this.performHealthCheck()).healthy;
|
|
262
|
+
}
|
|
263
|
+
/**
|
|
264
|
+
* Get metrics
|
|
265
|
+
*/
|
|
266
|
+
getMetrics() {
|
|
267
|
+
return {
|
|
268
|
+
memory: process.memoryUsage(),
|
|
269
|
+
uptime: Math.floor((Date.now() - this.startTime.getTime()) / 1e3),
|
|
270
|
+
cpu: process.cpuUsage()
|
|
271
|
+
};
|
|
272
|
+
}
|
|
273
|
+
};
|
|
274
|
+
/**
|
|
275
|
+
* Create bootstrap instance
|
|
276
|
+
*/
|
|
277
|
+
function createBootstrap(config) {
|
|
278
|
+
return new BootstrapModule(config);
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
export { BootstrapModule, createBootstrap };
|
|
282
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../src/bootstrap/index.ts"],"sourcesContent":["/**\n * Bootstrap Module\n * Helpers for bootstrapping server, loading modules, and setting up schemas\n */\n\nimport { logger } from '../logger/index.js';\nimport { DatabaseModule, type DatabaseConfig } from '../database/index.js';\nimport { ContextManager } from '../context/index.js';\nimport { disposeAll } from '../lifecycle/index.js';\nimport type { SDKConfig, SDKContext } from '../types/index.js';\n\n/**\n * Type for HTTP header values\n */\ntype HeaderValue = string | string[] | undefined;\n\nexport interface BootstrapConfig extends SDKConfig {\n /** Database configuration */\n database?: DatabaseConfig;\n /** Enable health checks */\n healthCheck?: boolean;\n /** Health check interval in milliseconds */\n healthCheckInterval?: number;\n /** Modules to load */\n modules?: string[];\n /** Environment */\n environment?: 'development' | 'staging' | 'production';\n /** Service name */\n serviceName?: string;\n /** Service version */\n serviceVersion?: string;\n /** Port to run health check server */\n healthCheckPort?: number;\n}\n\nexport interface BootstrapResult {\n success: boolean;\n serviceName: string;\n serviceVersion: string;\n environment: string;\n startedAt: string;\n modules: string[];\n databaseConnected: boolean;\n healthCheckEnabled: boolean;\n}\n\nexport interface BootstrapHealthCheckResult {\n healthy: boolean;\n checks: {\n database?: boolean;\n graphql?: boolean;\n memory?: {\n used: number;\n total: number;\n percentage: number;\n };\n uptime?: number;\n };\n timestamp: string;\n}\n\n/**\n * Bootstrap Module\n */\nexport class BootstrapModule {\n private config: BootstrapConfig;\n private startTime: Date;\n private healthCheckInterval?: NodeJS.Timeout;\n\n constructor(config: BootstrapConfig) {\n this.config = config;\n this.startTime = new Date();\n }\n\n /**\n * Bootstrap the application\n */\n public async bootstrap(): Promise<BootstrapResult> {\n logger.info('[Bootstrap] Starting application bootstrap', {\n serviceName: this.config.serviceName,\n environment: this.config.environment || 'development',\n });\n\n try {\n // 1. Validate configuration\n await this.validateConfiguration();\n\n // 2. Connect to database\n const databaseConnected = await this.connectDatabase();\n\n // 3. Load modules\n const loadedModules = await this.loadModules();\n\n // 4. Setup health checks\n if (this.config.healthCheck) {\n await this.setupHealthChecks();\n }\n\n // 5. Setup signal handlers\n this.setupSignalHandlers();\n\n const result: BootstrapResult = {\n success: true,\n serviceName: this.config.serviceName || 'burdenoff-service',\n serviceVersion: this.config.serviceVersion || '1.0.0',\n environment: this.config.environment || 'development',\n startedAt: this.startTime.toISOString(),\n modules: loadedModules,\n databaseConnected,\n healthCheckEnabled: this.config.healthCheck || false,\n };\n\n logger.info('[Bootstrap] Application bootstrapped successfully', result);\n\n return result;\n } catch (error) {\n logger.error('[Bootstrap] Failed to bootstrap application', { error });\n throw error;\n }\n }\n\n /**\n * Validate configuration\n */\n private async validateConfiguration(): Promise<void> {\n logger.debug('[Bootstrap] Validating configuration');\n\n if (!this.config.workspacesApiUrl) {\n throw new Error('Workspaces API URL is required');\n }\n\n if (this.config.database?.url && !DatabaseModule.validateDatabaseUrl(this.config.database.url)) {\n throw new Error('Invalid database URL');\n }\n\n logger.debug('[Bootstrap] Configuration validated');\n }\n\n /**\n * Connect to database\n */\n private async connectDatabase(): Promise<boolean> {\n if (!this.config.database) {\n logger.debug('[Bootstrap] No database configuration provided, skipping');\n return false;\n }\n\n logger.info('[Bootstrap] Connecting to database');\n\n try {\n // Database connection is typically handled by Prisma or other ORM\n // This is a placeholder for validation and logging\n const sanitizedUrl = DatabaseModule.sanitizeDatabaseUrl(this.config.database.url);\n logger.info('[Bootstrap] Database connection configured', { url: sanitizedUrl });\n\n return true;\n } catch (error) {\n logger.error('[Bootstrap] Failed to connect to database', { error });\n return false;\n }\n }\n\n /**\n * Load modules\n */\n private async loadModules(): Promise<string[]> {\n const modules = this.config.modules || [];\n\n if (modules.length === 0) {\n logger.debug('[Bootstrap] No modules to load');\n return [];\n }\n\n logger.info('[Bootstrap] Loading modules', { modules });\n\n const loadedModules: string[] = [];\n\n for (const moduleName of modules) {\n try {\n logger.debug(`[Bootstrap] Loading module: ${moduleName}`);\n // Module loading logic would go here\n loadedModules.push(moduleName);\n } catch (error) {\n logger.error(`[Bootstrap] Failed to load module: ${moduleName}`, { error });\n }\n }\n\n logger.info('[Bootstrap] Modules loaded', { loaded: loadedModules });\n\n return loadedModules;\n }\n\n /**\n * Setup health checks\n */\n private async setupHealthChecks(): Promise<void> {\n logger.info('[Bootstrap] Setting up health checks');\n\n const interval = this.config.healthCheckInterval || 30000; // 30 seconds\n\n this.healthCheckInterval = setInterval(() => {\n void (async () => {\n const health = await this.performHealthCheck();\n\n if (!health.healthy) {\n logger.warn('[Bootstrap] Health check failed', health);\n } else {\n logger.debug('[Bootstrap] Health check passed', health);\n }\n })();\n }, interval);\n\n logger.info('[Bootstrap] Health checks configured', { interval });\n }\n\n /**\n * Perform health check\n */\n public async performHealthCheck(): Promise<BootstrapHealthCheckResult> {\n const checks: BootstrapHealthCheckResult['checks'] = {};\n\n // Memory check\n const memUsage = process.memoryUsage();\n checks.memory = {\n used: memUsage.heapUsed,\n total: memUsage.heapTotal,\n percentage: (memUsage.heapUsed / memUsage.heapTotal) * 100,\n };\n\n // Uptime\n checks.uptime = Math.floor((Date.now() - this.startTime.getTime()) / 1000);\n\n // Determine overall health\n const healthy =\n checks.memory.percentage < 90 && // Less than 90% memory usage\n checks.uptime > 0;\n\n return {\n healthy,\n checks,\n timestamp: new Date().toISOString(),\n };\n }\n\n /**\n * Setup signal handlers for graceful shutdown\n */\n private setupSignalHandlers(): void {\n logger.debug('[Bootstrap] Setting up signal handlers');\n\n const gracefulShutdown = async (signal: string): Promise<void> => {\n logger.info(`[Bootstrap] Received ${signal}, shutting down gracefully`);\n\n // Clear health check interval\n if (this.healthCheckInterval) {\n clearInterval(this.healthCheckInterval);\n }\n\n // Perform cleanup\n await this.cleanup();\n\n process.exit(0);\n };\n\n process.on('SIGTERM', () => {\n void gracefulShutdown('SIGTERM');\n });\n process.on('SIGINT', () => {\n void gracefulShutdown('SIGINT');\n });\n\n process.on('unhandledRejection', (reason, promise) => {\n logger.error('[Bootstrap] Unhandled rejection', {\n reason,\n promise,\n });\n });\n\n process.on('uncaughtException', (error) => {\n logger.error('[Bootstrap] Uncaught exception', { error });\n process.exit(1);\n });\n }\n\n /**\n * Cleanup on shutdown\n */\n private async cleanup(): Promise<void> {\n logger.info('[Bootstrap] Performing cleanup');\n\n // Gracefully close every registered long-lived connection (Redis Streams\n // event publisher/consumer, cache client) so their sockets are torn down\n // deterministically here instead of being left for the OS at process exit.\n // Bounded per-connection so a hung close never blocks the exit. Never throws.\n await disposeAll();\n\n // Clear context\n ContextManager.clearContext();\n\n logger.info('[Bootstrap] Cleanup completed');\n }\n\n /**\n * Get application info\n */\n public getInfo(): {\n serviceName: string;\n serviceVersion: string;\n environment: string;\n uptime: number;\n startedAt: string;\n } {\n return {\n serviceName: this.config.serviceName || 'burdenoff-service',\n serviceVersion: this.config.serviceVersion || '1.0.0',\n environment: this.config.environment || 'development',\n uptime: Math.floor((Date.now() - this.startTime.getTime()) / 1000),\n startedAt: this.startTime.toISOString(),\n };\n }\n\n /**\n * Setup default context\n */\n public setupDefaultContext(context: SDKContext): void {\n logger.debug('[Bootstrap] Setting up default context', context);\n ContextManager.setContext(context);\n }\n\n /**\n * Create context middleware (for Elysia/HTTP frameworks)\n */\n public createContextMiddleware() {\n return async (\n req: { headers: Record<string, HeaderValue>; user?: unknown },\n _res: unknown,\n next: () => void\n ): Promise<void> => {\n const context = this.extractContextFromRequest(\n req as {\n headers: Record<string, HeaderValue>;\n user?: { user_id?: string; workspace_id?: string; org_id?: string; tenant_endpoint?: string };\n }\n );\n ContextManager.setContext(context);\n next();\n };\n }\n\n /**\n * Extract context from request\n */\n private extractContextFromRequest(req: {\n headers: Record<string, string | string[] | undefined>;\n user?: { user_id?: string; workspace_id?: string; org_id?: string; tenant_endpoint?: string };\n }): SDKContext {\n const context: SDKContext = {};\n\n // Extract from user object (if JWT already verified)\n if (req.user) {\n context.actorId = req.user.user_id;\n context.workspaceId = req.user.workspace_id;\n context.tenantId = req.user.tenant_endpoint;\n }\n\n // Extract from headers\n const getHeader = (key: string): string | undefined => {\n const value = req.headers[key.toLowerCase()];\n return Array.isArray(value) ? value[0] : value;\n };\n\n const authHeader = getHeader('authorization');\n if (authHeader) {\n context.token = authHeader.replace('Bearer ', '');\n }\n\n const workspaceId = getHeader('x-workspace-id');\n if (workspaceId && !context.workspaceId) {\n context.workspaceId = workspaceId;\n }\n\n const productId = getHeader('x-product-id');\n if (productId) {\n context.productId = productId;\n }\n\n const projectId = getHeader('x-project-id');\n if (projectId) {\n context.projectId = projectId;\n }\n\n const appId = getHeader('x-app-id');\n if (appId) {\n context.appId = appId;\n }\n\n // Cloudflare Access service token — captured so cross-layer calls can\n // re-present it on alpha (see ContextManager.getCfAccessHeaders). Kept in\n // sync with the canonical extractor in `src/context/index.ts`. Setting it\n // via ContextManager.setContext (see createContextMiddleware) also mirrors\n // it to the module-level fallback for Bun + Yoga.\n const cfAccessClientId = getHeader('cf-access-client-id');\n if (cfAccessClientId) {\n context.cfAccessClientId = cfAccessClientId;\n }\n\n const cfAccessClientSecret = getHeader('cf-access-client-secret');\n if (cfAccessClientSecret) {\n context.cfAccessClientSecret = cfAccessClientSecret;\n }\n\n // Cloudflare Access user-SSO cookie, forwarded by the public gateway as\n // x-cf-authorization. Re-presented as the CF_Authorization cookie on\n // cross-layer calls (see ContextManager.getCfAccessHeaders). See BOFF-2929.\n const cfAuthorization = getHeader('x-cf-authorization');\n if (cfAuthorization) {\n context.cfAuthorization = cfAuthorization;\n }\n\n return context;\n }\n\n /**\n * Load GraphQL schema\n */\n public async loadSchema(schemaPath: string): Promise<boolean> {\n logger.info('[Bootstrap] Loading GraphQL schema', { schemaPath });\n\n try {\n // Schema loading logic would go here\n // This is typically handled by the GraphQL server setup\n logger.info('[Bootstrap] Schema loaded successfully');\n return true;\n } catch (error) {\n logger.error('[Bootstrap] Failed to load schema', { error });\n return false;\n }\n }\n\n /**\n * Register shutdown hook\n */\n public onShutdown(callback: () => Promise<void> | void): void {\n const originalHandler = process.listeners('SIGTERM')[0] as (() => void) | undefined;\n\n process.removeAllListeners('SIGTERM');\n process.on('SIGTERM', () => {\n void (async () => {\n await callback();\n if (typeof originalHandler === 'function') {\n originalHandler();\n }\n })();\n });\n }\n\n /**\n * Check if application is ready\n */\n public async isReady(): Promise<boolean> {\n const health = await this.performHealthCheck();\n return health.healthy;\n }\n\n /**\n * Get metrics\n */\n public getMetrics(): {\n memory: NodeJS.MemoryUsage;\n uptime: number;\n cpu: NodeJS.CpuUsage;\n } {\n return {\n memory: process.memoryUsage(),\n uptime: Math.floor((Date.now() - this.startTime.getTime()) / 1000),\n cpu: process.cpuUsage(),\n };\n }\n}\n\n/**\n * Create bootstrap instance\n */\nexport function createBootstrap(config: BootstrapConfig): BootstrapModule {\n return new BootstrapModule(config);\n}\n"],"mappings":";;;;;;;;;;;;;AAgEA,IAAa,kBAAb,MAA6B;CAC3B,AAAQ;CACR,AAAQ;CACR,AAAQ;CAER,YAAY,QAAyB;EACnC,KAAK,SAAS;EACd,KAAK,4BAAY,IAAI,KAAK;CAC5B;;;;CAKA,MAAa,YAAsC;EACjD,OAAO,KAAK,8CAA8C;GACxD,aAAa,KAAK,OAAO;GACzB,aAAa,KAAK,OAAO,eAAe;EAC1C,CAAC;EAED,IAAI;GAEF,MAAM,KAAK,sBAAsB;GAGjC,MAAM,oBAAoB,MAAM,KAAK,gBAAgB;GAGrD,MAAM,gBAAgB,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OAAO,KAAK,IAAI,IAAI,KAAK,UAAU,QAAQ,KAAK,GAAI;GACjE,KAAK,QAAQ,SAAS;EACxB;CACF;AACF;;;;AAKA,SAAgB,gBAAgB,QAA0C;CACxE,OAAO,IAAI,gBAAgB,MAAM;AACnC"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { t as __exportAll } from "./rolldown-runtime-ad2WFvuA.js";
|
|
2
|
-
import {
|
|
2
|
+
import { ContextManager } from "./context/index.js";
|
|
3
3
|
import { t as LayerManager } from "./layer-CEKy6cm8.js";
|
|
4
4
|
import { a as logger } from "./logger-B6rCpb7D.js";
|
|
5
5
|
import { t as signServiceJwt } from "./service-jwt-Bu-WNA_-.js";
|
|
@@ -562,4 +562,4 @@ function createGatewayClientFromEnv() {
|
|
|
562
562
|
}
|
|
563
563
|
|
|
564
564
|
export { isGatewayClientError as a, createGatewayClientFromEnv as i, client_exports as n, createGatewayClient as r, GatewayClient as t };
|
|
565
|
-
//# sourceMappingURL=client-
|
|
565
|
+
//# sourceMappingURL=client-sAJTrb4i.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client-DcZ3iGES.js","names":[],"sources":["../src/gateway/service-jwt-guard.ts","../src/gateway/client.ts"],"sourcesContent":["/**\n * Cross-layer service-JWT configuration guard.\n *\n * A cross-layer call transits the peer layer's PUBLIC gateway, which propagates\n * `x-actor-*` context to subgraphs only when the request carries a valid JWT.\n * Without one the gateway strips those headers as potential client spoofing and\n * the subgraph rejects the call. So on a cross-layer request with no\n * Authorization header and no mintable service JWT, the outcome is already\n * decided before the request leaves the process: it will fail, downstream, with\n * an authentication error that names the callee rather than the missing secret.\n *\n * That is a bad trade in a deployed environment. It converts a one-line config\n * problem into an opaque failure attributed to the wrong service, and — because\n * several cross-layer callers treat these calls as best-effort and swallow the\n * error — into no visible failure at all. Alpha ran exactly that way: 414 calls\n * in 24h on `AddWorkspaceMemberFromWspace` and `WorkspaceOrganization`, every\n * one rejected, workspace-member mirroring silently not happening, and nothing\n * in the caller's logs above debug level.\n *\n * So in alpha, staging and production this throws before the request is sent,\n * naming the secret and the bundle to fix. Locally it stays a log: a laptop\n * calling across layers without a service JWT is a normal state while a\n * developer is mid-setup, and failing their `bun run dev` would be hostile.\n *\n * Verified inert before shipping, the same way the cache guard was: of the\n * alpha and prod service bundles in Secrets Manager, every be-sdk service that\n * makes cross-layer calls already carries `SERVICE_JWT_SECRET` (166 bundles).\n * The bundles without it are Temporal, OPA, the OTel collectors, NATS, Gatus,\n * the vibetunnels pair, the ai-assistant trio, the dormant `*-community`\n * deployments and the retired `state-archive-*` configs — none of which\n * constructs a GatewayClient or makes a cross-layer call. Nothing changes\n * today; this only catches the next caller rolled out without the secret.\n */\nimport { isDeployedEnvironment, currentEnvironment } from '../runtime/deployed-environment.js';\n\n/** Env var that must hold the signing key for service-actor JWTs. */\nexport const SERVICE_JWT_SECRET_ENV = 'SERVICE_JWT_SECRET';\n\nexport interface ServiceJwtGuardContext {\n /** Absolute URL of the peer gateway the call was about to be sent to. */\n gatewayUrl: string;\n /** GraphQL operation name, when the caller supplied one. */\n operationName?: string;\n /** Layer boundary of the CALLER, used to name the bundle to fix. */\n layer?: string;\n /** Service identity the JWT would have been minted for. */\n serviceIdentity?: string;\n}\n\n/**\n * Build the operator-facing explanation. Exported so the message itself is\n * covered by tests — a guard whose text does not say what to change just moves\n * the debugging, it does not remove it.\n */\nexport function serviceJwtMisconfigurationMessage(context: ServiceJwtGuardContext): string {\n const environment = currentEnvironment() || 'unset';\n const layer = context.layer ?? '{layer}';\n const operation = context.operationName ? ` (operation ${context.operationName})` : '';\n const identity = context.serviceIdentity ? ` as '${context.serviceIdentity}'` : '';\n return (\n `[GatewayClient] Cross-layer call to ${context.gatewayUrl}${operation} cannot be authenticated${identity}: ` +\n `${SERVICE_JWT_SECRET_ENV} is not set, so no service JWT can be minted. The peer layer's public ` +\n `gateway will strip actor headers and the subgraph will reject the request, so this call cannot ` +\n `succeed. Refusing to send it with DEPLOY_ENV=${environment}. Set ${SERVICE_JWT_SECRET_ENV} in ` +\n `boff/${environment}/${layer}/{module} — it must match the value the peer layer's gateway ` +\n `verifies with, which is per-environment and must never be copied across environments.`\n );\n}\n\n/**\n * Throw in a deployed environment when a cross-layer call is about to be sent\n * with no way to authenticate it. Returns normally everywhere else, and\n * whenever a JWT was available — so this costs nothing on the happy path.\n */\nexport function assertServiceJwtConfigured(context: ServiceJwtGuardContext): void {\n if (!isDeployedEnvironment()) return;\n throw new Error(serviceJwtMisconfigurationMessage(context));\n}\n","/**\n * Unified Gateway Client\n *\n * Provides a layer-aware GraphQL client with circuit breaker,\n * retry logic, and automatic header management for M2M communication.\n *\n * @module gateway/client\n * @category Gateway\n *\n * @example\n * ```typescript\n * import { GatewayClient } from '@burdenoff/be-sdk/gateway';\n *\n * const client = new GatewayClient({\n * layer: 'wspace',\n * serviceName: 'wspace-tags-svc',\n * });\n *\n * // Internal call (same layer)\n * const result = await client.internalQuery({\n * query: `query { getTag(id: \"123\") { id name } }`,\n * });\n *\n * // Cross-layer call\n * const authResult = await client.crossLayerQuery({\n * query: `query { getCurrentUser { id email } }`,\n * });\n * ```\n */\n\nimport { ContextManager } from '../context/index.js';\nimport { LayerManager } from '../layer/index.js';\nimport { logger } from '../logger/index.js';\nimport { signServiceJwt } from './service-jwt.js';\nimport { assertServiceJwtConfigured } from './service-jwt-guard.js';\nimport {\n DEFAULT_CIRCUIT_BREAKER_CONFIG,\n DEFAULT_GATEWAY_RETRY_CONFIG,\n type CircuitBreakerConfig,\n type GatewayRequestHeaders,\n type GatewayRetryConfig,\n type ServiceLayer,\n} from '../types/layer.js';\nimport {\n CircuitState,\n GatewayError,\n GatewayErrorType,\n type CircuitBreakerStats,\n type GatewayClientConfig,\n type GatewayClientHealth,\n type GraphQLError,\n type GraphQLRequestOptions,\n type GraphQLResponse,\n type ICircuitBreaker,\n type IGatewayClient,\n type RequestContext,\n} from './types.js';\n\nconst uuidv4 = (): string => crypto.randomUUID();\n\n/**\n * Case-insensitive presence check for the `Authorization` header. HTTP header\n * names are case-insensitive (RFC 7230), and while the outbound `fetch` will\n * preserve whatever casing the caller supplies, callers may legitimately set\n * `authorization` / `Authorization` / even `AUTHORIZATION` via defaultHeaders\n * or options.headers. We must not overwrite an already-supplied token.\n */\nfunction hasAuthorizationHeader(headers: Record<string, string>): boolean {\n for (const key of Object.keys(headers)) {\n if (key.toLowerCase() === 'authorization') return true;\n }\n return false;\n}\n\nfunction isGraphQLError(value: unknown): value is GraphQLError {\n return (\n value !== null &&\n typeof value === 'object' &&\n 'message' in value &&\n typeof value.message === 'string' &&\n (!('extensions' in value) ||\n (value.extensions !== null && typeof value.extensions === 'object' && !Array.isArray(value.extensions)))\n );\n}\n\n/**\n * HTTP statuses in the 4xx range that describe a transient condition rather than\n * a problem with the request itself: the request timed out at the peer (408) or\n * the peer is shedding load (429 without a GraphQL body, i.e. an edge or proxy\n * limit). Those stay retryable and still count toward the circuit breaker.\n */\nconst TRANSIENT_CLIENT_STATUSES: ReadonlySet<number> = new Set([408, 429]);\n\n/**\n * Is this failure a definitive answer about the request rather than a sign that\n * the gateway or the transport is unhealthy?\n *\n * True for:\n * - `GRAPHQL_ERROR`: the gateway executed the operation and answered with\n * GraphQL errors (for example `NOT_FOUND`, `BAD_USER_INPUT`, `FORBIDDEN`),\n * whether that arrived with HTTP 200 or with a 4xx status;\n * - an HTTP 4xx without a GraphQL body (for example an edge 403 or 404), except\n * the transient statuses 408 and 429.\n *\n * Such failures are never retried (the same request gets the same answer) and\n * are not counted toward the circuit breaker: a burst of legitimate \"not found\"\n * lookups must not open the circuit for every other call the service makes.\n *\n * @param error - Anything thrown by a GatewayClient call\n * @returns Whether the error is a client error in the sense above\n */\nexport function isGatewayClientError(error: unknown): boolean {\n if (!(error instanceof GatewayError)) return false;\n if (error.type === GatewayErrorType.GRAPHQL_ERROR) return true;\n if (error.type !== GatewayErrorType.NETWORK_ERROR || error.statusCode === undefined) return false;\n return error.statusCode >= 400 && error.statusCode < 500 && !TRANSIENT_CLIENT_STATUSES.has(error.statusCode);\n}\n\nexport function resolveBypassPermissionValue(\n token: string | undefined = process.env['INTERNAL_SERVICE_TOKEN']\n): string {\n const normalizedToken = token?.trim();\n\n if (!normalizedToken) {\n throw new Error('INTERNAL_SERVICE_TOKEN must be configured for bypass-enabled gateway calls');\n }\n\n return normalizedToken;\n}\n\n/**\n * Circuit Breaker Implementation\n */\nclass CircuitBreaker implements ICircuitBreaker {\n private state: CircuitState = CircuitState.CLOSED;\n private failures = 0;\n private successes = 0;\n private consecutiveFailures = 0;\n private lastFailureTime: number | null = null;\n private lastSuccessTime: number | null = null;\n private openedAt: number | null = null;\n private failureTimestamps: number[] = [];\n private config: CircuitBreakerConfig;\n\n constructor(config: CircuitBreakerConfig) {\n this.config = config;\n }\n\n getState(): CircuitState {\n this.checkStateTransition();\n return this.state;\n }\n\n recordSuccess(): void {\n this.successes++;\n this.consecutiveFailures = 0;\n this.lastSuccessTime = Date.now();\n\n if (this.state === CircuitState.HALF_OPEN) {\n this.state = CircuitState.CLOSED;\n this.failures = 0;\n this.failureTimestamps = [];\n this.openedAt = null;\n logger.info('[CircuitBreaker] Circuit closed after successful test');\n }\n }\n\n recordFailure(): void {\n this.failures++;\n this.consecutiveFailures++;\n this.lastFailureTime = Date.now();\n this.failureTimestamps.push(Date.now());\n\n // Clean up old timestamps\n const windowStart = Date.now() - this.config.failureWindow;\n this.failureTimestamps = this.failureTimestamps.filter((t) => t > windowStart);\n\n // Check if we should open the circuit\n if (this.state === CircuitState.CLOSED && this.failureTimestamps.length >= this.config.failureThreshold) {\n this.state = CircuitState.OPEN;\n this.openedAt = Date.now();\n logger.warn('[CircuitBreaker] Circuit opened due to failures', {\n failures: this.failureTimestamps.length,\n threshold: this.config.failureThreshold,\n });\n }\n\n // If we're half-open and fail, go back to open\n if (this.state === CircuitState.HALF_OPEN) {\n this.state = CircuitState.OPEN;\n this.openedAt = Date.now();\n logger.warn('[CircuitBreaker] Circuit re-opened after failed test');\n }\n }\n\n allowRequest(): boolean {\n this.checkStateTransition();\n\n switch (this.state) {\n case CircuitState.CLOSED:\n return true;\n case CircuitState.OPEN:\n return false;\n case CircuitState.HALF_OPEN:\n // Allow one test request\n return true;\n default:\n return true;\n }\n }\n\n forceOpen(): void {\n this.state = CircuitState.OPEN;\n this.openedAt = Date.now();\n logger.info('[CircuitBreaker] Circuit force-opened');\n }\n\n forceClose(): void {\n this.state = CircuitState.CLOSED;\n this.failures = 0;\n this.consecutiveFailures = 0;\n this.failureTimestamps = [];\n this.openedAt = null;\n logger.info('[CircuitBreaker] Circuit force-closed');\n }\n\n getStats(): CircuitBreakerStats {\n return {\n state: this.state,\n failures: this.failures,\n successes: this.successes,\n consecutiveFailures: this.consecutiveFailures,\n lastFailureTime: this.lastFailureTime,\n lastSuccessTime: this.lastSuccessTime,\n openedAt: this.openedAt,\n };\n }\n\n private checkStateTransition(): void {\n if (this.state === CircuitState.OPEN && this.openedAt) {\n const elapsed = Date.now() - this.openedAt;\n if (elapsed >= this.config.resetTimeout) {\n this.state = CircuitState.HALF_OPEN;\n logger.info('[CircuitBreaker] Circuit transitioning to half-open');\n }\n }\n }\n}\n\n/**\n * Unified Gateway Client\n */\nexport class GatewayClient implements IGatewayClient {\n private config: GatewayClientConfig;\n private layerManager: LayerManager;\n private internalCircuitBreaker: CircuitBreaker;\n private crossLayerCircuitBreaker: CircuitBreaker;\n private retryConfig: GatewayRetryConfig;\n private defaultHeaders: GatewayRequestHeaders;\n\n constructor(config: GatewayClientConfig) {\n this.config = {\n timeout: 30000,\n enableLogging: true,\n ...config,\n };\n\n // Initialize layer manager\n this.layerManager = new LayerManager({\n layer: config.layer,\n serviceName: config.serviceName,\n serviceIdentity: config.serviceIdentity,\n });\n\n // Override URLs if provided\n if (config.internalGatewayUrl) {\n // Use getter internally, but we'll store the override\n }\n if (config.crossLayerGatewayUrl) {\n // Use getter internally, but we'll store the override\n }\n\n // Initialize circuit breakers\n const cbConfig: CircuitBreakerConfig = {\n ...DEFAULT_CIRCUIT_BREAKER_CONFIG,\n ...config.circuitBreaker,\n };\n this.internalCircuitBreaker = new CircuitBreaker(cbConfig);\n this.crossLayerCircuitBreaker = new CircuitBreaker(cbConfig);\n\n // Initialize retry config\n this.retryConfig = {\n ...DEFAULT_GATEWAY_RETRY_CONFIG,\n ...config.retry,\n };\n\n // Initialize default headers\n this.defaultHeaders = {\n 'x-service-identity': this.layerManager.getServiceIdentity(),\n 'x-actor-type': 'service',\n ...config.defaultHeaders,\n };\n\n logger.debug('[GatewayClient] Initialized', {\n layer: config.layer,\n serviceName: config.serviceName,\n internalUrl: this.getInternalUrl(),\n crossLayerUrl: this.getCrossLayerUrl(),\n });\n }\n\n private getInternalUrl(): string {\n return this.config.internalGatewayUrl || this.layerManager.getInternalGatewayUrl();\n }\n\n private getCrossLayerUrl(): string {\n return this.config.crossLayerGatewayUrl || this.layerManager.getCrossLayerGatewayUrl();\n }\n\n /**\n * Execute internal (same layer) GraphQL query/mutation\n */\n async internalQuery<T = unknown>(options: GraphQLRequestOptions): Promise<GraphQLResponse<T>> {\n const context = this.createRequestContext('internal', options);\n\n return this.executeWithRetry(this.getInternalUrl(), options, this.internalCircuitBreaker, context, {\n bypassPermission: true,\n });\n }\n\n /**\n * Execute cross-layer GraphQL query/mutation\n */\n async crossLayerQuery<T = unknown>(options: GraphQLRequestOptions): Promise<GraphQLResponse<T>> {\n const context = this.createRequestContext('cross-layer', options);\n\n return this.executeWithRetry(\n this.getCrossLayerUrl(),\n options,\n this.crossLayerCircuitBreaker,\n context,\n { bypassPermission: false } // Cross-layer calls go through public gateway\n );\n }\n\n /**\n * Execute GraphQL query/mutation with explicit gateway URL\n */\n async query<T = unknown>(gatewayUrl: string, options: GraphQLRequestOptions): Promise<GraphQLResponse<T>> {\n const context = this.createRequestContext('direct', options);\n\n // Use internal circuit breaker for direct calls\n return this.executeWithRetry(gatewayUrl, options, this.internalCircuitBreaker, context, {\n bypassPermission: false,\n });\n }\n\n getInternalCircuitBreaker(): ICircuitBreaker {\n return this.internalCircuitBreaker;\n }\n\n getCrossLayerCircuitBreaker(): ICircuitBreaker {\n return this.crossLayerCircuitBreaker;\n }\n\n getHealthStatus(): GatewayClientHealth {\n return {\n internal: {\n url: this.getInternalUrl(),\n circuitState: this.internalCircuitBreaker.getState(),\n stats: this.internalCircuitBreaker.getStats(),\n },\n crossLayer: {\n url: this.getCrossLayerUrl(),\n circuitState: this.crossLayerCircuitBreaker.getState(),\n stats: this.crossLayerCircuitBreaker.getStats(),\n },\n };\n }\n\n updateDefaultHeaders(headers: Partial<GatewayRequestHeaders>): void {\n this.defaultHeaders = { ...this.defaultHeaders, ...headers };\n }\n\n private createRequestContext(\n callType: 'internal' | 'cross-layer' | 'direct',\n options: GraphQLRequestOptions\n ): RequestContext {\n return {\n requestId: uuidv4(),\n actorId: options.headers?.['x-actor-id'] || this.defaultHeaders['x-actor-id'],\n workspaceId: options.headers?.['x-workspace-id'] || this.defaultHeaders['x-workspace-id'],\n startTime: Date.now(),\n callType,\n };\n }\n\n /**\n * Check if an error should be retried\n */\n private shouldRetryError(error: unknown): boolean {\n if (!(error instanceof GatewayError)) {\n return true;\n }\n // Don't retry GraphQL errors or circuit open errors\n return error.type !== GatewayErrorType.GRAPHQL_ERROR && error.type !== GatewayErrorType.CIRCUIT_OPEN;\n }\n\n /**\n * Calculate retry delay with exponential backoff\n */\n private calculateRetryDelay(attempt: number): number {\n return Math.min(\n this.retryConfig.initialDelay * Math.pow(this.retryConfig.backoffMultiplier, attempt - 1),\n this.retryConfig.maxDelay\n );\n }\n\n /**\n * Log retry attempt if logging is enabled\n */\n private logRetryAttempt(\n context: RequestContext,\n attempt: number,\n maxAttempts: number,\n delay: number,\n error: Error\n ): void {\n if (this.config.enableLogging) {\n logger.warn('[GatewayClient] Request failed, retrying', {\n requestId: context.requestId,\n attempt,\n maxAttempts,\n delay,\n error: error.message,\n });\n }\n }\n\n private async executeWithRetry<T>(\n gatewayUrl: string,\n options: GraphQLRequestOptions,\n circuitBreaker: CircuitBreaker,\n context: RequestContext,\n settings: { bypassPermission: boolean }\n ): Promise<GraphQLResponse<T>> {\n // Check circuit breaker\n if (!options.skipCircuitBreaker && !circuitBreaker.allowRequest()) {\n throw new GatewayError(`Circuit breaker is open for ${gatewayUrl}`, GatewayErrorType.CIRCUIT_OPEN, gatewayUrl);\n }\n\n const maxAttempts = options.skipRetry ? 1 : this.retryConfig.maxAttempts;\n let lastError: Error | null = null;\n\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n try {\n const result = await this.executeRequest<T>(gatewayUrl, options, context, settings.bypassPermission);\n if (!options.skipCircuitBreaker) {\n circuitBreaker.recordSuccess();\n }\n return result;\n } catch (error) {\n lastError = error instanceof Error ? error : new Error(String(error));\n const clientError = isGatewayClientError(error);\n if (!options.skipCircuitBreaker) {\n // A client error means the gateway answered: record it as a healthy\n // round trip (which also closes a half-open circuit) instead of a failure.\n if (clientError) {\n circuitBreaker.recordSuccess();\n } else {\n circuitBreaker.recordFailure();\n }\n }\n\n if (clientError || !this.shouldRetryError(error)) {\n throw error;\n }\n\n if (attempt < maxAttempts) {\n const delay = this.calculateRetryDelay(attempt);\n this.logRetryAttempt(context, attempt, maxAttempts, delay, lastError);\n await this.sleep(delay);\n }\n }\n }\n\n throw lastError || new GatewayError('Request failed after retries', GatewayErrorType.UNKNOWN_ERROR, gatewayUrl);\n }\n\n /**\n * Build headers for a request\n */\n private buildRequestHeaders(\n context: RequestContext,\n options: GraphQLRequestOptions,\n bypassPermission: boolean\n ): Record<string, string> {\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n 'x-request-id': context.requestId,\n 'x-call-type': context.callType,\n };\n\n // Cross-layer calls transit the peer layer's PUBLIC gateway, which on alpha\n // sits behind Cloudflare Access. Re-present the inbound request's CF creds\n // (service token and/or the CF_Authorization cookie) so the call passes the\n // CF edge. Added before default/request headers so a caller may still\n // override the non-cookie CF headers explicitly; the CF cookie is reconciled\n // after the merges below so it is never silently clobbered. No-op when the\n // inbound request carried no CF creds (local dev, production) — returns {}.\n const cfHeaders = context.callType === 'cross-layer' ? ContextManager.getCfAccessHeaders() : {};\n Object.assign(headers, cfHeaders);\n\n // Add default headers\n for (const [key, value] of Object.entries(this.defaultHeaders)) {\n if (value !== undefined) {\n headers[key] = String(value);\n }\n }\n\n // Add request-specific headers\n if (options.headers) {\n for (const [key, value] of Object.entries(options.headers)) {\n if (value !== undefined) {\n headers[key] = String(value);\n }\n }\n }\n\n // Add bypass headers for internal calls\n if (bypassPermission) {\n headers['x-bypass-permission'] = resolveBypassPermissionValue();\n headers['x-bypass-source'] = this.layerManager.getServiceIdentity();\n headers['x-bypass-timestamp'] = Date.now().toString();\n }\n\n // Reconcile the CF_Authorization cookie: the default/request-header merges\n // above may set their own `cookie`, which would otherwise clobber the CF\n // cookie applied earlier (or vice versa). Merge so both survive, without\n // duplicating if it's already present.\n const cfCookie = cfHeaders['cookie'];\n if (cfCookie) {\n const existing = headers['cookie'];\n if (!existing) {\n headers['cookie'] = cfCookie;\n } else if (!existing.split(';').some((c) => c.trim() === cfCookie)) {\n headers['cookie'] = `${existing}; ${cfCookie}`;\n }\n }\n\n return headers;\n }\n\n /**\n * Handle GraphQL errors in response\n */\n private handleGraphQLErrors<T>(\n result: GraphQLResponse<T>,\n context: RequestContext,\n gatewayUrl: string,\n duration: number\n ): void {\n if (!result.errors || result.errors.length === 0) {\n return;\n }\n\n const errorMessages = result.errors.map((e: GraphQLError) => e.message).join(', ');\n\n if (this.config.enableLogging) {\n logger.warn('[GatewayClient] GraphQL errors', {\n requestId: context.requestId,\n errors: result.errors,\n duration,\n });\n }\n\n throw new GatewayError(`GraphQL error: ${errorMessages}`, GatewayErrorType.GRAPHQL_ERROR, gatewayUrl, {\n graphqlErrors: result.errors,\n });\n }\n\n /**\n * Handle fetch errors\n */\n private handleFetchError(\n error: unknown,\n context: RequestContext,\n gatewayUrl: string,\n timeout: number,\n duration: number\n ): never {\n if (error instanceof GatewayError) {\n throw error;\n }\n\n if (error instanceof Error) {\n if (error.name === 'AbortError') {\n throw new GatewayError(`Request timed out after ${timeout}ms`, GatewayErrorType.TIMEOUT_ERROR, gatewayUrl, {\n cause: error,\n });\n }\n\n if (this.config.enableLogging) {\n logger.error('[GatewayClient] Request failed', {\n requestId: context.requestId,\n error: error.message,\n duration,\n });\n }\n\n throw new GatewayError(error.message, GatewayErrorType.NETWORK_ERROR, gatewayUrl, {\n cause: error,\n });\n }\n\n throw new GatewayError(String(error), GatewayErrorType.UNKNOWN_ERROR, gatewayUrl);\n }\n\n private async executeRequest<T>(\n gatewayUrl: string,\n options: GraphQLRequestOptions,\n context: RequestContext,\n bypassPermission: boolean\n ): Promise<GraphQLResponse<T>> {\n const timeout = options.timeout || this.config.timeout || 30000;\n const headers = this.buildRequestHeaders(context, options, bypassPermission);\n\n // Cross-layer calls transit the peer layer's PUBLIC gateway, which\n // requires JWT auth to propagate actor context. Mint a short-lived\n // service-actor JWT so the gateway admits the call and preserves\n // `x-actor-type: service` downstream. Skipped when the caller has\n // already supplied an Authorization header (e.g., user-originated\n // cross-layer flows) or when SERVICE_JWT_SECRET is unset.\n if (context.callType === 'cross-layer' && !hasAuthorizationHeader(headers)) {\n const serviceActorId = this.layerManager.getServiceIdentity();\n const serviceJwt = await signServiceJwt(serviceActorId);\n if (serviceJwt) {\n headers['Authorization'] = `Bearer ${serviceJwt}`;\n } else {\n // Without the JWT this call is already decided: the peer layer's public\n // gateway strips actor headers and the subgraph rejects it. Continuing\n // only converts a missing secret into an authentication error that names\n // the callee — and several cross-layer callers swallow that as\n // best-effort, so it surfaces as nothing at all. In a deployed\n // environment, refuse instead. See ./service-jwt-guard.ts.\n assertServiceJwtConfigured({\n gatewayUrl,\n operationName: options.operationName,\n layer: this.layerManager.getLayer(),\n serviceIdentity: serviceActorId,\n });\n if (this.config.enableLogging) {\n logger.debug(\n '[GatewayClient] SERVICE_JWT_SECRET not configured — cross-layer call will proceed without service JWT',\n { requestId: context.requestId, gatewayUrl }\n );\n }\n }\n }\n\n const body = JSON.stringify({\n query: options.query,\n variables: options.variables || {},\n operationName: options.operationName,\n });\n\n if (this.config.enableLogging) {\n logger.debug('[GatewayClient] Executing request', {\n requestId: context.requestId,\n gatewayUrl,\n operationName: options.operationName,\n callType: context.callType,\n bypassPermission,\n });\n }\n\n try {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), timeout);\n\n const response = await fetch(gatewayUrl, {\n method: 'POST',\n headers,\n body,\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n const duration = Date.now() - context.startTime;\n\n if (!response.ok) {\n let graphqlErrors: GraphQLError[] | undefined;\n try {\n const body: unknown = await response.json();\n if (\n body !== null &&\n typeof body === 'object' &&\n 'errors' in body &&\n Array.isArray(body.errors) &&\n body.errors.length > 0 &&\n body.errors.every(isGraphQLError)\n )\n graphqlErrors = body.errors;\n } catch {\n // Edge/proxy errors need not contain JSON; retain the original HTTP failure.\n }\n // Keep the \"HTTP <status>: <text>\" prefix callers may already match on,\n // and append the GraphQL messages so logs show what the gateway said.\n const httpMessage = `HTTP ${response.status}: ${response.statusText}`;\n throw new GatewayError(\n graphqlErrors\n ? `${httpMessage} (GraphQL error: ${graphqlErrors.map((e) => e.message).join(', ')})`\n : httpMessage,\n graphqlErrors && response.status < 500 ? GatewayErrorType.GRAPHQL_ERROR : GatewayErrorType.NETWORK_ERROR,\n gatewayUrl,\n { statusCode: response.status, graphqlErrors }\n );\n }\n\n const result = (await response.json()) as GraphQLResponse<T>;\n this.handleGraphQLErrors(result, context, gatewayUrl, duration);\n\n if (this.config.enableLogging) {\n logger.debug('[GatewayClient] Request completed', {\n requestId: context.requestId,\n duration,\n hasData: !!result.data,\n });\n }\n\n return result;\n } catch (error) {\n const duration = Date.now() - context.startTime;\n this.handleFetchError(error, context, gatewayUrl, timeout, duration);\n }\n }\n\n private sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n}\n\n/**\n * Create a gateway client for a specific layer\n */\nexport function createGatewayClient(config: GatewayClientConfig): GatewayClient {\n return new GatewayClient(config);\n}\n\n/**\n * Create a gateway client from environment variables\n *\n * Required environment variables:\n * - SERVICE_LAYER: 'wspace' | 'global'\n * - SERVICE_NAME: Service name\n *\n * Optional:\n * - SERVICE_IDENTITY: Service identity (defaults to SERVICE_NAME)\n * - {LAYER}_INT_GATEWAY_URL: Internal gateway URL\n * - {OPPOSITE_LAYER}_PUBLIC_GATEWAY_URL: Cross-layer gateway URL\n */\nexport function createGatewayClientFromEnv(): GatewayClient {\n const layer = process.env['SERVICE_LAYER'] as ServiceLayer;\n\n if (!layer || (layer !== 'wspace' && layer !== 'global')) {\n throw new Error(`[GatewayClient] Invalid or missing SERVICE_LAYER. Expected 'wspace' or 'global', got '${layer}'`);\n }\n\n const serviceName = process.env['SERVICE_NAME'];\n if (!serviceName) {\n throw new Error('[GatewayClient] SERVICE_NAME environment variable is required');\n }\n\n const serviceIdentity = process.env['SERVICE_IDENTITY'] || serviceName;\n\n return new GatewayClient({\n layer,\n serviceName,\n serviceIdentity,\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,MAAa,yBAAyB;;;;;;AAkBtC,SAAgB,kCAAkC,SAAyC;CACzF,MAAM,cAAc,mBAAmB,KAAK;CAC5C,MAAM,QAAQ,QAAQ,SAAS;CAC/B,MAAM,YAAY,QAAQ,gBAAgB,eAAe,QAAQ,cAAc,KAAK;CACpF,MAAM,WAAW,QAAQ,kBAAkB,QAAQ,QAAQ,gBAAgB,KAAK;CAChF,OACE,uCAAuC,QAAQ,aAAa,UAAU,0BAA0B,SAAS,IACtG,uBAAuB,oNAEsB,YAAY,QAAQ,uBAAuB,WACnF,YAAY,GAAG,MAAM;AAGjC;;;;;;AAOA,SAAgB,2BAA2B,SAAuC;CAChF,IAAI,CAAC,sBAAsB,GAAG;CAC9B,MAAM,IAAI,MAAM,kCAAkC,OAAO,CAAC;AAC5D;;;;;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M,cAAc,QAAQ,IAAI;CAChC,IAAI,CAAC,aACH,MAAM,IAAI,MAAM,+DAA+D;CAGjF,MAAM,kBAAkB,QAAQ,IAAI,uBAAuB;CAE3D,OAAO,IAAI,cAAc;EACvB;EACA;EACA;CACF,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"client-sAJTrb4i.js","names":[],"sources":["../src/gateway/service-jwt-guard.ts","../src/gateway/client.ts"],"sourcesContent":["/**\n * Cross-layer service-JWT configuration guard.\n *\n * A cross-layer call transits the peer layer's PUBLIC gateway, which propagates\n * `x-actor-*` context to subgraphs only when the request carries a valid JWT.\n * Without one the gateway strips those headers as potential client spoofing and\n * the subgraph rejects the call. So on a cross-layer request with no\n * Authorization header and no mintable service JWT, the outcome is already\n * decided before the request leaves the process: it will fail, downstream, with\n * an authentication error that names the callee rather than the missing secret.\n *\n * That is a bad trade in a deployed environment. It converts a one-line config\n * problem into an opaque failure attributed to the wrong service, and — because\n * several cross-layer callers treat these calls as best-effort and swallow the\n * error — into no visible failure at all. Alpha ran exactly that way: 414 calls\n * in 24h on `AddWorkspaceMemberFromWspace` and `WorkspaceOrganization`, every\n * one rejected, workspace-member mirroring silently not happening, and nothing\n * in the caller's logs above debug level.\n *\n * So in alpha, staging and production this throws before the request is sent,\n * naming the secret and the bundle to fix. Locally it stays a log: a laptop\n * calling across layers without a service JWT is a normal state while a\n * developer is mid-setup, and failing their `bun run dev` would be hostile.\n *\n * Verified inert before shipping, the same way the cache guard was: of the\n * alpha and prod service bundles in Secrets Manager, every be-sdk service that\n * makes cross-layer calls already carries `SERVICE_JWT_SECRET` (166 bundles).\n * The bundles without it are Temporal, OPA, the OTel collectors, NATS, Gatus,\n * the vibetunnels pair, the ai-assistant trio, the dormant `*-community`\n * deployments and the retired `state-archive-*` configs — none of which\n * constructs a GatewayClient or makes a cross-layer call. Nothing changes\n * today; this only catches the next caller rolled out without the secret.\n */\nimport { isDeployedEnvironment, currentEnvironment } from '../runtime/deployed-environment.js';\n\n/** Env var that must hold the signing key for service-actor JWTs. */\nexport const SERVICE_JWT_SECRET_ENV = 'SERVICE_JWT_SECRET';\n\nexport interface ServiceJwtGuardContext {\n /** Absolute URL of the peer gateway the call was about to be sent to. */\n gatewayUrl: string;\n /** GraphQL operation name, when the caller supplied one. */\n operationName?: string;\n /** Layer boundary of the CALLER, used to name the bundle to fix. */\n layer?: string;\n /** Service identity the JWT would have been minted for. */\n serviceIdentity?: string;\n}\n\n/**\n * Build the operator-facing explanation. Exported so the message itself is\n * covered by tests — a guard whose text does not say what to change just moves\n * the debugging, it does not remove it.\n */\nexport function serviceJwtMisconfigurationMessage(context: ServiceJwtGuardContext): string {\n const environment = currentEnvironment() || 'unset';\n const layer = context.layer ?? '{layer}';\n const operation = context.operationName ? ` (operation ${context.operationName})` : '';\n const identity = context.serviceIdentity ? ` as '${context.serviceIdentity}'` : '';\n return (\n `[GatewayClient] Cross-layer call to ${context.gatewayUrl}${operation} cannot be authenticated${identity}: ` +\n `${SERVICE_JWT_SECRET_ENV} is not set, so no service JWT can be minted. The peer layer's public ` +\n `gateway will strip actor headers and the subgraph will reject the request, so this call cannot ` +\n `succeed. Refusing to send it with DEPLOY_ENV=${environment}. Set ${SERVICE_JWT_SECRET_ENV} in ` +\n `boff/${environment}/${layer}/{module} — it must match the value the peer layer's gateway ` +\n `verifies with, which is per-environment and must never be copied across environments.`\n );\n}\n\n/**\n * Throw in a deployed environment when a cross-layer call is about to be sent\n * with no way to authenticate it. Returns normally everywhere else, and\n * whenever a JWT was available — so this costs nothing on the happy path.\n */\nexport function assertServiceJwtConfigured(context: ServiceJwtGuardContext): void {\n if (!isDeployedEnvironment()) return;\n throw new Error(serviceJwtMisconfigurationMessage(context));\n}\n","/**\n * Unified Gateway Client\n *\n * Provides a layer-aware GraphQL client with circuit breaker,\n * retry logic, and automatic header management for M2M communication.\n *\n * @module gateway/client\n * @category Gateway\n *\n * @example\n * ```typescript\n * import { GatewayClient } from '@burdenoff/be-sdk/gateway';\n *\n * const client = new GatewayClient({\n * layer: 'wspace',\n * serviceName: 'wspace-tags-svc',\n * });\n *\n * // Internal call (same layer)\n * const result = await client.internalQuery({\n * query: `query { getTag(id: \"123\") { id name } }`,\n * });\n *\n * // Cross-layer call\n * const authResult = await client.crossLayerQuery({\n * query: `query { getCurrentUser { id email } }`,\n * });\n * ```\n */\n\nimport { ContextManager } from '../context/index.js';\nimport { LayerManager } from '../layer/index.js';\nimport { logger } from '../logger/index.js';\nimport { signServiceJwt } from './service-jwt.js';\nimport { assertServiceJwtConfigured } from './service-jwt-guard.js';\nimport {\n DEFAULT_CIRCUIT_BREAKER_CONFIG,\n DEFAULT_GATEWAY_RETRY_CONFIG,\n type CircuitBreakerConfig,\n type GatewayRequestHeaders,\n type GatewayRetryConfig,\n type ServiceLayer,\n} from '../types/layer.js';\nimport {\n CircuitState,\n GatewayError,\n GatewayErrorType,\n type CircuitBreakerStats,\n type GatewayClientConfig,\n type GatewayClientHealth,\n type GraphQLError,\n type GraphQLRequestOptions,\n type GraphQLResponse,\n type ICircuitBreaker,\n type IGatewayClient,\n type RequestContext,\n} from './types.js';\n\nconst uuidv4 = (): string => crypto.randomUUID();\n\n/**\n * Case-insensitive presence check for the `Authorization` header. HTTP header\n * names are case-insensitive (RFC 7230), and while the outbound `fetch` will\n * preserve whatever casing the caller supplies, callers may legitimately set\n * `authorization` / `Authorization` / even `AUTHORIZATION` via defaultHeaders\n * or options.headers. We must not overwrite an already-supplied token.\n */\nfunction hasAuthorizationHeader(headers: Record<string, string>): boolean {\n for (const key of Object.keys(headers)) {\n if (key.toLowerCase() === 'authorization') return true;\n }\n return false;\n}\n\nfunction isGraphQLError(value: unknown): value is GraphQLError {\n return (\n value !== null &&\n typeof value === 'object' &&\n 'message' in value &&\n typeof value.message === 'string' &&\n (!('extensions' in value) ||\n (value.extensions !== null && typeof value.extensions === 'object' && !Array.isArray(value.extensions)))\n );\n}\n\n/**\n * HTTP statuses in the 4xx range that describe a transient condition rather than\n * a problem with the request itself: the request timed out at the peer (408) or\n * the peer is shedding load (429 without a GraphQL body, i.e. an edge or proxy\n * limit). Those stay retryable and still count toward the circuit breaker.\n */\nconst TRANSIENT_CLIENT_STATUSES: ReadonlySet<number> = new Set([408, 429]);\n\n/**\n * Is this failure a definitive answer about the request rather than a sign that\n * the gateway or the transport is unhealthy?\n *\n * True for:\n * - `GRAPHQL_ERROR`: the gateway executed the operation and answered with\n * GraphQL errors (for example `NOT_FOUND`, `BAD_USER_INPUT`, `FORBIDDEN`),\n * whether that arrived with HTTP 200 or with a 4xx status;\n * - an HTTP 4xx without a GraphQL body (for example an edge 403 or 404), except\n * the transient statuses 408 and 429.\n *\n * Such failures are never retried (the same request gets the same answer) and\n * are not counted toward the circuit breaker: a burst of legitimate \"not found\"\n * lookups must not open the circuit for every other call the service makes.\n *\n * @param error - Anything thrown by a GatewayClient call\n * @returns Whether the error is a client error in the sense above\n */\nexport function isGatewayClientError(error: unknown): boolean {\n if (!(error instanceof GatewayError)) return false;\n if (error.type === GatewayErrorType.GRAPHQL_ERROR) return true;\n if (error.type !== GatewayErrorType.NETWORK_ERROR || error.statusCode === undefined) return false;\n return error.statusCode >= 400 && error.statusCode < 500 && !TRANSIENT_CLIENT_STATUSES.has(error.statusCode);\n}\n\nexport function resolveBypassPermissionValue(\n token: string | undefined = process.env['INTERNAL_SERVICE_TOKEN']\n): string {\n const normalizedToken = token?.trim();\n\n if (!normalizedToken) {\n throw new Error('INTERNAL_SERVICE_TOKEN must be configured for bypass-enabled gateway calls');\n }\n\n return normalizedToken;\n}\n\n/**\n * Circuit Breaker Implementation\n */\nclass CircuitBreaker implements ICircuitBreaker {\n private state: CircuitState = CircuitState.CLOSED;\n private failures = 0;\n private successes = 0;\n private consecutiveFailures = 0;\n private lastFailureTime: number | null = null;\n private lastSuccessTime: number | null = null;\n private openedAt: number | null = null;\n private failureTimestamps: number[] = [];\n private config: CircuitBreakerConfig;\n\n constructor(config: CircuitBreakerConfig) {\n this.config = config;\n }\n\n getState(): CircuitState {\n this.checkStateTransition();\n return this.state;\n }\n\n recordSuccess(): void {\n this.successes++;\n this.consecutiveFailures = 0;\n this.lastSuccessTime = Date.now();\n\n if (this.state === CircuitState.HALF_OPEN) {\n this.state = CircuitState.CLOSED;\n this.failures = 0;\n this.failureTimestamps = [];\n this.openedAt = null;\n logger.info('[CircuitBreaker] Circuit closed after successful test');\n }\n }\n\n recordFailure(): void {\n this.failures++;\n this.consecutiveFailures++;\n this.lastFailureTime = Date.now();\n this.failureTimestamps.push(Date.now());\n\n // Clean up old timestamps\n const windowStart = Date.now() - this.config.failureWindow;\n this.failureTimestamps = this.failureTimestamps.filter((t) => t > windowStart);\n\n // Check if we should open the circuit\n if (this.state === CircuitState.CLOSED && this.failureTimestamps.length >= this.config.failureThreshold) {\n this.state = CircuitState.OPEN;\n this.openedAt = Date.now();\n logger.warn('[CircuitBreaker] Circuit opened due to failures', {\n failures: this.failureTimestamps.length,\n threshold: this.config.failureThreshold,\n });\n }\n\n // If we're half-open and fail, go back to open\n if (this.state === CircuitState.HALF_OPEN) {\n this.state = CircuitState.OPEN;\n this.openedAt = Date.now();\n logger.warn('[CircuitBreaker] Circuit re-opened after failed test');\n }\n }\n\n allowRequest(): boolean {\n this.checkStateTransition();\n\n switch (this.state) {\n case CircuitState.CLOSED:\n return true;\n case CircuitState.OPEN:\n return false;\n case CircuitState.HALF_OPEN:\n // Allow one test request\n return true;\n default:\n return true;\n }\n }\n\n forceOpen(): void {\n this.state = CircuitState.OPEN;\n this.openedAt = Date.now();\n logger.info('[CircuitBreaker] Circuit force-opened');\n }\n\n forceClose(): void {\n this.state = CircuitState.CLOSED;\n this.failures = 0;\n this.consecutiveFailures = 0;\n this.failureTimestamps = [];\n this.openedAt = null;\n logger.info('[CircuitBreaker] Circuit force-closed');\n }\n\n getStats(): CircuitBreakerStats {\n return {\n state: this.state,\n failures: this.failures,\n successes: this.successes,\n consecutiveFailures: this.consecutiveFailures,\n lastFailureTime: this.lastFailureTime,\n lastSuccessTime: this.lastSuccessTime,\n openedAt: this.openedAt,\n };\n }\n\n private checkStateTransition(): void {\n if (this.state === CircuitState.OPEN && this.openedAt) {\n const elapsed = Date.now() - this.openedAt;\n if (elapsed >= this.config.resetTimeout) {\n this.state = CircuitState.HALF_OPEN;\n logger.info('[CircuitBreaker] Circuit transitioning to half-open');\n }\n }\n }\n}\n\n/**\n * Unified Gateway Client\n */\nexport class GatewayClient implements IGatewayClient {\n private config: GatewayClientConfig;\n private layerManager: LayerManager;\n private internalCircuitBreaker: CircuitBreaker;\n private crossLayerCircuitBreaker: CircuitBreaker;\n private retryConfig: GatewayRetryConfig;\n private defaultHeaders: GatewayRequestHeaders;\n\n constructor(config: GatewayClientConfig) {\n this.config = {\n timeout: 30000,\n enableLogging: true,\n ...config,\n };\n\n // Initialize layer manager\n this.layerManager = new LayerManager({\n layer: config.layer,\n serviceName: config.serviceName,\n serviceIdentity: config.serviceIdentity,\n });\n\n // Override URLs if provided\n if (config.internalGatewayUrl) {\n // Use getter internally, but we'll store the override\n }\n if (config.crossLayerGatewayUrl) {\n // Use getter internally, but we'll store the override\n }\n\n // Initialize circuit breakers\n const cbConfig: CircuitBreakerConfig = {\n ...DEFAULT_CIRCUIT_BREAKER_CONFIG,\n ...config.circuitBreaker,\n };\n this.internalCircuitBreaker = new CircuitBreaker(cbConfig);\n this.crossLayerCircuitBreaker = new CircuitBreaker(cbConfig);\n\n // Initialize retry config\n this.retryConfig = {\n ...DEFAULT_GATEWAY_RETRY_CONFIG,\n ...config.retry,\n };\n\n // Initialize default headers\n this.defaultHeaders = {\n 'x-service-identity': this.layerManager.getServiceIdentity(),\n 'x-actor-type': 'service',\n ...config.defaultHeaders,\n };\n\n logger.debug('[GatewayClient] Initialized', {\n layer: config.layer,\n serviceName: config.serviceName,\n internalUrl: this.getInternalUrl(),\n crossLayerUrl: this.getCrossLayerUrl(),\n });\n }\n\n private getInternalUrl(): string {\n return this.config.internalGatewayUrl || this.layerManager.getInternalGatewayUrl();\n }\n\n private getCrossLayerUrl(): string {\n return this.config.crossLayerGatewayUrl || this.layerManager.getCrossLayerGatewayUrl();\n }\n\n /**\n * Execute internal (same layer) GraphQL query/mutation\n */\n async internalQuery<T = unknown>(options: GraphQLRequestOptions): Promise<GraphQLResponse<T>> {\n const context = this.createRequestContext('internal', options);\n\n return this.executeWithRetry(this.getInternalUrl(), options, this.internalCircuitBreaker, context, {\n bypassPermission: true,\n });\n }\n\n /**\n * Execute cross-layer GraphQL query/mutation\n */\n async crossLayerQuery<T = unknown>(options: GraphQLRequestOptions): Promise<GraphQLResponse<T>> {\n const context = this.createRequestContext('cross-layer', options);\n\n return this.executeWithRetry(\n this.getCrossLayerUrl(),\n options,\n this.crossLayerCircuitBreaker,\n context,\n { bypassPermission: false } // Cross-layer calls go through public gateway\n );\n }\n\n /**\n * Execute GraphQL query/mutation with explicit gateway URL\n */\n async query<T = unknown>(gatewayUrl: string, options: GraphQLRequestOptions): Promise<GraphQLResponse<T>> {\n const context = this.createRequestContext('direct', options);\n\n // Use internal circuit breaker for direct calls\n return this.executeWithRetry(gatewayUrl, options, this.internalCircuitBreaker, context, {\n bypassPermission: false,\n });\n }\n\n getInternalCircuitBreaker(): ICircuitBreaker {\n return this.internalCircuitBreaker;\n }\n\n getCrossLayerCircuitBreaker(): ICircuitBreaker {\n return this.crossLayerCircuitBreaker;\n }\n\n getHealthStatus(): GatewayClientHealth {\n return {\n internal: {\n url: this.getInternalUrl(),\n circuitState: this.internalCircuitBreaker.getState(),\n stats: this.internalCircuitBreaker.getStats(),\n },\n crossLayer: {\n url: this.getCrossLayerUrl(),\n circuitState: this.crossLayerCircuitBreaker.getState(),\n stats: this.crossLayerCircuitBreaker.getStats(),\n },\n };\n }\n\n updateDefaultHeaders(headers: Partial<GatewayRequestHeaders>): void {\n this.defaultHeaders = { ...this.defaultHeaders, ...headers };\n }\n\n private createRequestContext(\n callType: 'internal' | 'cross-layer' | 'direct',\n options: GraphQLRequestOptions\n ): RequestContext {\n return {\n requestId: uuidv4(),\n actorId: options.headers?.['x-actor-id'] || this.defaultHeaders['x-actor-id'],\n workspaceId: options.headers?.['x-workspace-id'] || this.defaultHeaders['x-workspace-id'],\n startTime: Date.now(),\n callType,\n };\n }\n\n /**\n * Check if an error should be retried\n */\n private shouldRetryError(error: unknown): boolean {\n if (!(error instanceof GatewayError)) {\n return true;\n }\n // Don't retry GraphQL errors or circuit open errors\n return error.type !== GatewayErrorType.GRAPHQL_ERROR && error.type !== GatewayErrorType.CIRCUIT_OPEN;\n }\n\n /**\n * Calculate retry delay with exponential backoff\n */\n private calculateRetryDelay(attempt: number): number {\n return Math.min(\n this.retryConfig.initialDelay * Math.pow(this.retryConfig.backoffMultiplier, attempt - 1),\n this.retryConfig.maxDelay\n );\n }\n\n /**\n * Log retry attempt if logging is enabled\n */\n private logRetryAttempt(\n context: RequestContext,\n attempt: number,\n maxAttempts: number,\n delay: number,\n error: Error\n ): void {\n if (this.config.enableLogging) {\n logger.warn('[GatewayClient] Request failed, retrying', {\n requestId: context.requestId,\n attempt,\n maxAttempts,\n delay,\n error: error.message,\n });\n }\n }\n\n private async executeWithRetry<T>(\n gatewayUrl: string,\n options: GraphQLRequestOptions,\n circuitBreaker: CircuitBreaker,\n context: RequestContext,\n settings: { bypassPermission: boolean }\n ): Promise<GraphQLResponse<T>> {\n // Check circuit breaker\n if (!options.skipCircuitBreaker && !circuitBreaker.allowRequest()) {\n throw new GatewayError(`Circuit breaker is open for ${gatewayUrl}`, GatewayErrorType.CIRCUIT_OPEN, gatewayUrl);\n }\n\n const maxAttempts = options.skipRetry ? 1 : this.retryConfig.maxAttempts;\n let lastError: Error | null = null;\n\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n try {\n const result = await this.executeRequest<T>(gatewayUrl, options, context, settings.bypassPermission);\n if (!options.skipCircuitBreaker) {\n circuitBreaker.recordSuccess();\n }\n return result;\n } catch (error) {\n lastError = error instanceof Error ? error : new Error(String(error));\n const clientError = isGatewayClientError(error);\n if (!options.skipCircuitBreaker) {\n // A client error means the gateway answered: record it as a healthy\n // round trip (which also closes a half-open circuit) instead of a failure.\n if (clientError) {\n circuitBreaker.recordSuccess();\n } else {\n circuitBreaker.recordFailure();\n }\n }\n\n if (clientError || !this.shouldRetryError(error)) {\n throw error;\n }\n\n if (attempt < maxAttempts) {\n const delay = this.calculateRetryDelay(attempt);\n this.logRetryAttempt(context, attempt, maxAttempts, delay, lastError);\n await this.sleep(delay);\n }\n }\n }\n\n throw lastError || new GatewayError('Request failed after retries', GatewayErrorType.UNKNOWN_ERROR, gatewayUrl);\n }\n\n /**\n * Build headers for a request\n */\n private buildRequestHeaders(\n context: RequestContext,\n options: GraphQLRequestOptions,\n bypassPermission: boolean\n ): Record<string, string> {\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n 'x-request-id': context.requestId,\n 'x-call-type': context.callType,\n };\n\n // Cross-layer calls transit the peer layer's PUBLIC gateway, which on alpha\n // sits behind Cloudflare Access. Re-present the inbound request's CF creds\n // (service token and/or the CF_Authorization cookie) so the call passes the\n // CF edge. Added before default/request headers so a caller may still\n // override the non-cookie CF headers explicitly; the CF cookie is reconciled\n // after the merges below so it is never silently clobbered. No-op when the\n // inbound request carried no CF creds (local dev, production) — returns {}.\n const cfHeaders = context.callType === 'cross-layer' ? ContextManager.getCfAccessHeaders() : {};\n Object.assign(headers, cfHeaders);\n\n // Add default headers\n for (const [key, value] of Object.entries(this.defaultHeaders)) {\n if (value !== undefined) {\n headers[key] = String(value);\n }\n }\n\n // Add request-specific headers\n if (options.headers) {\n for (const [key, value] of Object.entries(options.headers)) {\n if (value !== undefined) {\n headers[key] = String(value);\n }\n }\n }\n\n // Add bypass headers for internal calls\n if (bypassPermission) {\n headers['x-bypass-permission'] = resolveBypassPermissionValue();\n headers['x-bypass-source'] = this.layerManager.getServiceIdentity();\n headers['x-bypass-timestamp'] = Date.now().toString();\n }\n\n // Reconcile the CF_Authorization cookie: the default/request-header merges\n // above may set their own `cookie`, which would otherwise clobber the CF\n // cookie applied earlier (or vice versa). Merge so both survive, without\n // duplicating if it's already present.\n const cfCookie = cfHeaders['cookie'];\n if (cfCookie) {\n const existing = headers['cookie'];\n if (!existing) {\n headers['cookie'] = cfCookie;\n } else if (!existing.split(';').some((c) => c.trim() === cfCookie)) {\n headers['cookie'] = `${existing}; ${cfCookie}`;\n }\n }\n\n return headers;\n }\n\n /**\n * Handle GraphQL errors in response\n */\n private handleGraphQLErrors<T>(\n result: GraphQLResponse<T>,\n context: RequestContext,\n gatewayUrl: string,\n duration: number\n ): void {\n if (!result.errors || result.errors.length === 0) {\n return;\n }\n\n const errorMessages = result.errors.map((e: GraphQLError) => e.message).join(', ');\n\n if (this.config.enableLogging) {\n logger.warn('[GatewayClient] GraphQL errors', {\n requestId: context.requestId,\n errors: result.errors,\n duration,\n });\n }\n\n throw new GatewayError(`GraphQL error: ${errorMessages}`, GatewayErrorType.GRAPHQL_ERROR, gatewayUrl, {\n graphqlErrors: result.errors,\n });\n }\n\n /**\n * Handle fetch errors\n */\n private handleFetchError(\n error: unknown,\n context: RequestContext,\n gatewayUrl: string,\n timeout: number,\n duration: number\n ): never {\n if (error instanceof GatewayError) {\n throw error;\n }\n\n if (error instanceof Error) {\n if (error.name === 'AbortError') {\n throw new GatewayError(`Request timed out after ${timeout}ms`, GatewayErrorType.TIMEOUT_ERROR, gatewayUrl, {\n cause: error,\n });\n }\n\n if (this.config.enableLogging) {\n logger.error('[GatewayClient] Request failed', {\n requestId: context.requestId,\n error: error.message,\n duration,\n });\n }\n\n throw new GatewayError(error.message, GatewayErrorType.NETWORK_ERROR, gatewayUrl, {\n cause: error,\n });\n }\n\n throw new GatewayError(String(error), GatewayErrorType.UNKNOWN_ERROR, gatewayUrl);\n }\n\n private async executeRequest<T>(\n gatewayUrl: string,\n options: GraphQLRequestOptions,\n context: RequestContext,\n bypassPermission: boolean\n ): Promise<GraphQLResponse<T>> {\n const timeout = options.timeout || this.config.timeout || 30000;\n const headers = this.buildRequestHeaders(context, options, bypassPermission);\n\n // Cross-layer calls transit the peer layer's PUBLIC gateway, which\n // requires JWT auth to propagate actor context. Mint a short-lived\n // service-actor JWT so the gateway admits the call and preserves\n // `x-actor-type: service` downstream. Skipped when the caller has\n // already supplied an Authorization header (e.g., user-originated\n // cross-layer flows) or when SERVICE_JWT_SECRET is unset.\n if (context.callType === 'cross-layer' && !hasAuthorizationHeader(headers)) {\n const serviceActorId = this.layerManager.getServiceIdentity();\n const serviceJwt = await signServiceJwt(serviceActorId);\n if (serviceJwt) {\n headers['Authorization'] = `Bearer ${serviceJwt}`;\n } else {\n // Without the JWT this call is already decided: the peer layer's public\n // gateway strips actor headers and the subgraph rejects it. Continuing\n // only converts a missing secret into an authentication error that names\n // the callee — and several cross-layer callers swallow that as\n // best-effort, so it surfaces as nothing at all. In a deployed\n // environment, refuse instead. See ./service-jwt-guard.ts.\n assertServiceJwtConfigured({\n gatewayUrl,\n operationName: options.operationName,\n layer: this.layerManager.getLayer(),\n serviceIdentity: serviceActorId,\n });\n if (this.config.enableLogging) {\n logger.debug(\n '[GatewayClient] SERVICE_JWT_SECRET not configured — cross-layer call will proceed without service JWT',\n { requestId: context.requestId, gatewayUrl }\n );\n }\n }\n }\n\n const body = JSON.stringify({\n query: options.query,\n variables: options.variables || {},\n operationName: options.operationName,\n });\n\n if (this.config.enableLogging) {\n logger.debug('[GatewayClient] Executing request', {\n requestId: context.requestId,\n gatewayUrl,\n operationName: options.operationName,\n callType: context.callType,\n bypassPermission,\n });\n }\n\n try {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), timeout);\n\n const response = await fetch(gatewayUrl, {\n method: 'POST',\n headers,\n body,\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n const duration = Date.now() - context.startTime;\n\n if (!response.ok) {\n let graphqlErrors: GraphQLError[] | undefined;\n try {\n const body: unknown = await response.json();\n if (\n body !== null &&\n typeof body === 'object' &&\n 'errors' in body &&\n Array.isArray(body.errors) &&\n body.errors.length > 0 &&\n body.errors.every(isGraphQLError)\n )\n graphqlErrors = body.errors;\n } catch {\n // Edge/proxy errors need not contain JSON; retain the original HTTP failure.\n }\n // Keep the \"HTTP <status>: <text>\" prefix callers may already match on,\n // and append the GraphQL messages so logs show what the gateway said.\n const httpMessage = `HTTP ${response.status}: ${response.statusText}`;\n throw new GatewayError(\n graphqlErrors\n ? `${httpMessage} (GraphQL error: ${graphqlErrors.map((e) => e.message).join(', ')})`\n : httpMessage,\n graphqlErrors && response.status < 500 ? GatewayErrorType.GRAPHQL_ERROR : GatewayErrorType.NETWORK_ERROR,\n gatewayUrl,\n { statusCode: response.status, graphqlErrors }\n );\n }\n\n const result = (await response.json()) as GraphQLResponse<T>;\n this.handleGraphQLErrors(result, context, gatewayUrl, duration);\n\n if (this.config.enableLogging) {\n logger.debug('[GatewayClient] Request completed', {\n requestId: context.requestId,\n duration,\n hasData: !!result.data,\n });\n }\n\n return result;\n } catch (error) {\n const duration = Date.now() - context.startTime;\n this.handleFetchError(error, context, gatewayUrl, timeout, duration);\n }\n }\n\n private sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n}\n\n/**\n * Create a gateway client for a specific layer\n */\nexport function createGatewayClient(config: GatewayClientConfig): GatewayClient {\n return new GatewayClient(config);\n}\n\n/**\n * Create a gateway client from environment variables\n *\n * Required environment variables:\n * - SERVICE_LAYER: 'wspace' | 'global'\n * - SERVICE_NAME: Service name\n *\n * Optional:\n * - SERVICE_IDENTITY: Service identity (defaults to SERVICE_NAME)\n * - {LAYER}_INT_GATEWAY_URL: Internal gateway URL\n * - {OPPOSITE_LAYER}_PUBLIC_GATEWAY_URL: Cross-layer gateway URL\n */\nexport function createGatewayClientFromEnv(): GatewayClient {\n const layer = process.env['SERVICE_LAYER'] as ServiceLayer;\n\n if (!layer || (layer !== 'wspace' && layer !== 'global')) {\n throw new Error(`[GatewayClient] Invalid or missing SERVICE_LAYER. Expected 'wspace' or 'global', got '${layer}'`);\n }\n\n const serviceName = process.env['SERVICE_NAME'];\n if (!serviceName) {\n throw new Error('[GatewayClient] SERVICE_NAME environment variable is required');\n }\n\n const serviceIdentity = process.env['SERVICE_IDENTITY'] || serviceName;\n\n return new GatewayClient({\n layer,\n serviceName,\n serviceIdentity,\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,MAAa,yBAAyB;;;;;;AAkBtC,SAAgB,kCAAkC,SAAyC;CACzF,MAAM,cAAc,mBAAmB,KAAK;CAC5C,MAAM,QAAQ,QAAQ,SAAS;CAC/B,MAAM,YAAY,QAAQ,gBAAgB,eAAe,QAAQ,cAAc,KAAK;CACpF,MAAM,WAAW,QAAQ,kBAAkB,QAAQ,QAAQ,gBAAgB,KAAK;CAChF,OACE,uCAAuC,QAAQ,aAAa,UAAU,0BAA0B,SAAS,IACtG,uBAAuB,oNAEsB,YAAY,QAAQ,uBAAuB,WACnF,YAAY,GAAG,MAAM;AAGjC;;;;;;AAOA,SAAgB,2BAA2B,SAAuC;CAChF,IAAI,CAAC,sBAAsB,GAAG;CAC9B,MAAM,IAAI,MAAM,kCAAkC,OAAO,CAAC;AAC5D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACnBA,MAAM,eAAuB,OAAO,WAAW;;;;;;;;AAS/C,SAAS,uBAAuB,SAA0C;CACxE,KAAK,MAAM,OAAO,OAAO,KAAK,OAAO,GACnC,IAAI,IAAI,YAAY,MAAM,iBAAiB,OAAO;CAEpD,OAAO;AACT;AAEA,SAAS,eAAe,OAAuC;CAC7D,OACE,UAAU,QACV,OAAO,UAAU,YACjB,aAAa,SACb,OAAO,MAAM,YAAY,aACxB,EAAE,gBAAgB,UAChB,MAAM,eAAe,QAAQ,OAAO,MAAM,eAAe,YAAY,CAAC,MAAM,QAAQ,MAAM,UAAU;AAE3G;;;;;;;AAQA,MAAM,4CAAiD,IAAI,IAAI,CAAC,KAAK,GAAG,CAAC;;;;;;;;;;;;;;;;;;;AAoBzE,S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S,yCACnC,YACA;KAAE,YAAY,SAAS;KAAQ;IAAc,CAC/C;GACF;GAEA,MAAM,SAAU,MAAM,SAAS,KAAK;GACpC,KAAK,oBAAoB,QAAQ,SAAS,YAAY,QAAQ;GAE9D,IAAI,KAAK,OAAO,eACd,OAAO,MAAM,qCAAqC;IAChD,WAAW,QAAQ;IACnB;IACA,SAAS,CAAC,CAAC,OAAO;GACpB,CAAC;GAGH,OAAO;EACT,SAAS,OAAO;GACd,MAAM,WAAW,KAAK,IAAI,IAAI,QAAQ;GACtC,KAAK,iBAAiB,OAAO,SAAS,YAAY,SAAS,QAAQ;EACrE;CACF;CAEA,AAAQ,MAAM,IAA2B;EACvC,OAAO,IAAI,SAAS,YAAY,WAAW,SAAS,EAAE,CAAC;CACzD;AACF;;;;AAKA,SAAgB,oBAAoB,QAA4C;CAC9E,OAAO,IAAI,cAAc,MAAM;AACjC;;;;;;;;;;;;;AAcA,SAAgB,6BAA4C;CAC1D,MAAM,QAAQ,QAAQ,IAAI;CAE1B,IAAI,CAAC,SAAU,UAAU,YAAY,UAAU,UAC7C,MAAM,IAAI,MAAM,yFAAyF,MAAM,EAAE;CAGnH,MAAM,cAAc,QAAQ,IAAI;CAChC,IAAI,CAAC,aACH,MAAM,IAAI,MAAM,+DAA+D;CAGjF,MAAM,kBAAkB,QAAQ,IAAI,uBAAuB;CAE3D,OAAO,IAAI,cAAc;EACvB;EACA;EACA;CACF,CAAC;AACH"}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { p as SDKContext } from "../index-CTTwo9av.js";
|
|
2
|
+
export declare class ContextManager {
|
|
3
|
+
static getContext(): SDKContext | undefined;
|
|
4
|
+
static setContext(context: SDKContext): void;
|
|
5
|
+
static setCfAccessContext(clientId?: string, clientSecret?: string, cfAuthorization?: string): void;
|
|
6
|
+
static withContext<T>(context: SDKContext, fn: () => Promise<T>): Promise<T>;
|
|
7
|
+
static withContextSync<T>(context: SDKContext, fn: () => T): T;
|
|
8
|
+
static clearContext(): void;
|
|
9
|
+
static getActorId(): string | undefined;
|
|
10
|
+
static getUser(): string | undefined;
|
|
11
|
+
static getWorkspace(): string | undefined;
|
|
12
|
+
static getTenant(): string | undefined;
|
|
13
|
+
static getOrganization(): string | undefined;
|
|
14
|
+
static getProject(): string | undefined;
|
|
15
|
+
static getApp(): string | undefined;
|
|
16
|
+
static getToken(): string | undefined;
|
|
17
|
+
static getProduct(): string | undefined;
|
|
18
|
+
static getCfAccessClientId(): string | undefined;
|
|
19
|
+
static getCfAccessClientSecret(): string | undefined;
|
|
20
|
+
static getCfAuthorization(): string | undefined;
|
|
21
|
+
static getCfAccessHeaders(): Record<string, string>;
|
|
22
|
+
static updateContext(updates: Partial<SDKContext>): void;
|
|
23
|
+
static hasContext(): boolean;
|
|
24
|
+
static getCustomField(key: string): unknown;
|
|
25
|
+
static setCustomField(key: string, value: unknown): void;
|
|
26
|
+
}
|
|
27
|
+
export declare const contextManager: typeof ContextManager;
|
|
28
|
+
export declare function extractContextFromRequest(req: {
|
|
29
|
+
headers: Record<string, string | string[] | undefined>;
|
|
30
|
+
user?: {
|
|
31
|
+
user_id?: string;
|
|
32
|
+
workspace_id?: string;
|
|
33
|
+
tenant_endpoint?: string;
|
|
34
|
+
};
|
|
35
|
+
}): SDKContext;
|
|
@@ -242,6 +242,42 @@ var ContextManager = class {
|
|
|
242
242
|
});
|
|
243
243
|
}
|
|
244
244
|
};
|
|
245
|
+
/**
|
|
246
|
+
* Default export for convenience
|
|
247
|
+
*/
|
|
248
|
+
const contextManager = ContextManager;
|
|
249
|
+
/**
|
|
250
|
+
* Helper function to extract context from HTTP request
|
|
251
|
+
*/
|
|
252
|
+
function extractContextFromRequest(req) {
|
|
253
|
+
const context = {};
|
|
254
|
+
if (req.user) {
|
|
255
|
+
context.actorId = req.user.user_id;
|
|
256
|
+
context.workspaceId = req.user.workspace_id;
|
|
257
|
+
context.tenantId = req.user.tenant_endpoint;
|
|
258
|
+
}
|
|
259
|
+
const getHeader = (key) => {
|
|
260
|
+
const value = req.headers[key.toLowerCase()];
|
|
261
|
+
return Array.isArray(value) ? value[0] : value;
|
|
262
|
+
};
|
|
263
|
+
const authHeader = getHeader("authorization");
|
|
264
|
+
if (authHeader) context.token = authHeader.replace("Bearer ", "");
|
|
265
|
+
const workspaceId = getHeader("x-workspace-id");
|
|
266
|
+
if (workspaceId && !context.workspaceId) context.workspaceId = workspaceId;
|
|
267
|
+
const productId = getHeader("x-product-id");
|
|
268
|
+
if (productId) context.productId = productId;
|
|
269
|
+
const projectId = getHeader("x-project-id");
|
|
270
|
+
if (projectId) context.projectId = projectId;
|
|
271
|
+
const appId = getHeader("x-app-id");
|
|
272
|
+
if (appId) context.appId = appId;
|
|
273
|
+
const cfAccessClientId = getHeader("cf-access-client-id");
|
|
274
|
+
if (cfAccessClientId) context.cfAccessClientId = cfAccessClientId;
|
|
275
|
+
const cfAccessClientSecret = getHeader("cf-access-client-secret");
|
|
276
|
+
if (cfAccessClientSecret) context.cfAccessClientSecret = cfAccessClientSecret;
|
|
277
|
+
const cfAuthorization = getHeader("x-cf-authorization");
|
|
278
|
+
if (cfAuthorization) context.cfAuthorization = cfAuthorization;
|
|
279
|
+
return context;
|
|
280
|
+
}
|
|
245
281
|
|
|
246
|
-
export { ContextManager
|
|
247
|
-
//# sourceMappingURL=
|
|
282
|
+
export { ContextManager, contextManager, extractContextFromRequest };
|
|
283
|
+
//# sourceMappingURL=index.js.map
|