tokensafe-backend-node 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/stdio.cjs ADDED
@@ -0,0 +1,1211 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
18
+ // If the importer is in node compatibility mode or this is not an ESM
19
+ // file that has been converted to a CommonJS file using a Babel-
20
+ // compatible transform (i.e. "__esModule" has not been set), then set
21
+ // "default" to the CommonJS "module.exports" for node compatibility.
22
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
23
+ mod
24
+ ));
25
+
26
+ // src/stdio.ts
27
+ var import_node_path4 = __toESM(require("path"), 1);
28
+ var import_node_url = require("url");
29
+
30
+ // src/runtime.ts
31
+ var import_node_crypto2 = __toESM(require("crypto"), 1);
32
+ var import_node_fs2 = __toESM(require("fs"), 1);
33
+ var import_node_http = __toESM(require("http"), 1);
34
+ var import_node_path2 = __toESM(require("path"), 1);
35
+ var import_parser = require("@babel/parser");
36
+
37
+ // src/errors.ts
38
+ var ERROR_CODES = {
39
+ CONFLICT_DETECTED: -32001,
40
+ SYNTAX_ERROR: -32002,
41
+ SECURITY_VIOLATION: -32003,
42
+ TARGET_NOT_FOUND: -32004,
43
+ ACTION_NOT_FOUND: -32005,
44
+ UNSUPPORTED_CAPABILITY: -32006,
45
+ PERMISSION_DENIED: -32007,
46
+ RUNTIME_UNAVAILABLE: -32008,
47
+ RESOURCE_NOT_FOUND: -32009,
48
+ VALIDATION_FAILED: -32011,
49
+ PARSE_ERROR: -32700,
50
+ INVALID_REQUEST: -32600,
51
+ METHOD_NOT_FOUND: -32601,
52
+ INVALID_PARAMS: -32602,
53
+ INTERNAL_ERROR: -32603
54
+ };
55
+ var OumvError = class extends Error {
56
+ code;
57
+ data;
58
+ constructor(code, message, data) {
59
+ super(message);
60
+ this.name = "OumvError";
61
+ this.code = code;
62
+ this.data = data;
63
+ }
64
+ };
65
+ var conflict = (message, data) => new OumvError(ERROR_CODES.CONFLICT_DETECTED, message, data);
66
+ var syntaxError = (message, data) => new OumvError(ERROR_CODES.SYNTAX_ERROR, message, data);
67
+ var securityViolation = (message, data) => new OumvError(ERROR_CODES.SECURITY_VIOLATION, message, data);
68
+ var targetNotFound = (message) => new OumvError(ERROR_CODES.TARGET_NOT_FOUND, message);
69
+ var permissionDenied = (message) => new OumvError(ERROR_CODES.PERMISSION_DENIED, message);
70
+ var resourceNotFound = (message) => new OumvError(ERROR_CODES.RESOURCE_NOT_FOUND, message);
71
+ var validationFailed = (message, data) => new OumvError(ERROR_CODES.VALIDATION_FAILED, message, data);
72
+ var invalidParams = (message) => new OumvError(ERROR_CODES.INVALID_PARAMS, message);
73
+ var unsupported = (message) => new OumvError(ERROR_CODES.UNSUPPORTED_CAPABILITY, message);
74
+
75
+ // src/paths.ts
76
+ var import_node_fs = __toESM(require("fs"), 1);
77
+ var import_node_path = __toESM(require("path"), 1);
78
+ var SENSITIVE = /(^|[\\/])(\.env(\..*)?|id_rsa|id_ed25519|\.npmrc|\.pypirc|credentials\.json|secrets\.ya?ml)$/i;
79
+ function resolveWorkspacePath(inputPath, workspaceDir) {
80
+ let canonicalRoot = import_node_path.default.resolve(workspaceDir);
81
+ try {
82
+ if (import_node_fs.default.existsSync(canonicalRoot)) canonicalRoot = import_node_fs.default.realpathSync(canonicalRoot);
83
+ } catch {
84
+ }
85
+ let resolved = import_node_path.default.isAbsolute(inputPath) ? import_node_path.default.resolve(inputPath) : import_node_path.default.resolve(canonicalRoot, inputPath);
86
+ try {
87
+ if (import_node_fs.default.existsSync(resolved)) resolved = import_node_fs.default.realpathSync(resolved);
88
+ } catch {
89
+ }
90
+ const rootWithSep = canonicalRoot.endsWith(import_node_path.default.sep) ? canonicalRoot : canonicalRoot + import_node_path.default.sep;
91
+ if (resolved !== canonicalRoot && !resolved.startsWith(rootWithSep)) {
92
+ throw securityViolation(`SECURITY_VIOLATION: path traversal blocked: ${JSON.stringify(inputPath)} escapes the workspace`);
93
+ }
94
+ if (SENSITIVE.test(resolved)) {
95
+ throw securityViolation(`SECURITY_VIOLATION: access to a credential file is blocked: ${JSON.stringify(inputPath)}`);
96
+ }
97
+ return resolved;
98
+ }
99
+ function splitSourceTarget(target) {
100
+ const [rawPath, symbol] = target.split("#");
101
+ return { path: rawPath.trim(), symbol: symbol?.trim() || void 0 };
102
+ }
103
+
104
+ // src/sessions.ts
105
+ var import_node_crypto = __toESM(require("crypto"), 1);
106
+ var SessionRegistry = class {
107
+ sessions = /* @__PURE__ */ new Map();
108
+ ttlSeconds;
109
+ constructor(ttlSeconds = 3600) {
110
+ this.ttlSeconds = Math.max(Math.floor(ttlSeconds), 1);
111
+ }
112
+ create() {
113
+ const id = `sess-${import_node_crypto.default.randomBytes(8).toString("hex")}`;
114
+ this.sessions.set(id, Date.now() + this.ttlSeconds * 1e3);
115
+ return id;
116
+ }
117
+ /** Unknown or expired ids are invalid; expiry is enforced on read. */
118
+ validate(id) {
119
+ if (!id) return true;
120
+ const expiresAt = this.sessions.get(id);
121
+ if (expiresAt === void 0) return false;
122
+ if (Date.now() > expiresAt) {
123
+ this.sessions.delete(id);
124
+ return false;
125
+ }
126
+ return true;
127
+ }
128
+ delete(id) {
129
+ if (!id) return false;
130
+ return this.sessions.delete(id);
131
+ }
132
+ count() {
133
+ return this.sessions.size;
134
+ }
135
+ };
136
+
137
+ // src/runtime.ts
138
+ var PROTOCOL_VERSION = "1.1.0";
139
+ var OBSERVE_LEVELS = ["L0", "L1", "L2", "L3", "L4"];
140
+ var MAX_TRACES = 128;
141
+ function sha256(content) {
142
+ return "sha256:" + import_node_crypto2.default.createHash("sha256").update(content, "utf-8").digest("hex");
143
+ }
144
+ function intersect(implemented, requested) {
145
+ if (!Array.isArray(requested) || requested.length === 0) return implemented;
146
+ const wanted = new Set(requested.map(String));
147
+ return implemented.filter((item) => wanted.has(item));
148
+ }
149
+ var OumvRuntime = class {
150
+ name;
151
+ version;
152
+ workspaceDir;
153
+ transportPath;
154
+ maxBodyBytes;
155
+ sessions;
156
+ authToken;
157
+ routes = /* @__PURE__ */ new Map();
158
+ traces = [];
159
+ startTime = Date.now();
160
+ enabled;
161
+ transports = ["http"];
162
+ handler;
163
+ dispatchServer;
164
+ dispatchPort = 0;
165
+ constructor(options = {}) {
166
+ this.name = options.name || "tokensafe-node";
167
+ this.version = options.version || "0.2.0";
168
+ this.workspaceDir = import_node_path2.default.resolve(options.workspaceDir || process.cwd());
169
+ this.transportPath = options.transportPath || "/__oumv/rpc";
170
+ this.maxBodyBytes = options.maxBodyBytes ?? 8 * 1024 * 1024;
171
+ this.authToken = options.authToken || "";
172
+ this.sessions = new SessionRegistry(options.sessionTtlSeconds ?? 3600);
173
+ this.handler = options.handler;
174
+ this.enabled = {
175
+ observe: options.capabilities?.observe ?? true,
176
+ understand: options.capabilities?.understand ?? true,
177
+ mutate: options.capabilities?.mutate ?? true,
178
+ verify: options.capabilities?.verify ?? true
179
+ };
180
+ }
181
+ /* ---------------------------------------------------------------- registry */
182
+ registerRoute(method, routePath, handlerName = "handler", middlewares = []) {
183
+ const key = `${method.toUpperCase()} ${routePath}`;
184
+ if (this.routes.has(key)) return;
185
+ this.routes.set(key, {
186
+ method: method.toUpperCase(),
187
+ path: routePath,
188
+ handlerName,
189
+ ...middlewares.length > 0 ? { middlewares } : {}
190
+ });
191
+ }
192
+ listRoutes() {
193
+ return Array.from(this.routes.values());
194
+ }
195
+ /** Records an executed request: the only source of L4/causality evidence. */
196
+ recordTrace(entry) {
197
+ this.traces.push({ ...entry, timestamp: entry.timestamp ?? (/* @__PURE__ */ new Date()).toISOString() });
198
+ if (this.traces.length > MAX_TRACES) this.traces.shift();
199
+ }
200
+ recentTraces() {
201
+ return this.traces.slice();
202
+ }
203
+ setHandler(handler) {
204
+ this.handler = handler;
205
+ }
206
+ setTransports(transports) {
207
+ this.transports = transports;
208
+ }
209
+ /* --------------------------------------------------------------- handshake */
210
+ handshake(params = {}) {
211
+ const capabilities = {
212
+ observe: { levels: [...OBSERVE_LEVELS], formats: ["json"] },
213
+ understand: { causality: true, signalsGraph: false, impactAnalysis: true },
214
+ mutate: { occ: true, syntaxGuard: true },
215
+ verify: { multiMetric: true, surfaceDiff: false }
216
+ };
217
+ if (!this.enabled.understand) {
218
+ capabilities.understand = { causality: false, signalsGraph: false, impactAnalysis: false };
219
+ }
220
+ if (!this.enabled.mutate) capabilities.mutate = { occ: false, syntaxGuard: false };
221
+ if (!this.enabled.verify) capabilities.verify = { multiMetric: false, surfaceDiff: false };
222
+ const requested = params.requestedCapabilities;
223
+ if (requested && typeof requested === "object") {
224
+ capabilities.observe.levels = intersect(capabilities.observe.levels, requested.observe?.levels);
225
+ capabilities.observe.formats = intersect(capabilities.observe.formats, requested.observe?.formats);
226
+ }
227
+ if (!this.enabled.observe) capabilities.observe = { levels: [], formats: [] };
228
+ return {
229
+ protocolVersion: PROTOCOL_VERSION,
230
+ profile: "backend",
231
+ sessionId: this.sessions.create(),
232
+ ttlSeconds: this.sessions.ttlSeconds,
233
+ runtimeInfo: { name: this.name, version: this.version },
234
+ capabilities
235
+ };
236
+ }
237
+ /* ----------------------------------------------------------------- observe */
238
+ observe(params = {}) {
239
+ if (!this.enabled.observe) throw permissionDenied("PERMISSION_DENIED: observe capability is disabled");
240
+ const level = String(params.level || "L0").toUpperCase();
241
+ const format = String(params.format || "json").toLowerCase();
242
+ if (!OBSERVE_LEVELS.includes(level)) throw invalidParams(`INVALID_PARAMS: unknown observe level ${level}`);
243
+ if (format !== "json") throw unsupported(`UNSUPPORTED_CAPABILITY: format ${format} is not implemented`);
244
+ switch (level) {
245
+ case "L0": {
246
+ const memory = process.memoryUsage().rss / (1024 * 1024);
247
+ return {
248
+ level,
249
+ format: "json",
250
+ data: {
251
+ status: "HEALTHY",
252
+ uptimeSeconds: Math.floor((Date.now() - this.startTime) / 1e3),
253
+ activeRoutes: this.routes.size,
254
+ errorCount1m: 0,
255
+ memoryAllocMB: Math.round(memory)
256
+ },
257
+ tokenEstimate: 30
258
+ };
259
+ }
260
+ case "L1":
261
+ return {
262
+ level,
263
+ format: "json",
264
+ data: { endpoints: this.listRoutes() },
265
+ tokenEstimate: 30 + this.routes.size * 15
266
+ };
267
+ case "L2": {
268
+ const target = String(params.target || "").trim();
269
+ if (!target) throw invalidParams("INVALID_PARAMS: target is required for L2");
270
+ const route = this.findRoute(target);
271
+ if (!route) throw targetNotFound(`TARGET_NOT_FOUND: no route matches ${JSON.stringify(target)}`);
272
+ return {
273
+ level,
274
+ format: "json",
275
+ data: {
276
+ target,
277
+ method: route.method,
278
+ path: route.path,
279
+ handlerName: route.handlerName,
280
+ middlewares: route.middlewares ?? [],
281
+ // A mounted Express/Fastify router exposes handler names, not DTOs:
282
+ // saying so is honest, inventing schemas is not.
283
+ note: "route contract from live router registration; request/response DTOs are not reflectable \u2014 use observe L3 for handler source",
284
+ evidence: { provenance: "runtime", sourceAdapter: this.name, confidence: "confirmed" }
285
+ },
286
+ tokenEstimate: 80
287
+ };
288
+ }
289
+ case "L3": {
290
+ const target = String(params.target || "").trim();
291
+ if (!target) throw invalidParams("INVALID_PARAMS: target (path or path#symbol) is required for L3");
292
+ const { path: filePath, symbol } = splitSourceTarget(target);
293
+ const source = this.readSource(filePath, symbol);
294
+ return {
295
+ level,
296
+ format: "json",
297
+ data: source,
298
+ tokenEstimate: Math.ceil(source.source.length / 4)
299
+ };
300
+ }
301
+ case "L4": {
302
+ const target = String(params.target || "").trim();
303
+ const traces = target ? this.traces.filter((trace) => matchesTarget(trace, target)) : this.recentTraces();
304
+ return {
305
+ level,
306
+ format: "json",
307
+ data: {
308
+ ...target ? { target } : {},
309
+ traces,
310
+ traceCount: traces.length,
311
+ ...traces.length === 0 ? { note: "no request has been executed for this target yet \u2014 verify or instrument the app first" } : {},
312
+ evidence: {
313
+ provenance: "runtime",
314
+ sourceAdapter: this.name,
315
+ confidence: traces.length > 0 ? "confirmed" : "unknown"
316
+ }
317
+ },
318
+ tokenEstimate: 40 + traces.length * 12
319
+ };
320
+ }
321
+ }
322
+ }
323
+ /* -------------------------------------------------------------- understand */
324
+ understand(params = {}) {
325
+ if (!this.enabled.understand) throw permissionDenied("PERMISSION_DENIED: understand capability is disabled");
326
+ const query = String(params.query || "causality");
327
+ const target = String(params.target || "").trim();
328
+ if (query === "impact") {
329
+ if (!target) throw invalidParams("INVALID_PARAMS: target is required for impact");
330
+ const route = this.findRoute(target);
331
+ const affected = route?.handlerName ? [route.handlerName] : [];
332
+ return {
333
+ query: "impact",
334
+ target,
335
+ impact: {
336
+ target,
337
+ affectedSymbols: affected,
338
+ breakingRisk: route ? "LOW" : "UNKNOWN",
339
+ summary: route ? `impact derived from the registered route table for ${route.method} ${route.path}` : "no matching route; impact cannot be derived from registration data",
340
+ observed: false,
341
+ evidence: {
342
+ provenance: "static",
343
+ sourceAdapter: this.name,
344
+ confidence: route ? "probable" : "unknown"
345
+ }
346
+ }
347
+ };
348
+ }
349
+ if (query === "causality" || query === "why_state") {
350
+ const matching = target ? this.traces.filter((trace) => matchesTarget(trace, target)) : this.recentTraces();
351
+ const newest = matching[matching.length - 1];
352
+ if (!newest) {
353
+ return {
354
+ query: "causality",
355
+ target,
356
+ causality: {
357
+ target,
358
+ observed: false,
359
+ traceCount: 0,
360
+ traceChain: [],
361
+ rootCause: "",
362
+ note: "no execution trace for this target yet \u2014 run oumv/verify or serve a request first",
363
+ evidence: { provenance: "static", sourceAdapter: this.name, confidence: "unknown" }
364
+ }
365
+ };
366
+ }
367
+ return {
368
+ query: "causality",
369
+ target,
370
+ causality: {
371
+ target,
372
+ observed: true,
373
+ traceCount: matching.length,
374
+ traceChain: matching.slice(-5).map((trace) => ({
375
+ method: trace.method,
376
+ path: trace.path,
377
+ statusCode: trace.statusCode,
378
+ durationMs: trace.durationMs,
379
+ timestamp: trace.timestamp
380
+ })),
381
+ statusCode: newest.statusCode,
382
+ latencyMs: newest.durationMs,
383
+ rootCause: `${newest.method} ${newest.path} -> ${newest.statusCode}`,
384
+ evidence: { provenance: "runtime", sourceAdapter: this.name, confidence: "confirmed" }
385
+ }
386
+ };
387
+ }
388
+ throw unsupported(`UNSUPPORTED_CAPABILITY: understand query ${query}`);
389
+ }
390
+ /* ------------------------------------------------------------ source & edits */
391
+ getSource(params = {}) {
392
+ const filePath = String(params.path ?? params.filePath ?? "").trim();
393
+ if (!filePath) throw invalidParams("INVALID_PARAMS: path is required");
394
+ return this.readSource(filePath, params.symbol ? String(params.symbol) : void 0);
395
+ }
396
+ readSource(filePath, symbol) {
397
+ const resolved = resolveWorkspacePath(filePath, this.workspaceDir);
398
+ if (!import_node_fs2.default.existsSync(resolved) || !import_node_fs2.default.statSync(resolved).isFile()) {
399
+ throw resourceNotFound(`RESOURCE_NOT_FOUND: ${filePath}`);
400
+ }
401
+ const full = import_node_fs2.default.readFileSync(resolved, "utf-8");
402
+ const relative = import_node_path2.default.relative(this.workspaceDir, resolved).split(import_node_path2.default.sep).join("/");
403
+ const version = sha256(full);
404
+ if (!symbol) {
405
+ const lines = full.split("\n").length + (full.endsWith("\n") ? 0 : 1);
406
+ return { path: relative, source: full, version, startLine: 1, endLine: lines };
407
+ }
408
+ const range = extractSymbolRange(full, symbol);
409
+ if (!range) throw resourceNotFound(`RESOURCE_NOT_FOUND: symbol ${JSON.stringify(symbol)} not found in ${relative}`);
410
+ return {
411
+ path: relative,
412
+ symbol,
413
+ source: range.source,
414
+ version,
415
+ startLine: range.startLine,
416
+ endLine: range.endLine
417
+ };
418
+ }
419
+ applyEdit(params = {}) {
420
+ if (!this.enabled.mutate) throw permissionDenied("PERMISSION_DENIED: mutate capability is disabled");
421
+ const requestedPath = String(params.path ?? params.filePath ?? "").trim();
422
+ if (!requestedPath) throw invalidParams("INVALID_PARAMS: path is required");
423
+ const resolved = resolveWorkspacePath(requestedPath, this.workspaceDir);
424
+ if (String(params.mode ?? "replace").toLowerCase() === "create") {
425
+ const replacement2 = String(params.replacement ?? params.source ?? "");
426
+ if (!replacement2) throw invalidParams("INVALID_PARAMS: replacement is required for mode=create");
427
+ if (params.expectedVersion) {
428
+ throw validationFailed("VALIDATION_FAILED: expectedVersion must be omitted for mode=create", {
429
+ reason: "create_forbids_version"
430
+ });
431
+ }
432
+ if (import_node_fs2.default.existsSync(resolved)) {
433
+ throw conflict("CONFLICT_DETECTED: file already exists; use mode=replace with its version", {
434
+ reason: "file_exists"
435
+ });
436
+ }
437
+ const syntax2 = checkSyntax(resolved, replacement2);
438
+ import_node_fs2.default.mkdirSync(import_node_path2.default.dirname(resolved), { recursive: true });
439
+ import_node_fs2.default.writeFileSync(resolved, replacement2, "utf-8");
440
+ return {
441
+ status: "APPLIED",
442
+ path: import_node_path2.default.relative(this.workspaceDir, resolved).split(import_node_path2.default.sep).join("/"),
443
+ newVersion: sha256(replacement2),
444
+ syntaxCheck: syntax2,
445
+ created: true
446
+ };
447
+ }
448
+ if (!import_node_fs2.default.existsSync(resolved) || !import_node_fs2.default.statSync(resolved).isFile()) {
449
+ throw resourceNotFound(`RESOURCE_NOT_FOUND: ${requestedPath}`);
450
+ }
451
+ const current = import_node_fs2.default.readFileSync(resolved, "utf-8");
452
+ const replacement = String(params.replacement ?? params.source ?? "");
453
+ if (!replacement) throw invalidParams("INVALID_PARAMS: replacement is required");
454
+ const syntax = checkSyntax(resolved, replacement);
455
+ const expectedVersion = String(params.expectedVersion ?? "").trim();
456
+ if (!expectedVersion) {
457
+ throw validationFailed(
458
+ "VALIDATION_FAILED: expectedVersion is required to edit an existing file \u2014 call oumv/getSource and pass its version",
459
+ { path: requestedPath, current: sha256(current) }
460
+ );
461
+ }
462
+ const currentVersion = sha256(current);
463
+ if (expectedVersion !== currentVersion) {
464
+ throw conflict(`CONFLICT_DETECTED: expected ${expectedVersion}, current is ${currentVersion}`, {
465
+ expected: expectedVersion,
466
+ current: currentVersion
467
+ });
468
+ }
469
+ const backupPath = import_node_path2.default.join(this.workspaceDir, ".tokensafe", "backups", `${Date.now()}-${import_node_path2.default.basename(resolved)}`);
470
+ let backedUp;
471
+ try {
472
+ import_node_fs2.default.mkdirSync(import_node_path2.default.dirname(backupPath), { recursive: true });
473
+ import_node_fs2.default.writeFileSync(backupPath, current, "utf-8");
474
+ backedUp = import_node_path2.default.relative(this.workspaceDir, backupPath).split(import_node_path2.default.sep).join("/");
475
+ } catch {
476
+ backedUp = void 0;
477
+ }
478
+ import_node_fs2.default.writeFileSync(resolved, replacement, "utf-8");
479
+ return {
480
+ status: "APPLIED",
481
+ path: import_node_path2.default.relative(this.workspaceDir, resolved).split(import_node_path2.default.sep).join("/"),
482
+ ...params.symbol ? { symbol: String(params.symbol) } : {},
483
+ newVersion: sha256(replacement),
484
+ syntaxCheck: syntax,
485
+ ...backedUp ? { backupPath: backedUp } : {}
486
+ };
487
+ }
488
+ /* ------------------------------------------------------------------ verify */
489
+ async verify(params = {}) {
490
+ if (!this.enabled.verify) throw permissionDenied("PERMISSION_DENIED: verify capability is disabled");
491
+ const target = String(params.target ?? "").trim();
492
+ if (!target) throw invalidParams('INVALID_PARAMS: target ("METHOD /path") is required');
493
+ if (!this.handler) throw resourceUnavailable("RUNTIME_UNAVAILABLE: no application handler is mounted for verification");
494
+ const { method, url } = parseVerifyTarget(target);
495
+ await this.ensureDispatchServer();
496
+ const body = params.payload === void 0 ? void 0 : JSON.stringify(params.payload);
497
+ const startedAt = process.hrtime.bigint();
498
+ const response = await new Promise((resolve, reject) => {
499
+ const request = import_node_http.default.request(
500
+ {
501
+ host: "127.0.0.1",
502
+ port: this.dispatchPort,
503
+ method,
504
+ path: url,
505
+ headers: {
506
+ "content-type": "application/json",
507
+ ...body ? { "content-length": Buffer.byteLength(body).toString() } : {},
508
+ ...params.headers && typeof params.headers === "object" ? params.headers : {}
509
+ }
510
+ },
511
+ (res) => {
512
+ let data = "";
513
+ res.setEncoding("utf-8");
514
+ res.on("data", (chunk) => data += chunk);
515
+ res.on("end", () => resolve({ statusCode: res.statusCode ?? 0, body: data }));
516
+ }
517
+ );
518
+ request.on("error", reject);
519
+ if (body) request.write(body);
520
+ request.end();
521
+ });
522
+ const durationMs = Number(process.hrtime.bigint() - startedAt) / 1e6;
523
+ const status = response.statusCode < 400 ? "passed" : "failed";
524
+ this.recordTrace({
525
+ method,
526
+ path: url,
527
+ route: url,
528
+ handler: "loopback",
529
+ statusCode: response.statusCode,
530
+ durationMs
531
+ });
532
+ return {
533
+ status,
534
+ target,
535
+ statusCode: response.statusCode,
536
+ diff: { status: response.statusCode, responseBody: response.body },
537
+ timings: { t_action_ms: durationMs, t_total_ms: durationMs },
538
+ durationMs,
539
+ scope: {
540
+ checked: ["loopback HTTP dispatch against the live handler"],
541
+ notExecuted: ["external processes", "persistent database state"],
542
+ notSupported: ["browser/DOM assertions"]
543
+ }
544
+ };
545
+ }
546
+ async ensureDispatchServer() {
547
+ if (this.dispatchServer) return;
548
+ const server = import_node_http.default.createServer((req, res) => this.handler(req, res));
549
+ await new Promise((resolve, reject) => {
550
+ server.once("error", reject);
551
+ server.listen(0, "127.0.0.1", () => resolve());
552
+ });
553
+ const address = server.address();
554
+ this.dispatchPort = typeof address === "object" && address ? address.port : 0;
555
+ this.dispatchServer = server;
556
+ }
557
+ /** Releases the loopback dispatcher (tests, shutdown hooks). */
558
+ async dispose() {
559
+ if (!this.dispatchServer) return;
560
+ const server = this.dispatchServer;
561
+ this.dispatchServer = void 0;
562
+ this.dispatchPort = 0;
563
+ await new Promise((resolve) => server.close(() => resolve()));
564
+ }
565
+ /* ---------------------------------------------------------------- helpers */
566
+ findRoute(target) {
567
+ const trimmed = target.trim();
568
+ const match = trimmed.match(/^([A-Za-z]+)\s+(\S+)$/);
569
+ if (match) {
570
+ const byRoute = this.routes.get(`${match[1].toUpperCase()} ${match[2]}`);
571
+ if (byRoute) return byRoute;
572
+ }
573
+ for (const route of this.routes.values()) {
574
+ if (route.path === trimmed) return route;
575
+ }
576
+ return void 0;
577
+ }
578
+ };
579
+ function matchesTarget(trace, target) {
580
+ const trimmed = target.trim();
581
+ const upper = trimmed.toUpperCase();
582
+ if (`${trace.method} ${trace.path}`.toUpperCase() === upper) return true;
583
+ if (trace.path === trimmed) return true;
584
+ if (trace.route && trace.route === trimmed) return true;
585
+ return trace.path.includes(trimmed) && trimmed.startsWith("/");
586
+ }
587
+ function parseVerifyTarget(target) {
588
+ const match = target.trim().match(/^([A-Za-z]+)\s+(\S+)$/);
589
+ if (match) return { method: match[1].toUpperCase(), url: match[2] };
590
+ return { method: "POST", url: target.trim() };
591
+ }
592
+ function checkSyntax(filePath, source) {
593
+ if (!/\.(c|m)?(t|j)sx?$/.test(filePath)) return { status: "skipped", tool: "none" };
594
+ try {
595
+ (0, import_parser.parse)(source, {
596
+ sourceType: "unambiguous",
597
+ plugins: ["typescript", "jsx", "decorators-legacy"],
598
+ errorRecovery: false
599
+ });
600
+ } catch (error) {
601
+ throw syntaxError(`SYNTAX_ERROR: pre-flight parse failed: ${error.message}`);
602
+ }
603
+ return { status: "passed", tool: "@babel/parser" };
604
+ }
605
+ function extractSymbolRange(source, symbol) {
606
+ const escaped = symbol.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
607
+ const pattern = new RegExp(
608
+ `(?:function\\s+${escaped}\\b|class\\s+${escaped}\\b|(?:const|let|var)\\s+${escaped}\\b|${escaped}\\s*[:=]\\s*(?:async\\s*)?\\(|export\\s+(?:default\\s+)?(?:function|class|const|let)\\s+${escaped}\\b)`
609
+ );
610
+ const match = pattern.exec(source);
611
+ if (!match) return void 0;
612
+ const start = match.index;
613
+ let braceStart = source.indexOf("{", start);
614
+ const arrowEnd = source.indexOf(";", start);
615
+ if (braceStart === -1 || arrowEnd !== -1 && arrowEnd < braceStart) {
616
+ const end2 = arrowEnd === -1 ? source.length : arrowEnd + 1;
617
+ const slice = source.slice(start, end2);
618
+ return {
619
+ source: slice,
620
+ startLine: source.slice(0, start).split("\n").length,
621
+ endLine: source.slice(0, end2).split("\n").length
622
+ };
623
+ }
624
+ let depth = 0;
625
+ let end = braceStart;
626
+ for (let i = braceStart; i < source.length; i += 1) {
627
+ if (source[i] === "{") depth += 1;
628
+ else if (source[i] === "}") {
629
+ depth -= 1;
630
+ if (depth === 0) {
631
+ end = i + 1;
632
+ break;
633
+ }
634
+ }
635
+ }
636
+ return {
637
+ source: source.slice(start, end),
638
+ startLine: source.slice(0, start).split("\n").length,
639
+ endLine: source.slice(0, end).split("\n").length
640
+ };
641
+ }
642
+ function resourceUnavailable(message) {
643
+ return new OumvError(ERROR_CODES.RUNTIME_UNAVAILABLE, message);
644
+ }
645
+
646
+ // src/transport/stdio.ts
647
+ var import_node_readline = __toESM(require("readline"), 1);
648
+
649
+ // src/transport/dispatcher.ts
650
+ var success = (id, result) => ({
651
+ jsonrpc: "2.0",
652
+ id: id ?? null,
653
+ result
654
+ });
655
+ var failure = (id, code, message, data) => ({
656
+ jsonrpc: "2.0",
657
+ id: id ?? null,
658
+ error: { code, message, ...data ? { data } : {} }
659
+ });
660
+ var Dispatcher = class {
661
+ constructor(runtime) {
662
+ this.runtime = runtime;
663
+ }
664
+ runtime;
665
+ async dispatch(request) {
666
+ const id = request?.id ?? null;
667
+ const method = String(request?.method ?? "");
668
+ const params = request?.params ?? {};
669
+ if (!method) return failure(id, ERROR_CODES.INVALID_REQUEST, "INVALID_REQUEST: method is required");
670
+ if (method === "oumv/disconnect") {
671
+ return success(id, { closed: this.runtime.sessions.delete(params.sessionId) });
672
+ }
673
+ if (method !== "oumv/handshake" && method !== "handshake" && params.sessionId) {
674
+ if (!this.runtime.sessions.validate(String(params.sessionId))) {
675
+ return failure(
676
+ id,
677
+ ERROR_CODES.VALIDATION_FAILED,
678
+ "VALIDATION_FAILED: unknown or expired sessionId \u2014 re-run oumv/handshake",
679
+ { reason: "session_expired", sessionId: params.sessionId }
680
+ );
681
+ }
682
+ }
683
+ try {
684
+ switch (method) {
685
+ case "oumv/handshake":
686
+ case "handshake":
687
+ return success(id, this.runtime.handshake(params));
688
+ case "oumv/observe":
689
+ return success(id, this.runtime.observe(params));
690
+ case "oumv/understand":
691
+ return success(id, this.runtime.understand(params));
692
+ case "oumv/getSource":
693
+ return success(id, this.runtime.getSource(params));
694
+ case "oumv/applyEdit":
695
+ return success(id, this.runtime.applyEdit(params));
696
+ case "oumv/verify":
697
+ return success(id, await this.runtime.verify(params));
698
+ default:
699
+ return failure(id, ERROR_CODES.METHOD_NOT_FOUND, `METHOD_NOT_FOUND: ${method}`);
700
+ }
701
+ } catch (error) {
702
+ if (error instanceof OumvError) {
703
+ return failure(id, error.code, error.message, error.data);
704
+ }
705
+ return failure(id, ERROR_CODES.INTERNAL_ERROR, `INTERNAL_ERROR: ${error?.message ?? String(error)}`);
706
+ }
707
+ }
708
+ };
709
+ function parsePayload(raw) {
710
+ let parsed;
711
+ try {
712
+ parsed = JSON.parse(raw);
713
+ } catch (error) {
714
+ throw new OumvError(ERROR_CODES.PARSE_ERROR, `Parse error: ${error.message}`);
715
+ }
716
+ if (Array.isArray(parsed)) {
717
+ if (parsed.length === 0) throw invalidParams("INVALID_REQUEST: empty batch");
718
+ return parsed;
719
+ }
720
+ if (!parsed || typeof parsed !== "object") {
721
+ throw invalidParams("INVALID_REQUEST: body must be a JSON-RPC object or array");
722
+ }
723
+ return parsed;
724
+ }
725
+ async function dispatchAll(dispatcher, payload) {
726
+ if (!Array.isArray(payload)) {
727
+ const response = await dispatcher.dispatch(payload);
728
+ if (payload.id === void 0 && !response.error) {
729
+ return response;
730
+ }
731
+ return response;
732
+ }
733
+ const responses = [];
734
+ for (const item of payload) {
735
+ if (!item || typeof item !== "object") {
736
+ responses.push(failure(null, ERROR_CODES.INVALID_REQUEST, "INVALID_REQUEST: batch entries must be objects"));
737
+ continue;
738
+ }
739
+ const response = await dispatcher.dispatch(item);
740
+ if (item.id === void 0 && !response.error) continue;
741
+ responses.push(response);
742
+ }
743
+ return responses;
744
+ }
745
+
746
+ // src/transport/stdio.ts
747
+ var isNotification = (request) => Boolean(request) && typeof request === "object" && request.id === void 0;
748
+ function attachStdio(runtime, options = {}) {
749
+ const dispatcher = new Dispatcher(runtime);
750
+ const output = options.output ?? process.stdout;
751
+ const input = options.input ?? process.stdin;
752
+ const write = (body) => {
753
+ if (body !== void 0 && body !== null) output.write(JSON.stringify(body) + "\n");
754
+ };
755
+ const handleLine = async (line) => {
756
+ let payload;
757
+ try {
758
+ payload = parsePayload(line);
759
+ } catch (error) {
760
+ write(failure(null, error?.code ?? -32700, error?.message ?? "Parse error"));
761
+ return;
762
+ }
763
+ if (Array.isArray(payload)) {
764
+ const responses = [];
765
+ for (const request of payload) {
766
+ const response = await dispatcher.dispatch(request);
767
+ if (!isNotification(request)) responses.push(response);
768
+ }
769
+ if (responses.length > 0) write(responses);
770
+ return;
771
+ }
772
+ if (isNotification(payload)) {
773
+ await dispatcher.dispatch(payload);
774
+ return;
775
+ }
776
+ write(await dispatcher.dispatch(payload));
777
+ };
778
+ const rl = import_node_readline.default.createInterface({ input, crlfDelay: Infinity });
779
+ let queue = Promise.resolve();
780
+ rl.on("line", (line) => {
781
+ const trimmed = line.trim();
782
+ if (!trimmed) return;
783
+ queue = queue.then(() => handleLine(trimmed)).catch((error) => {
784
+ process.stderr.write(`tokensafe-oumv-stdio: ${error?.stack ?? error}
785
+ `);
786
+ });
787
+ });
788
+ return { close: () => rl.close() };
789
+ }
790
+
791
+ // src/descriptor.ts
792
+ var import_node_crypto3 = __toESM(require("crypto"), 1);
793
+ var import_node_fs3 = __toESM(require("fs"), 1);
794
+ var import_node_os = __toESM(require("os"), 1);
795
+ var import_node_path3 = __toESM(require("path"), 1);
796
+ function descriptorPath(workspaceDir, home) {
797
+ const root = process.env.TOKENSAFE_HOME || home || import_node_path3.default.join(import_node_os.default.homedir(), ".tokensafe");
798
+ const canonical = import_node_fs3.default.existsSync(workspaceDir) ? import_node_fs3.default.realpathSync(workspaceDir) : import_node_path3.default.resolve(workspaceDir);
799
+ const digest = import_node_crypto3.default.createHash("sha256").update(canonical).digest("hex").slice(0, 16);
800
+ return import_node_path3.default.join(root, "runtimes", `${digest}.json`);
801
+ }
802
+ function readRegistry(file) {
803
+ try {
804
+ const raw = import_node_fs3.default.readFileSync(file, "utf-8");
805
+ const parsed = JSON.parse(raw);
806
+ return parsed && typeof parsed === "object" ? parsed : {};
807
+ } catch {
808
+ return {};
809
+ }
810
+ }
811
+ function writeRegistry(file, registry) {
812
+ import_node_fs3.default.writeFileSync(file, JSON.stringify(registry, null, 2) + "\n", { encoding: "utf-8", mode: 384 });
813
+ import_node_fs3.default.chmodSync(file, 384);
814
+ }
815
+ function writeDescriptor(workspaceDir, descriptor, home) {
816
+ const file = descriptorPath(workspaceDir, home);
817
+ import_node_fs3.default.mkdirSync(import_node_path3.default.dirname(file), { recursive: true });
818
+ const registry = readRegistry(file);
819
+ registry.backend = descriptor;
820
+ registry.workspaceRoot = import_node_fs3.default.existsSync(workspaceDir) ? import_node_fs3.default.realpathSync(workspaceDir) : import_node_path3.default.resolve(workspaceDir);
821
+ registry.pid = process.pid;
822
+ registry.updatedAt = Date.now();
823
+ writeRegistry(file, registry);
824
+ return file;
825
+ }
826
+ function deleteDescriptor(workspaceDir, home) {
827
+ const file = descriptorPath(workspaceDir, home);
828
+ const registry = readRegistry(file);
829
+ if (Object.keys(registry).length === 0) return;
830
+ delete registry.backend;
831
+ if (registry.frontend) {
832
+ writeRegistry(file, registry);
833
+ return;
834
+ }
835
+ try {
836
+ import_node_fs3.default.unlinkSync(file);
837
+ } catch {
838
+ }
839
+ }
840
+
841
+ // src/transport/http.ts
842
+ function isAuthorized(req, token, requireAuth) {
843
+ const provided = String(
844
+ req.headers["x-oumv-session-token"] ?? (typeof req.headers.authorization === "string" && req.headers.authorization.toLowerCase().startsWith("bearer ") ? req.headers.authorization.slice(7).trim() : "") ?? ""
845
+ );
846
+ if (!token) return !requireAuth;
847
+ if (provided) return provided === token;
848
+ return !requireAuth;
849
+ }
850
+ function createHttpHandler(options) {
851
+ const runtime = options.runtime;
852
+ const dispatcher = new Dispatcher(runtime);
853
+ const token = options.authToken ?? runtime.authToken ?? "";
854
+ const maxBodyBytes = options.maxBodyBytes ?? runtime.maxBodyBytes;
855
+ return async function handle(req, res) {
856
+ const pathname = String(req.originalUrl ?? req.url ?? "").split("?")[0];
857
+ if (pathname !== runtime.transportPath) return false;
858
+ res.setHeader("Access-Control-Allow-Origin", "*");
859
+ res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, X-OUMV-Session-Token");
860
+ res.setHeader("Access-Control-Allow-Methods", "POST, OPTIONS");
861
+ if (req.method === "OPTIONS") {
862
+ res.statusCode = 204;
863
+ res.end();
864
+ return true;
865
+ }
866
+ if (req.method !== "POST") {
867
+ res.statusCode = 405;
868
+ res.setHeader("Content-Type", "application/json");
869
+ res.end(JSON.stringify({ error: "Method not allowed" }));
870
+ return true;
871
+ }
872
+ if (!isAuthorized(req, token, Boolean(options.requireAuth))) {
873
+ res.statusCode = 401;
874
+ res.setHeader("Content-Type", "application/json");
875
+ res.end(JSON.stringify(failure(null, ERROR_CODES.PERMISSION_DENIED, "PERMISSION_DENIED: invalid OUMV session token")));
876
+ return true;
877
+ }
878
+ const preParsed = req.body;
879
+ const chunks = [];
880
+ let size = 0;
881
+ if (preParsed === void 0) {
882
+ for await (const chunk of req) {
883
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
884
+ size += buffer.length;
885
+ if (size > maxBodyBytes) {
886
+ res.statusCode = 413;
887
+ res.setHeader("Content-Type", "application/json");
888
+ res.end(JSON.stringify(failure(null, ERROR_CODES.INVALID_REQUEST, "INVALID_REQUEST: body too large")));
889
+ return true;
890
+ }
891
+ chunks.push(buffer);
892
+ }
893
+ }
894
+ res.setHeader("Content-Type", "application/json");
895
+ try {
896
+ const payload = preParsed !== void 0 && typeof preParsed === "object" ? preParsed : parsePayload(Buffer.concat(chunks).toString("utf-8"));
897
+ const response = await dispatchAll(dispatcher, payload);
898
+ res.statusCode = 200;
899
+ res.end(JSON.stringify(response));
900
+ } catch (error) {
901
+ res.statusCode = 200;
902
+ res.end(
903
+ JSON.stringify(
904
+ failure(null, error?.code ?? ERROR_CODES.INTERNAL_ERROR, error?.message ?? "INTERNAL_ERROR: unreadable body")
905
+ )
906
+ );
907
+ }
908
+ return true;
909
+ };
910
+ }
911
+
912
+ // src/transport/sse.ts
913
+ function createSseHandler(options) {
914
+ const runtime = options.runtime;
915
+ const heartbeatMs = options.heartbeatMs ?? 15e3;
916
+ const pollMs = options.pollMs ?? 300;
917
+ const eventsPath = runtime.transportPath.replace(/\/rpc$/, "/events");
918
+ const token = options.authToken ?? runtime.authToken ?? "";
919
+ return async function handle(req, res) {
920
+ const pathname = String(req.originalUrl ?? req.url ?? "").split("?")[0];
921
+ if (pathname !== eventsPath) return false;
922
+ if (req.method !== "GET") {
923
+ res.statusCode = 405;
924
+ res.end(JSON.stringify({ error: "SSE requires GET" }));
925
+ return true;
926
+ }
927
+ if (!isAuthorized(req, token, Boolean(options.requireAuth))) {
928
+ res.statusCode = 401;
929
+ res.setHeader("Content-Type", "application/json");
930
+ res.end(JSON.stringify({ jsonrpc: "2.0", id: null, error: { code: -32007, message: "PERMISSION_DENIED" } }));
931
+ return true;
932
+ }
933
+ res.writeHead(200, {
934
+ "Content-Type": "text/event-stream",
935
+ "Cache-Control": "no-cache",
936
+ Connection: "keep-alive",
937
+ "X-Accel-Buffering": "no"
938
+ });
939
+ res.write(": connected\n\n");
940
+ let cursor = Number.parseInt(String(req.headers["last-event-id"] ?? "0"), 10);
941
+ if (!Number.isFinite(cursor) || cursor < 0) cursor = 0;
942
+ const flush = () => {
943
+ const traces = runtime.recentTraces();
944
+ for (let index = cursor; index < traces.length; index += 1) {
945
+ res.write(`id: ${index + 1}
946
+ event: trace
947
+ data: ${JSON.stringify(traces[index])}
948
+
949
+ `);
950
+ }
951
+ cursor = traces.length;
952
+ };
953
+ flush();
954
+ const poll = setInterval(flush, pollMs);
955
+ const heartbeat = setInterval(() => {
956
+ res.write(`event: heartbeat
957
+ data: ${JSON.stringify((/* @__PURE__ */ new Date()).toISOString())}
958
+
959
+ `);
960
+ }, heartbeatMs);
961
+ const stop = () => {
962
+ clearInterval(poll);
963
+ clearInterval(heartbeat);
964
+ res.end();
965
+ };
966
+ req.on("close", stop);
967
+ return true;
968
+ };
969
+ }
970
+
971
+ // src/transport/ws.ts
972
+ var import_ws = require("ws");
973
+ function attachWebSocket(server, options) {
974
+ const runtime = options.runtime;
975
+ const token = options.authToken ?? runtime.authToken ?? "";
976
+ const dispatcher = new Dispatcher(runtime);
977
+ const wss = new import_ws.WebSocketServer({ noServer: true });
978
+ const sessions = /* @__PURE__ */ new WeakMap();
979
+ const onUpgrade = (req, socket, head) => {
980
+ const pathname = String(req.url || "").split("?")[0];
981
+ if (pathname !== runtime.transportPath) return;
982
+ if (!isAuthorized(req, token, Boolean(options.requireAuth))) {
983
+ socket.write("HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n");
984
+ socket.destroy();
985
+ return;
986
+ }
987
+ wss.handleUpgrade(req, socket, head, (ws) => wss.emit("connection", ws, req));
988
+ };
989
+ server.on("upgrade", onUpgrade);
990
+ wss.on("connection", (ws) => {
991
+ ws.on("message", async (raw) => {
992
+ let payload;
993
+ try {
994
+ payload = JSON.parse(String(raw));
995
+ } catch (error) {
996
+ ws.send(JSON.stringify(failure(null, -32700, `Parse error: ${error.message}`)));
997
+ return;
998
+ }
999
+ const isNotification2 = !Array.isArray(payload) && payload && typeof payload === "object" && payload.id === void 0;
1000
+ const response = await dispatchAll(dispatcher, payload);
1001
+ if (isNotification2 && !Array.isArray(payload) && !response.error) return;
1002
+ if (Array.isArray(payload) && Array.isArray(response) && response.length === 0) return;
1003
+ ws.send(JSON.stringify(response));
1004
+ if (!Array.isArray(payload) && payload?.method === "oumv/handshake") {
1005
+ const sessionId = response?.result?.sessionId;
1006
+ if (sessionId) sessions.set(ws, sessionId);
1007
+ }
1008
+ });
1009
+ ws.on("close", () => {
1010
+ const sessionId = sessions.get(ws);
1011
+ if (sessionId) runtime.sessions.delete(sessionId);
1012
+ sessions.delete(ws);
1013
+ });
1014
+ });
1015
+ return {
1016
+ close: () => new Promise((resolve) => {
1017
+ server.off("upgrade", onUpgrade);
1018
+ for (const client of wss.clients) client.terminate();
1019
+ wss.close(() => resolve());
1020
+ })
1021
+ };
1022
+ }
1023
+
1024
+ // src/adapters/express.ts
1025
+ function collectExpressRoutes(app) {
1026
+ const anyApp = app;
1027
+ let stack = [];
1028
+ try {
1029
+ stack = anyApp._router?.stack ?? [];
1030
+ } catch {
1031
+ }
1032
+ if (stack.length === 0) {
1033
+ try {
1034
+ stack = anyApp.router?.stack ?? [];
1035
+ } catch {
1036
+ }
1037
+ }
1038
+ const routes = [];
1039
+ for (const layer of stack) {
1040
+ if (layer.route) {
1041
+ const methods = Object.keys(layer.route.methods ?? {}).filter((m) => layer.route.methods[m]);
1042
+ const handlerName = layer.route.stack?.find((entry) => entry?.name && entry.name !== "router")?.name;
1043
+ for (const method of methods) {
1044
+ routes.push({ method: method.toUpperCase(), path: layer.route.path, handlerName });
1045
+ }
1046
+ }
1047
+ }
1048
+ return routes;
1049
+ }
1050
+ function mountTokensafe(app, options = {}) {
1051
+ const runtime = options.runtime ?? new OumvRuntime({
1052
+ ...options,
1053
+ workspaceDir: options.workspaceDir ?? process.cwd(),
1054
+ handler: app
1055
+ });
1056
+ for (const route of collectExpressRoutes(app)) {
1057
+ runtime.registerRoute(route.method, route.path, route.handlerName);
1058
+ }
1059
+ runtime.setHandler(app);
1060
+ const httpHandler = createHttpHandler({ runtime, authToken: options.authToken, requireAuth: options.requireAuth });
1061
+ const sseHandler = createSseHandler({ runtime, authToken: options.authToken, requireAuth: options.requireAuth });
1062
+ app.use(runtime.transportPath, (req, res, next) => {
1063
+ void httpHandler(req, res).then((handled) => {
1064
+ if (!handled) next();
1065
+ });
1066
+ });
1067
+ const eventsPath = runtime.transportPath.replace(/\/rpc$/, "/events");
1068
+ app.use(eventsPath, (req, res, next) => {
1069
+ void sseHandler(req, res).then((handled) => {
1070
+ if (!handled) next();
1071
+ });
1072
+ });
1073
+ runtime.setTransports(["http", "sse"]);
1074
+ if (options.publicUrl && options.descriptor !== false) {
1075
+ writeDescriptor(runtime.workspaceDir, {
1076
+ type: "backend",
1077
+ name: runtime.name,
1078
+ version: runtime.version,
1079
+ url: options.publicUrl,
1080
+ ...options.authToken ? { sessionToken: options.authToken } : {},
1081
+ workspace: runtime.workspaceDir,
1082
+ capabilities: { observeLevels: ["L0", "L1", "L2", "L3", "L4"], transports: ["http", "sse"] },
1083
+ startedAt: (/* @__PURE__ */ new Date()).toISOString()
1084
+ });
1085
+ }
1086
+ return {
1087
+ runtime,
1088
+ attachWebSocket: (server) => {
1089
+ const attachment = attachWebSocket(server, { runtime, authToken: options.authToken, requireAuth: options.requireAuth });
1090
+ runtime.setTransports(["http", "sse", "ws"]);
1091
+ return attachment;
1092
+ },
1093
+ dispose: async () => {
1094
+ await runtime.dispose();
1095
+ deleteDescriptor(runtime.workspaceDir);
1096
+ }
1097
+ };
1098
+ }
1099
+
1100
+ // src/adapters/fastify.ts
1101
+ async function registerTokensafe(fastify, options = {}) {
1102
+ const runtime = options.runtime ?? new OumvRuntime({
1103
+ ...options,
1104
+ workspaceDir: options.workspaceDir ?? process.cwd()
1105
+ });
1106
+ const eventsPath = runtime.transportPath.replace(/\/rpc$/, "/events");
1107
+ fastify.addHook("onRoute", (route) => {
1108
+ if (route.url === runtime.transportPath || route.url === eventsPath) return;
1109
+ const methods = Array.isArray(route.method) ? route.method : [route.method];
1110
+ for (const method of methods) {
1111
+ if (String(method).toUpperCase() === "HEAD") continue;
1112
+ runtime.registerRoute(String(method), route.url, route.handler?.name);
1113
+ }
1114
+ });
1115
+ runtime.setHandler((req, res) => {
1116
+ fastify.routing(req, res);
1117
+ });
1118
+ const httpHandler = createHttpHandler({ runtime, authToken: options.authToken, requireAuth: options.requireAuth });
1119
+ const sseHandler = createSseHandler({ runtime, authToken: options.authToken, requireAuth: options.requireAuth });
1120
+ const bridge = (handler) => async (request, reply) => {
1121
+ if (request.body !== void 0) request.raw.body = request.body;
1122
+ const handled = await handler(request.raw, reply.raw);
1123
+ if (!handled) {
1124
+ reply.callNotFound();
1125
+ return reply;
1126
+ }
1127
+ return reply;
1128
+ };
1129
+ fastify.route({
1130
+ method: ["POST", "OPTIONS"],
1131
+ url: runtime.transportPath,
1132
+ handler: bridge(httpHandler)
1133
+ });
1134
+ fastify.route({
1135
+ method: "GET",
1136
+ url: eventsPath,
1137
+ handler: bridge(sseHandler)
1138
+ });
1139
+ runtime.setTransports(["http", "sse"]);
1140
+ if (options.publicUrl && options.descriptor !== false) {
1141
+ writeDescriptor(runtime.workspaceDir, {
1142
+ type: "backend",
1143
+ name: runtime.name,
1144
+ version: runtime.version,
1145
+ url: options.publicUrl,
1146
+ ...options.authToken ? { sessionToken: options.authToken } : {},
1147
+ workspace: runtime.workspaceDir,
1148
+ capabilities: { observeLevels: ["L0", "L1", "L2", "L3", "L4"], transports: ["http", "sse"] },
1149
+ startedAt: (/* @__PURE__ */ new Date()).toISOString()
1150
+ });
1151
+ }
1152
+ return {
1153
+ runtime,
1154
+ attachWebSocket: () => {
1155
+ const attachment = attachWebSocket(fastify.server, {
1156
+ runtime,
1157
+ authToken: options.authToken,
1158
+ requireAuth: options.requireAuth
1159
+ });
1160
+ runtime.setTransports(["http", "sse", "ws"]);
1161
+ return attachment;
1162
+ },
1163
+ dispose: async () => {
1164
+ await runtime.dispose();
1165
+ deleteDescriptor(runtime.workspaceDir);
1166
+ }
1167
+ };
1168
+ }
1169
+
1170
+ // src/stdio.ts
1171
+ var flag = (name) => {
1172
+ const index = process.argv.indexOf(name);
1173
+ return index > -1 ? process.argv[index + 1] : void 0;
1174
+ };
1175
+ var isFastify = (value) => Boolean(value) && typeof value.ready === "function" && typeof value.inject === "function" && typeof value.register === "function";
1176
+ var main = async () => {
1177
+ const appPath = flag("--app");
1178
+ const configuredWorkspace = flag("--workspace") || process.env.TOKENSAFE_WORKSPACE;
1179
+ const workspaceDir = import_node_path4.default.resolve(
1180
+ configuredWorkspace || (appPath ? import_node_path4.default.dirname(import_node_path4.default.resolve(appPath)) : process.cwd())
1181
+ );
1182
+ let runtime;
1183
+ if (appPath) {
1184
+ const module2 = await import((0, import_node_url.pathToFileURL)(import_node_path4.default.resolve(appPath)).href);
1185
+ const app = module2.default ?? module2.app ?? module2;
1186
+ if (isFastify(app)) {
1187
+ runtime = new OumvRuntime({ workspaceDir });
1188
+ await registerTokensafe(app, { runtime });
1189
+ await app.ready();
1190
+ } else {
1191
+ runtime = mountTokensafe(app, { workspaceDir }).runtime;
1192
+ }
1193
+ } else {
1194
+ runtime = new OumvRuntime({ workspaceDir });
1195
+ }
1196
+ runtime.setTransports(["stdio"]);
1197
+ const attachment = attachStdio(runtime);
1198
+ const shutdown = async () => {
1199
+ attachment.close();
1200
+ await runtime.dispose();
1201
+ process.exit(0);
1202
+ };
1203
+ process.on("SIGINT", () => void shutdown());
1204
+ process.on("SIGTERM", () => void shutdown());
1205
+ };
1206
+ void main().catch((error) => {
1207
+ process.stderr.write(`tokensafe-oumv-stdio: ${error?.stack ?? error}
1208
+ `);
1209
+ process.exit(1);
1210
+ });
1211
+ //# sourceMappingURL=stdio.cjs.map