@launchsecure/launch-kit 0.0.3 → 0.0.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.
@@ -0,0 +1,1764 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/server/chart-serve.ts
31
+ var chart_serve_exports = {};
32
+ __export(chart_serve_exports, {
33
+ runServeCli: () => runServeCli,
34
+ startChartServer: () => startChartServer
35
+ });
36
+ module.exports = __toCommonJS(chart_serve_exports);
37
+ var import_node_http = __toESM(require("node:http"));
38
+ var import_node_fs7 = __toESM(require("node:fs"));
39
+ var import_node_path7 = __toESM(require("node:path"));
40
+
41
+ // src/server/graph/index.ts
42
+ var import_node_fs5 = require("node:fs");
43
+ var import_node_path5 = require("node:path");
44
+
45
+ // src/server/graph/parsers/ui/react-nextjs.ts
46
+ var import_node_fs2 = require("node:fs");
47
+ var import_node_path2 = require("node:path");
48
+
49
+ // src/server/graph/core/ast-helpers.ts
50
+ var import_node_fs = require("node:fs");
51
+ var import_node_path = require("node:path");
52
+ var tsModule;
53
+ function getTs() {
54
+ if (!tsModule) {
55
+ tsModule = require("typescript");
56
+ }
57
+ return tsModule;
58
+ }
59
+ var HTTP_METHODS = /* @__PURE__ */ new Set(["get", "post", "put", "patch", "delete", "head", "options"]);
60
+ function parseFile(absPath) {
61
+ const ts = getTs();
62
+ const content = (0, import_node_fs.readFileSync)(absPath, "utf-8");
63
+ const ext = (0, import_node_path.extname)(absPath);
64
+ const scriptKind = ext === ".tsx" ? ts.ScriptKind.TSX : ext === ".ts" ? ts.ScriptKind.TS : ext === ".jsx" ? ts.ScriptKind.JSX : ts.ScriptKind.JS;
65
+ const sourceFile = ts.createSourceFile(
66
+ absPath,
67
+ content,
68
+ ts.ScriptTarget.Latest,
69
+ /* setParentNodes */
70
+ true,
71
+ scriptKind
72
+ );
73
+ const exportsSet = /* @__PURE__ */ new Set();
74
+ const exportsOrdered = [];
75
+ let defaultName = null;
76
+ let firstValueExport = null;
77
+ let firstTypeExport = null;
78
+ const imports = [];
79
+ const reExports = [];
80
+ const jsxElements = /* @__PURE__ */ new Set();
81
+ const navigations = [];
82
+ const fetchCalls = [];
83
+ const includeConcat = process.env.LAUNCH_CHART_INCLUDE_CONCAT_FETCHES === "1";
84
+ function addExport(name2, kind) {
85
+ if (!exportsSet.has(name2)) {
86
+ exportsSet.add(name2);
87
+ exportsOrdered.push(name2);
88
+ }
89
+ if (kind === "default") defaultName = name2;
90
+ else if (kind === "value" && !firstValueExport) firstValueExport = name2;
91
+ else if (kind === "type" && !firstTypeExport) firstTypeExport = name2;
92
+ }
93
+ function hasModifier(node, kind) {
94
+ const modifiers = ts.canHaveModifiers(node) ? ts.getModifiers(node) : void 0;
95
+ return modifiers?.some((m) => m.kind === kind) ?? false;
96
+ }
97
+ function extractTargetFromExpression(expr) {
98
+ if (ts.isStringLiteral(expr) || ts.isNoSubstitutionTemplateLiteral(expr)) {
99
+ return { target: expr.text, isTemplate: false };
100
+ }
101
+ if (ts.isTemplateExpression(expr)) {
102
+ return { target: expr.getText(sourceFile), isTemplate: true };
103
+ }
104
+ return null;
105
+ }
106
+ function looksLikeUrl(s) {
107
+ return s.startsWith("/") || /^(https?:)?\/\//i.test(s);
108
+ }
109
+ function templateStartsWithSlash(expr) {
110
+ const head = expr.head.text;
111
+ return head.startsWith("/");
112
+ }
113
+ function extractUrlFromFetchArg(arg) {
114
+ if (ts.isStringLiteral(arg) || ts.isNoSubstitutionTemplateLiteral(arg)) {
115
+ if (!looksLikeUrl(arg.text)) return null;
116
+ return { url: arg.text, isTemplate: false };
117
+ }
118
+ if (ts.isTemplateExpression(arg)) {
119
+ if (!templateStartsWithSlash(arg)) return null;
120
+ return { url: arg.getText(sourceFile), isTemplate: true };
121
+ }
122
+ if (includeConcat && ts.isBinaryExpression(arg) && arg.operatorToken.kind === ts.SyntaxKind.PlusToken) {
123
+ let leftmost = arg;
124
+ while (ts.isBinaryExpression(leftmost) && leftmost.operatorToken.kind === ts.SyntaxKind.PlusToken) {
125
+ leftmost = leftmost.left;
126
+ }
127
+ if ((ts.isStringLiteral(leftmost) || ts.isNoSubstitutionTemplateLiteral(leftmost)) && leftmost.text.startsWith("/")) {
128
+ return { url: arg.getText(sourceFile), isTemplate: false, isConcat: true };
129
+ }
130
+ }
131
+ return null;
132
+ }
133
+ function visit(node) {
134
+ if (ts.isImportDeclaration(node)) {
135
+ const moduleSpec = node.moduleSpecifier;
136
+ if (ts.isStringLiteral(moduleSpec)) {
137
+ const specifier = moduleSpec.text;
138
+ const clause = node.importClause;
139
+ const isTypeOnly = !!clause?.isTypeOnly;
140
+ const names = [];
141
+ const typeNames = /* @__PURE__ */ new Set();
142
+ if (clause) {
143
+ if (clause.name) names.push(clause.name.text);
144
+ const nb = clause.namedBindings;
145
+ if (nb && ts.isNamedImports(nb)) {
146
+ for (const el of nb.elements) {
147
+ names.push(el.name.text);
148
+ if (el.isTypeOnly) typeNames.add(el.name.text);
149
+ }
150
+ } else if (nb && ts.isNamespaceImport(nb)) {
151
+ names.push(nb.name.text);
152
+ }
153
+ }
154
+ if (names.length > 0 || isTypeOnly) {
155
+ imports.push({ names, specifier, isTypeOnly, typeNames });
156
+ } else if (!clause) {
157
+ imports.push({ names: [], specifier, isTypeOnly: false, typeNames: /* @__PURE__ */ new Set() });
158
+ }
159
+ }
160
+ }
161
+ if (ts.isExportDeclaration(node)) {
162
+ const fromSpec = node.moduleSpecifier && ts.isStringLiteral(node.moduleSpecifier) ? node.moduleSpecifier.text : null;
163
+ if (node.exportClause && ts.isNamedExports(node.exportClause)) {
164
+ for (const el of node.exportClause.elements) {
165
+ const exportedName = el.name.text;
166
+ addExport(exportedName, "value");
167
+ if (fromSpec) {
168
+ reExports.push({ name: exportedName, from: fromSpec });
169
+ }
170
+ }
171
+ } else if (!node.exportClause && fromSpec) {
172
+ reExports.push({ name: "*", from: fromSpec, isWildcard: true });
173
+ }
174
+ }
175
+ if (ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword) {
176
+ const arg = node.arguments[0];
177
+ if (arg && ts.isStringLiteral(arg)) {
178
+ imports.push({
179
+ names: [],
180
+ specifier: arg.text,
181
+ isTypeOnly: false,
182
+ typeNames: /* @__PURE__ */ new Set()
183
+ });
184
+ }
185
+ }
186
+ if (ts.isExportAssignment(node) && !node.isExportEquals) {
187
+ if (ts.isIdentifier(node.expression)) {
188
+ addExport(node.expression.text, "default");
189
+ } else {
190
+ if (!defaultName) defaultName = "default";
191
+ }
192
+ }
193
+ if (ts.isFunctionDeclaration(node) && hasModifier(node, ts.SyntaxKind.ExportKeyword)) {
194
+ const isDefault = hasModifier(node, ts.SyntaxKind.DefaultKeyword);
195
+ if (node.name) addExport(node.name.text, isDefault ? "default" : "value");
196
+ }
197
+ if (ts.isVariableStatement(node) && hasModifier(node, ts.SyntaxKind.ExportKeyword)) {
198
+ for (const decl of node.declarationList.declarations) {
199
+ if (ts.isIdentifier(decl.name)) {
200
+ addExport(decl.name.text, "value");
201
+ }
202
+ }
203
+ }
204
+ if (ts.isClassDeclaration(node) && hasModifier(node, ts.SyntaxKind.ExportKeyword)) {
205
+ const isDefault = hasModifier(node, ts.SyntaxKind.DefaultKeyword);
206
+ if (node.name) addExport(node.name.text, isDefault ? "default" : "value");
207
+ }
208
+ if (ts.isTypeAliasDeclaration(node) && hasModifier(node, ts.SyntaxKind.ExportKeyword)) {
209
+ addExport(node.name.text, "type");
210
+ }
211
+ if (ts.isInterfaceDeclaration(node) && hasModifier(node, ts.SyntaxKind.ExportKeyword)) {
212
+ addExport(node.name.text, "type");
213
+ }
214
+ if (ts.isEnumDeclaration(node) && hasModifier(node, ts.SyntaxKind.ExportKeyword)) {
215
+ addExport(node.name.text, "value");
216
+ }
217
+ if (ts.isJsxOpeningElement(node) || ts.isJsxSelfClosingElement(node)) {
218
+ const tagName = node.tagName;
219
+ if (ts.isIdentifier(tagName) && /^[A-Z]/.test(tagName.text)) {
220
+ jsxElements.add(tagName.text);
221
+ } else if (ts.isPropertyAccessExpression(tagName)) {
222
+ let root = tagName;
223
+ while (ts.isPropertyAccessExpression(root)) root = root.expression;
224
+ if (ts.isIdentifier(root) && /^[A-Z]/.test(root.text)) {
225
+ jsxElements.add(root.text);
226
+ }
227
+ }
228
+ }
229
+ if (ts.isCallExpression(node)) {
230
+ const expr = node.expression;
231
+ if (ts.isPropertyAccessExpression(expr) && ts.isIdentifier(expr.expression) && expr.expression.text === "router" && (expr.name.text === "push" || expr.name.text === "replace")) {
232
+ const arg = node.arguments[0];
233
+ if (arg) {
234
+ const parsed = extractTargetFromExpression(arg);
235
+ if (parsed) {
236
+ navigations.push({
237
+ kind: expr.name.text === "push" ? "router-push" : "router-replace",
238
+ target: parsed.target,
239
+ isTemplate: parsed.isTemplate
240
+ });
241
+ }
242
+ }
243
+ }
244
+ }
245
+ if (ts.isCallExpression(node) && node.arguments.length > 0) {
246
+ const expr = node.expression;
247
+ const firstArg = node.arguments[0];
248
+ if (ts.isIdentifier(expr) && expr.text === "fetch") {
249
+ const extracted = extractUrlFromFetchArg(firstArg);
250
+ if (extracted) {
251
+ fetchCalls.push({
252
+ url: extracted.url,
253
+ isTemplate: extracted.isTemplate,
254
+ ...extracted.isConcat ? { isConcat: true } : {},
255
+ kind: "fetch"
256
+ });
257
+ }
258
+ }
259
+ if (ts.isPropertyAccessExpression(expr) && ts.isIdentifier(expr.name)) {
260
+ const methodName = expr.name.text;
261
+ if (HTTP_METHODS.has(methodName)) {
262
+ const extracted = extractUrlFromFetchArg(firstArg);
263
+ if (extracted) {
264
+ fetchCalls.push({
265
+ method: methodName.toUpperCase(),
266
+ url: extracted.url,
267
+ isTemplate: extracted.isTemplate,
268
+ ...extracted.isConcat ? { isConcat: true } : {},
269
+ kind: "client-method"
270
+ });
271
+ }
272
+ }
273
+ }
274
+ }
275
+ if (ts.isJsxOpeningElement(node) || ts.isJsxSelfClosingElement(node)) {
276
+ const tagName = node.tagName;
277
+ if (ts.isIdentifier(tagName) && tagName.text === "Link") {
278
+ for (const attr of node.attributes.properties) {
279
+ if (ts.isJsxAttribute(attr) && attr.name.getText(sourceFile) === "href" && attr.initializer) {
280
+ const init = attr.initializer;
281
+ if (ts.isStringLiteral(init)) {
282
+ navigations.push({ kind: "link-href", target: init.text, isTemplate: false });
283
+ } else if (ts.isJsxExpression(init) && init.expression) {
284
+ const parsed = extractTargetFromExpression(init.expression);
285
+ if (parsed) {
286
+ navigations.push({ kind: "link-href", target: parsed.target, isTemplate: parsed.isTemplate });
287
+ }
288
+ }
289
+ }
290
+ }
291
+ }
292
+ }
293
+ if (ts.isBinaryExpression(node) && node.operatorToken.kind === ts.SyntaxKind.EqualsToken) {
294
+ const left = node.left;
295
+ if (ts.isPropertyAccessExpression(left) && ts.isPropertyAccessExpression(left.expression) && ts.isIdentifier(left.expression.expression) && left.expression.expression.text === "window" && left.expression.name.text === "location" && left.name.text === "href") {
296
+ const parsed = extractTargetFromExpression(node.right);
297
+ if (parsed) {
298
+ navigations.push({ kind: "window-location", target: parsed.target, isTemplate: parsed.isTemplate });
299
+ }
300
+ }
301
+ }
302
+ if (ts.isCallExpression(node)) {
303
+ const expr = node.expression;
304
+ if (ts.isPropertyAccessExpression(expr) && ts.isPropertyAccessExpression(expr.expression) && ts.isIdentifier(expr.expression.expression) && expr.expression.expression.text === "window" && expr.expression.name.text === "location" && (expr.name.text === "assign" || expr.name.text === "replace")) {
305
+ const arg = node.arguments[0];
306
+ if (arg) {
307
+ const parsed = extractTargetFromExpression(arg);
308
+ if (parsed) {
309
+ navigations.push({ kind: "window-location", target: parsed.target, isTemplate: parsed.isTemplate });
310
+ }
311
+ }
312
+ }
313
+ }
314
+ ts.forEachChild(node, visit);
315
+ }
316
+ visit(sourceFile);
317
+ const name = defaultName ?? firstValueExport ?? firstTypeExport ?? "";
318
+ return {
319
+ name,
320
+ exports: exportsOrdered,
321
+ imports,
322
+ reExports,
323
+ jsxElements,
324
+ navigations,
325
+ fetchCalls
326
+ };
327
+ }
328
+ var MUTATION_METHODS = /* @__PURE__ */ new Set([
329
+ "create",
330
+ "createMany",
331
+ "createManyAndReturn",
332
+ "update",
333
+ "updateMany",
334
+ "updateManyAndReturn",
335
+ "upsert",
336
+ "delete",
337
+ "deleteMany"
338
+ ]);
339
+ function extractDbCalls(absPath) {
340
+ const ts = getTs();
341
+ const content = (0, import_node_fs.readFileSync)(absPath, "utf-8");
342
+ const ext = (0, import_node_path.extname)(absPath);
343
+ const scriptKind = ext === ".tsx" ? ts.ScriptKind.TSX : ts.ScriptKind.TS;
344
+ const sourceFile = ts.createSourceFile(absPath, content, ts.ScriptTarget.Latest, true, scriptKind);
345
+ const calls = [];
346
+ const seen = /* @__PURE__ */ new Set();
347
+ function visit(node) {
348
+ if (ts.isCallExpression(node)) {
349
+ const expr = node.expression;
350
+ if (ts.isPropertyAccessExpression(expr) && ts.isPropertyAccessExpression(expr.expression) && ts.isIdentifier(expr.expression.expression) && expr.expression.expression.text === "db") {
351
+ const model = expr.expression.name.text;
352
+ const method = expr.name.text;
353
+ const key = `${model}.${method}`;
354
+ if (!seen.has(key)) {
355
+ seen.add(key);
356
+ calls.push({
357
+ model,
358
+ method,
359
+ isMutation: MUTATION_METHODS.has(method)
360
+ });
361
+ }
362
+ }
363
+ }
364
+ ts.forEachChild(node, visit);
365
+ }
366
+ visit(sourceFile);
367
+ return calls;
368
+ }
369
+ function extractAuthWrappers(absPath) {
370
+ const ts = getTs();
371
+ const content = (0, import_node_fs.readFileSync)(absPath, "utf-8");
372
+ const ext = (0, import_node_path.extname)(absPath);
373
+ const scriptKind = ext === ".tsx" ? ts.ScriptKind.TSX : ts.ScriptKind.TS;
374
+ const sourceFile = ts.createSourceFile(absPath, content, ts.ScriptTarget.Latest, true, scriptKind);
375
+ const wrappers = /* @__PURE__ */ new Set();
376
+ const AUTH_WRAPPERS = /* @__PURE__ */ new Set(["withAuth", "withPermission", "withRole", "requireAuth"]);
377
+ function visit(node) {
378
+ if (ts.isCallExpression(node) && ts.isIdentifier(node.expression)) {
379
+ if (AUTH_WRAPPERS.has(node.expression.text)) {
380
+ wrappers.add(node.expression.text);
381
+ }
382
+ }
383
+ ts.forEachChild(node, visit);
384
+ }
385
+ visit(sourceFile);
386
+ return wrappers;
387
+ }
388
+
389
+ // src/server/graph/parsers/ui/react-nextjs.ts
390
+ var RENDER_TYPES = /* @__PURE__ */ new Set(["component", "ui", "layout", "context"]);
391
+ function walk(dir, exts) {
392
+ const results = [];
393
+ if (!(0, import_node_fs2.existsSync)(dir)) return results;
394
+ for (const entry of (0, import_node_fs2.readdirSync)(dir, { withFileTypes: true })) {
395
+ const full = (0, import_node_path2.join)(dir, entry.name);
396
+ if (entry.isDirectory()) {
397
+ results.push(...walk(full, exts));
398
+ } else if (exts.includes((0, import_node_path2.extname)(entry.name))) {
399
+ results.push(full);
400
+ }
401
+ }
402
+ return results;
403
+ }
404
+ function walkWithIgnore(dir, exts, ignoreDirs) {
405
+ const results = [];
406
+ if (!(0, import_node_fs2.existsSync)(dir)) return results;
407
+ for (const entry of (0, import_node_fs2.readdirSync)(dir, { withFileTypes: true })) {
408
+ if (entry.isDirectory()) {
409
+ if (ignoreDirs.has(entry.name)) continue;
410
+ results.push(...walkWithIgnore((0, import_node_path2.join)(dir, entry.name), exts, ignoreDirs));
411
+ } else if (exts.includes((0, import_node_path2.extname)(entry.name))) {
412
+ results.push((0, import_node_path2.join)(dir, entry.name));
413
+ }
414
+ }
415
+ return results;
416
+ }
417
+ function toNodeId(srcDir, absPath) {
418
+ return (0, import_node_path2.relative)(srcDir, absPath).replace(/\\/g, "/");
419
+ }
420
+ function resolveImport(srcDir, specifier) {
421
+ if (!specifier.startsWith("@/")) return null;
422
+ const rel = specifier.slice(2);
423
+ const base = (0, import_node_path2.join)(srcDir, rel);
424
+ for (const c of [base, base + ".ts", base + ".tsx", (0, import_node_path2.join)(base, "index.ts"), (0, import_node_path2.join)(base, "index.tsx")]) {
425
+ if ((0, import_node_fs2.existsSync)(c) && (0, import_node_fs2.statSync)(c).isFile()) return c;
426
+ }
427
+ return null;
428
+ }
429
+ function resolveRelativeImport(fromFile, specifier) {
430
+ const base = (0, import_node_path2.join)((0, import_node_path2.dirname)(fromFile), specifier);
431
+ for (const c of [base, base + ".ts", base + ".tsx", (0, import_node_path2.join)(base, "index.ts"), (0, import_node_path2.join)(base, "index.tsx")]) {
432
+ if ((0, import_node_fs2.existsSync)(c) && (0, import_node_fs2.statSync)(c).isFile()) return c;
433
+ }
434
+ return null;
435
+ }
436
+ function resolveBarrelMap(barrelAbsPath, parsedByPath, memo, visiting) {
437
+ const cached = memo.get(barrelAbsPath);
438
+ if (cached) return cached;
439
+ if (visiting.has(barrelAbsPath)) return /* @__PURE__ */ new Map();
440
+ visiting.add(barrelAbsPath);
441
+ const parsed = parsedByPath.get(barrelAbsPath);
442
+ const map = /* @__PURE__ */ new Map();
443
+ if (!parsed) {
444
+ visiting.delete(barrelAbsPath);
445
+ memo.set(barrelAbsPath, map);
446
+ return map;
447
+ }
448
+ for (const re of parsed.reExports) {
449
+ if (!re.from.startsWith(".")) continue;
450
+ const resolved = resolveRelativeImport(barrelAbsPath, re.from);
451
+ if (!resolved) continue;
452
+ if (re.isWildcard) {
453
+ const targetBn = (0, import_node_path2.basename)(resolved);
454
+ const targetIsBarrel = targetBn === "index.ts" || targetBn === "index.tsx";
455
+ if (targetIsBarrel) {
456
+ const nested = resolveBarrelMap(resolved, parsedByPath, memo, visiting);
457
+ for (const [name, target] of nested) {
458
+ if (!map.has(name)) map.set(name, target);
459
+ }
460
+ } else {
461
+ const targetParsed = parsedByPath.get(resolved);
462
+ if (targetParsed) {
463
+ for (const exp of targetParsed.exports) {
464
+ if (!map.has(exp)) map.set(exp, resolved);
465
+ }
466
+ }
467
+ }
468
+ } else {
469
+ if (!map.has(re.name)) map.set(re.name, resolved);
470
+ }
471
+ }
472
+ visiting.delete(barrelAbsPath);
473
+ memo.set(barrelAbsPath, map);
474
+ return map;
475
+ }
476
+ function buildAllBarrelMaps(srcDir, parsedByPath) {
477
+ const barrels = /* @__PURE__ */ new Map();
478
+ const memo = /* @__PURE__ */ new Map();
479
+ for (const [absPath, parsed] of parsedByPath) {
480
+ const bn = (0, import_node_path2.basename)(absPath);
481
+ if (bn !== "index.ts" && bn !== "index.tsx") continue;
482
+ if (parsed.reExports.length === 0) continue;
483
+ const map = resolveBarrelMap(absPath, parsedByPath, memo, /* @__PURE__ */ new Set());
484
+ if (map.size > 0) {
485
+ const barrelId = (0, import_node_path2.relative)(srcDir, (0, import_node_path2.dirname)(absPath)).replace(/\\/g, "/");
486
+ barrels.set(barrelId, map);
487
+ }
488
+ }
489
+ return barrels;
490
+ }
491
+ function classifyType(id) {
492
+ if (id.endsWith("/page.tsx")) return "page";
493
+ if (id.endsWith("/layout.tsx")) return "layout";
494
+ if (id.startsWith("client/components/ui/")) return "ui";
495
+ if (id.startsWith("client/components/")) return "component";
496
+ if (id.startsWith("client/hooks/")) return "hook";
497
+ if (/client\/lib\/.*-context\./.test(id)) return "context";
498
+ if (id.startsWith("client/lib/")) return id.includes("config") ? "config" : "util";
499
+ if (id.startsWith("client/api/")) return "util";
500
+ if (id.startsWith("server/mcp/")) return "mcp-tool";
501
+ if (id.startsWith("server/lib/")) return "lib";
502
+ if (id.startsWith("server/")) return "lib";
503
+ if (id.startsWith("lib/") || id.startsWith("config/")) return "lib";
504
+ return "component";
505
+ }
506
+ function classifyModule(id) {
507
+ if (/app\/\(auth\)\//.test(id)) return "auth";
508
+ if (/app\/\(admin\)\//.test(id)) return "admin";
509
+ if (/app\/\(settings\)\//.test(id)) return "settings";
510
+ if (/app\/\(app\)\/\[orgSlug\]\/\(project-pages\)\//.test(id)) return "project";
511
+ if (/app\/\(app\)\/\[orgSlug\]\/\(org-pages\)\//.test(id)) return "org";
512
+ if (/app\/\(app\)\/\[orgSlug\]\//.test(id)) return "org";
513
+ if (id.startsWith("app/integrations/")) return "integrations";
514
+ if (id.startsWith("app/docs/")) return "admin";
515
+ if (id.startsWith("client/components/ui/")) return "shared-ui";
516
+ if (id.startsWith("client/components/layout/") || /client\/lib\/navigation/.test(id)) return "layout";
517
+ if (/client\/components\/auth\//.test(id) || /client\/lib\/auth-/.test(id) || /client\/lib\/github-oauth/.test(id) || /client\/lib\/permission-service/.test(id) || /client\/hooks\/use-permissions/.test(id)) return "auth";
518
+ if (/client\/components\/prd-/.test(id) || /client\/hooks\/use-admin/.test(id)) return "admin";
519
+ if (/client\/components\/org-/.test(id) || /client\/hooks\/use-org-/.test(id) || /client\/hooks\/use-provider-def/.test(id)) return "org";
520
+ if (/client\/components\/project/.test(id) || /client\/hooks\/use-project-/.test(id) || /client\/hooks\/use-pipeline/.test(id) || /client\/hooks\/use-databases/.test(id) || /client\/hooks\/use-provider-env/.test(id) || /client\/hooks\/use-role-assign/.test(id) || /client\/components\/pipeline/.test(id) || /client\/components\/deployments/.test(id)) return "project";
521
+ if (/client\/hooks\/use-(profile|sessions|organizations|notification)/.test(id)) return "settings";
522
+ if (id.startsWith("server/auth/")) return "auth";
523
+ if (id.startsWith("server/mcp/")) return "mcp";
524
+ if (id.startsWith("server/lib/")) return "server-lib";
525
+ if (id.startsWith("server/middleware")) return "middleware";
526
+ if (id.startsWith("server/services/")) return "services";
527
+ if (id.startsWith("server/db")) return "db";
528
+ if (id.startsWith("server/errors")) return "errors";
529
+ if (id.startsWith("server/")) return "server-lib";
530
+ if (id.startsWith("config/")) return "config";
531
+ if (id.startsWith("lib/")) return "lib";
532
+ return "root";
533
+ }
534
+ function extractRoute(id) {
535
+ if (!id.endsWith("/page.tsx")) return null;
536
+ let route = id.replace(/^app\//, "/").replace(/\/page\.tsx$/, "");
537
+ route = route.replace(/\/\([^)]+\)/g, "");
538
+ route = route.replace(/\[([^\]]+)\]/g, ":$1");
539
+ route = route.replace(/\/+/g, "/");
540
+ if (!route.startsWith("/")) route = "/" + route;
541
+ return route || "/";
542
+ }
543
+ function nameFromFilename(absPath) {
544
+ return (0, import_node_path2.basename)(absPath, (0, import_node_path2.extname)(absPath)).replace(/[-_](\w)/g, (_, c) => c.toUpperCase()).replace(/^(\w)/, (_, c) => c.toUpperCase());
545
+ }
546
+ function resolveTemplateLiteralRoute(template, routeToNodeId) {
547
+ const parameterized = template.replace(/\$\{([^}]+)\}/g, (_, expr) => {
548
+ const cleaned = expr.trim();
549
+ if (cleaned.includes(".")) {
550
+ const parts = cleaned.split(".");
551
+ const last = parts[parts.length - 1];
552
+ const secondLast = parts.length > 1 ? parts[parts.length - 2] : "";
553
+ if (last === "slug" && secondLast === "project") return ":projectSlug";
554
+ if (last === "slug") return ":projectSlug";
555
+ if (last === "id" && /cred/i.test(secondLast)) return ":credentialId";
556
+ if (last === "id" && /run/i.test(secondLast)) return ":runId";
557
+ if (last === "sha") return ":commitSha";
558
+ if (last === "id") return ":id";
559
+ return `:${last}`;
560
+ }
561
+ if (/orgSlug/i.test(cleaned)) return ":orgSlug";
562
+ if (/projectSlug/i.test(cleaned)) return ":projectSlug";
563
+ if (/runId/i.test(cleaned)) return ":runId";
564
+ if (/credentialId/i.test(cleaned)) return ":credentialId";
565
+ if (/commitSha/i.test(cleaned)) return ":commitSha";
566
+ if (/token/i.test(cleaned)) return ":token";
567
+ return `:${cleaned}`;
568
+ });
569
+ const normalized = parameterized.replace(/\/+/g, "/").replace(/\/$/, "") || "/";
570
+ if (routeToNodeId.has(normalized)) return routeToNodeId.get(normalized);
571
+ let bestScore = -1;
572
+ let bestId = null;
573
+ for (const [route, nodeId] of routeToNodeId) {
574
+ const score = routeMatchScore(normalized, route);
575
+ if (score > bestScore) {
576
+ bestScore = score;
577
+ bestId = nodeId;
578
+ }
579
+ }
580
+ return bestScore > 0 ? bestId : null;
581
+ }
582
+ function routeMatchScore(candidate, known) {
583
+ const segsA = candidate.split("/");
584
+ const segsB = known.split("/");
585
+ if (segsA.length !== segsB.length) return -1;
586
+ let score = 0;
587
+ for (let i = 0; i < segsA.length; i++) {
588
+ const a = segsA[i], b = segsB[i];
589
+ if (a === b) {
590
+ score += 3;
591
+ continue;
592
+ }
593
+ if (a.startsWith(":") && b.startsWith(":")) {
594
+ score += 2;
595
+ continue;
596
+ }
597
+ if (a.startsWith(":") || b.startsWith(":")) {
598
+ score += 0;
599
+ continue;
600
+ }
601
+ return -1;
602
+ }
603
+ return score;
604
+ }
605
+ function templateToRoute(template) {
606
+ return template.replace(/\$\{([^}]+)\}/g, (_, expr) => {
607
+ const cleaned = expr.trim();
608
+ if (cleaned.includes(".")) {
609
+ const parts = cleaned.split(".");
610
+ const last = parts[parts.length - 1];
611
+ const secondLast = parts.length > 1 ? parts[parts.length - 2] : "";
612
+ if (last === "slug" && /project/i.test(secondLast)) return ":projectSlug";
613
+ if (last === "slug") return ":slug";
614
+ if (last === "sha") return ":commitSha";
615
+ return `:${last}`;
616
+ }
617
+ return `:${cleaned}`;
618
+ });
619
+ }
620
+ function matchRouteToPage(route, routeToNodeId) {
621
+ const normalized = route.replace(/\/$/, "") || "/";
622
+ if (routeToNodeId.has(normalized)) return routeToNodeId.get(normalized);
623
+ return null;
624
+ }
625
+ function loadApiRoutes(rootDir) {
626
+ const apiJsonPath = (0, import_node_path2.join)(rootDir, ".launchsecure", "graphs", "api.json");
627
+ if (!(0, import_node_fs2.existsSync)(apiJsonPath)) return [];
628
+ try {
629
+ const parsed = JSON.parse((0, import_node_fs2.readFileSync)(apiJsonPath, "utf-8"));
630
+ const routes = [];
631
+ for (const n of parsed.nodes ?? []) {
632
+ const path2 = n.path;
633
+ if (!path2 || typeof path2 !== "string") continue;
634
+ routes.push({
635
+ path: path2,
636
+ nodeId: n.id,
637
+ segments: path2.split("/").filter(Boolean)
638
+ });
639
+ }
640
+ return routes;
641
+ } catch {
642
+ return [];
643
+ }
644
+ }
645
+ function buildApiPathMap(routes) {
646
+ const map = /* @__PURE__ */ new Map();
647
+ for (const r of routes) {
648
+ if (!map.has(r.path)) map.set(r.path, r.nodeId);
649
+ }
650
+ return map;
651
+ }
652
+ function normalizeFetchUrl(raw) {
653
+ let s = raw.replace(/^`|`$/g, "");
654
+ const qIdx = s.indexOf("?");
655
+ if (qIdx >= 0) s = s.slice(0, qIdx);
656
+ const hIdx = s.indexOf("#");
657
+ if (hIdx >= 0) s = s.slice(0, hIdx);
658
+ let hadInterpolation = false;
659
+ s = s.replace(/\$\{([^}]+)\}/g, (_, expr) => {
660
+ hadInterpolation = true;
661
+ const cleaned = expr.trim();
662
+ const last = cleaned.split(".").pop() ?? cleaned;
663
+ const name = last.replace(/[^\w]/g, "") || "param";
664
+ return ":" + name;
665
+ });
666
+ s = s.replace(/\/+/g, "/");
667
+ if (s.length > 1 && s.endsWith("/")) s = s.slice(0, -1);
668
+ return { path: s || "/", hadInterpolation };
669
+ }
670
+ function scoreApiRouteMatch(candidate, known) {
671
+ if (candidate.length !== known.length) return -1;
672
+ let score = 0;
673
+ for (let i = 0; i < candidate.length; i++) {
674
+ const a = candidate[i];
675
+ const b = known[i];
676
+ if (a === b) {
677
+ score += 3;
678
+ continue;
679
+ }
680
+ if (a.startsWith(":") && b.startsWith(":")) {
681
+ score += 2;
682
+ continue;
683
+ }
684
+ if (a.startsWith(":") || b.startsWith(":")) {
685
+ score += 1;
686
+ continue;
687
+ }
688
+ return -1;
689
+ }
690
+ return score;
691
+ }
692
+ function resolveFetchCall(call, apiPathMap, apiRoutes) {
693
+ const raw = call.url;
694
+ if (/^(https?:)?\/\//i.test(raw)) {
695
+ return { kind: "external", normalizedUrl: raw };
696
+ }
697
+ if (call.isConcat) {
698
+ return { kind: "dynamic", normalizedUrl: raw };
699
+ }
700
+ const { path: path2, hadInterpolation } = normalizeFetchUrl(raw);
701
+ if (!path2.startsWith("/")) {
702
+ return { kind: "unresolved", normalizedUrl: path2 };
703
+ }
704
+ const segs = path2.split("/").filter(Boolean);
705
+ if (hadInterpolation && segs.length > 0 && segs[0].startsWith(":")) {
706
+ return { kind: "dynamic", normalizedUrl: path2 };
707
+ }
708
+ const exact = apiPathMap.get(path2);
709
+ if (exact) return { kind: "resolved", nodeId: exact, normalizedUrl: path2 };
710
+ let bestScore = -1;
711
+ let bestId = null;
712
+ for (const r of apiRoutes) {
713
+ const score = scoreApiRouteMatch(segs, r.segments);
714
+ if (score > bestScore) {
715
+ bestScore = score;
716
+ bestId = r.nodeId;
717
+ }
718
+ }
719
+ if (bestId && bestScore > 0) {
720
+ return { kind: "resolved", nodeId: bestId, normalizedUrl: path2 };
721
+ }
722
+ return { kind: "unresolved", normalizedUrl: path2 };
723
+ }
724
+ function extractEdges(srcDir, absPath, sourceId, parsed, nodeIdSet, nodeTypeMap, barrelMaps, routeToNodeId) {
725
+ const edges = [];
726
+ const flagged = [];
727
+ const seen = /* @__PURE__ */ new Set();
728
+ function addEdge(target, type, label) {
729
+ const key = `${sourceId}\u2192${target}\u2192${type}`;
730
+ if (seen.has(key)) return;
731
+ seen.add(key);
732
+ const edge = { source: sourceId, target, type };
733
+ if (label) edge.label = label;
734
+ edges.push(edge);
735
+ }
736
+ function edgeTypeFor(targetId, isTypeOnlyImport, importedNames) {
737
+ if (isTypeOnlyImport) return "imports";
738
+ const targetType = nodeTypeMap.get(targetId);
739
+ if (targetType && RENDER_TYPES.has(targetType)) {
740
+ const anyRendered = importedNames.some((n) => parsed.jsxElements.has(n));
741
+ if (anyRendered) return "renders";
742
+ }
743
+ return "imports";
744
+ }
745
+ for (const imp of parsed.imports) {
746
+ const { names, specifier, isTypeOnly, typeNames } = imp;
747
+ if (specifier.startsWith("@/")) {
748
+ const relToSrc = specifier.slice(2);
749
+ const barrelMap = barrelMaps.get(relToSrc);
750
+ if (barrelMap && names.length > 0) {
751
+ const byTarget = /* @__PURE__ */ new Map();
752
+ for (const name of names) {
753
+ const targetAbs = barrelMap.get(name);
754
+ if (targetAbs) {
755
+ const targetId = toNodeId(srcDir, targetAbs);
756
+ if (nodeIdSet.has(targetId)) {
757
+ if (!byTarget.has(targetId)) byTarget.set(targetId, []);
758
+ byTarget.get(targetId).push(name);
759
+ }
760
+ }
761
+ }
762
+ for (const [targetId, targetNames] of byTarget) {
763
+ const allType = isTypeOnly || targetNames.every((n) => typeNames.has(n));
764
+ addEdge(targetId, edgeTypeFor(targetId, allType, targetNames));
765
+ }
766
+ } else {
767
+ const resolved = resolveImport(srcDir, specifier);
768
+ if (resolved) {
769
+ const targetId = toNodeId(srcDir, resolved);
770
+ if (nodeIdSet.has(targetId) && !targetId.endsWith("/index.ts") && !targetId.endsWith("/index.tsx")) {
771
+ addEdge(targetId, edgeTypeFor(targetId, isTypeOnly, names));
772
+ }
773
+ }
774
+ }
775
+ } else if (specifier.startsWith(".")) {
776
+ const resolved = resolveRelativeImport(absPath, specifier);
777
+ if (resolved) {
778
+ const targetId = toNodeId(srcDir, resolved);
779
+ if (nodeIdSet.has(targetId) && !targetId.endsWith("/index.ts") && !targetId.endsWith("/index.tsx")) {
780
+ addEdge(targetId, edgeTypeFor(targetId, isTypeOnly, names));
781
+ }
782
+ }
783
+ }
784
+ }
785
+ for (const nav of parsed.navigations) {
786
+ if (nav.kind === "window-location") {
787
+ flagged.push({
788
+ source: sourceId,
789
+ target: "EXTERNAL",
790
+ type: "navigates",
791
+ label: `window.location to ${nav.target}`,
792
+ confidence: "high"
793
+ });
794
+ continue;
795
+ }
796
+ if (!nav.isTemplate) {
797
+ const targetId = matchRouteToPage(nav.target, routeToNodeId);
798
+ if (targetId && targetId !== sourceId) {
799
+ const label = nav.kind === "link-href" ? `Link to ${nav.target}` : `router.${nav.kind === "router-push" ? "push" : "replace"}('${nav.target}')`;
800
+ addEdge(targetId, "navigates", label);
801
+ }
802
+ } else {
803
+ const template = nav.target.replace(/^`|`$/g, "");
804
+ if (!template.includes("${")) continue;
805
+ const targetId = resolveTemplateLiteralRoute(template, routeToNodeId);
806
+ if (targetId && targetId !== sourceId) {
807
+ const label = nav.kind === "link-href" ? `Link to ${templateToRoute(template)}` : `router.${nav.kind === "router-push" ? "push" : "replace"}('${templateToRoute(template)}')`;
808
+ addEdge(targetId, "navigates", label);
809
+ } else {
810
+ flagged.push({
811
+ source: sourceId,
812
+ target: "DYNAMIC",
813
+ type: "navigates",
814
+ label: nav.kind === "link-href" ? `Link with template: \`${template}\`` : `router.${nav.kind === "router-push" ? "push" : "replace"} with template: \`${template}\``,
815
+ confidence: "medium"
816
+ });
817
+ }
818
+ }
819
+ }
820
+ return { edges, flagged };
821
+ }
822
+ function detect(rootDir) {
823
+ return (0, import_node_fs2.existsSync)((0, import_node_path2.join)(rootDir, "src", "app")) && (0, import_node_fs2.existsSync)((0, import_node_path2.join)(rootDir, "next.config.ts")) || (0, import_node_fs2.existsSync)((0, import_node_path2.join)(rootDir, "next.config.js")) || (0, import_node_fs2.existsSync)((0, import_node_path2.join)(rootDir, "next.config.mjs"));
824
+ }
825
+ function generate(rootDir) {
826
+ const srcDir = (0, import_node_path2.join)(rootDir, "src");
827
+ const appFiles = walk((0, import_node_path2.join)(srcDir, "app"), [".tsx", ".ts"]).filter(
828
+ (f) => (0, import_node_path2.basename)(f) !== "route.ts" && (0, import_node_path2.basename)(f) !== "route.tsx"
829
+ );
830
+ const clientFiles = walk((0, import_node_path2.join)(srcDir, "client"), [".tsx", ".ts"]);
831
+ const serverFiles = walk((0, import_node_path2.join)(srcDir, "server"), [".ts", ".tsx"]).filter(
832
+ (f) => (0, import_node_path2.basename)(f) !== "route.ts" && (0, import_node_path2.basename)(f) !== "route.tsx"
833
+ );
834
+ const libFiles = walk((0, import_node_path2.join)(srcDir, "lib"), [".ts", ".tsx"]);
835
+ const configFiles = walk((0, import_node_path2.join)(srcDir, "config"), [".ts", ".tsx"]);
836
+ const allDiscovered = [...appFiles, ...clientFiles, ...serverFiles, ...libFiles, ...configFiles];
837
+ const parsedByPath = /* @__PURE__ */ new Map();
838
+ for (const absPath of allDiscovered) {
839
+ parsedByPath.set(absPath, parseFile(absPath));
840
+ }
841
+ const barrelMaps = buildAllBarrelMaps(srcDir, parsedByPath);
842
+ const fileSet = allDiscovered.filter((f) => !(0, import_node_path2.basename)(f).startsWith("index."));
843
+ const nodes = [];
844
+ const nodeIdSet = /* @__PURE__ */ new Set();
845
+ const nodeTypeMap = /* @__PURE__ */ new Map();
846
+ const routeToNodeId = /* @__PURE__ */ new Map();
847
+ for (const absPath of fileSet) {
848
+ const id = toNodeId(srcDir, absPath);
849
+ const type = classifyType(id);
850
+ const parsed = parsedByPath.get(absPath);
851
+ const name = parsed.name || nameFromFilename(absPath);
852
+ const route = extractRoute(id);
853
+ const module_ = classifyModule(id);
854
+ nodes.push({ id, type, name, route, module: module_, exports: parsed.exports });
855
+ nodeIdSet.add(id);
856
+ nodeTypeMap.set(id, type);
857
+ if (route) routeToNodeId.set(route, id);
858
+ }
859
+ const allEdges = [];
860
+ const allFlagged = [];
861
+ const crossRefs = [];
862
+ for (const absPath of fileSet) {
863
+ const sourceId = toNodeId(srcDir, absPath);
864
+ const parsed = parsedByPath.get(absPath);
865
+ const { edges, flagged } = extractEdges(
866
+ srcDir,
867
+ absPath,
868
+ sourceId,
869
+ parsed,
870
+ nodeIdSet,
871
+ nodeTypeMap,
872
+ barrelMaps,
873
+ routeToNodeId
874
+ );
875
+ allEdges.push(...edges);
876
+ allFlagged.push(...flagged);
877
+ }
878
+ const apiRoutes = loadApiRoutes(rootDir);
879
+ const apiPathMap = buildApiPathMap(apiRoutes);
880
+ const includeExternalFetches = process.env.LAUNCH_CHART_INCLUDE_EXTERNAL_FETCHES === "1";
881
+ const fetchSeen = /* @__PURE__ */ new Set();
882
+ let fetchResolvedCount = 0;
883
+ let fetchDynamicCount = 0;
884
+ let fetchUnresolvedCount = 0;
885
+ let fetchExternalCount = 0;
886
+ for (const absPath of fileSet) {
887
+ const sourceId = toNodeId(srcDir, absPath);
888
+ const parsed = parsedByPath.get(absPath);
889
+ if (parsed.fetchCalls.length === 0) continue;
890
+ for (const call of parsed.fetchCalls) {
891
+ const result = resolveFetchCall(call, apiPathMap, apiRoutes);
892
+ const methodTag = call.method ?? (call.kind === "fetch" ? "GET?" : "?");
893
+ if (result.kind === "resolved" && result.nodeId) {
894
+ const key = `${sourceId}\u2192${result.nodeId}\u2192calls_api`;
895
+ if (fetchSeen.has(key)) continue;
896
+ fetchSeen.add(key);
897
+ crossRefs.push({
898
+ source: sourceId,
899
+ target: result.nodeId,
900
+ type: "calls_api",
901
+ layer: "api"
902
+ });
903
+ fetchResolvedCount++;
904
+ continue;
905
+ }
906
+ if (result.kind === "dynamic") {
907
+ fetchDynamicCount++;
908
+ allFlagged.push({
909
+ source: sourceId,
910
+ target: "DYNAMIC",
911
+ type: "calls_api",
912
+ label: call.isConcat ? `${methodTag} fetch with concat: ${call.url}` : `${methodTag} fetch with template: ${call.url}`,
913
+ confidence: call.isConcat ? "low" : "medium"
914
+ });
915
+ continue;
916
+ }
917
+ if (result.kind === "external") {
918
+ fetchExternalCount++;
919
+ if (!includeExternalFetches) continue;
920
+ allFlagged.push({
921
+ source: sourceId,
922
+ target: "EXTERNAL",
923
+ type: "calls_external",
924
+ label: `${methodTag} external fetch: ${call.url}`,
925
+ confidence: "high"
926
+ });
927
+ continue;
928
+ }
929
+ fetchUnresolvedCount++;
930
+ allFlagged.push({
931
+ source: sourceId,
932
+ target: "UNRESOLVED",
933
+ type: "calls_api",
934
+ label: `${methodTag} fetch to unknown path: ${result.normalizedUrl}`,
935
+ confidence: "medium"
936
+ });
937
+ }
938
+ }
939
+ const externalScanned = new Set(allDiscovered.map((f) => f.replace(/\\/g, "/")));
940
+ const IGNORE_DIRS = /* @__PURE__ */ new Set([
941
+ "node_modules",
942
+ ".next",
943
+ "dist",
944
+ ".launchsecure",
945
+ ".git",
946
+ "src",
947
+ "coverage",
948
+ ".turbo",
949
+ "build",
950
+ "out",
951
+ ".vercel"
952
+ ]);
953
+ const externalCandidates = walkWithIgnore(rootDir, [".ts", ".tsx"], IGNORE_DIRS);
954
+ for (const absPath of externalCandidates) {
955
+ const normalized = absPath.replace(/\\/g, "/");
956
+ if (externalScanned.has(normalized)) continue;
957
+ let parsed;
958
+ try {
959
+ parsed = parseFile(absPath);
960
+ } catch {
961
+ continue;
962
+ }
963
+ const externalId = (0, import_node_path2.relative)(rootDir, absPath).replace(/\\/g, "/");
964
+ const edgesFromThis = [];
965
+ const seen = /* @__PURE__ */ new Set();
966
+ for (const imp of parsed.imports) {
967
+ const { specifier, isTypeOnly, names } = imp;
968
+ let resolved = null;
969
+ if (specifier.startsWith("@/")) {
970
+ const relToSrc = specifier.slice(2);
971
+ const barrelMap = barrelMaps.get(relToSrc);
972
+ if (barrelMap && names.length > 0) {
973
+ for (const name of names) {
974
+ const targetAbs = barrelMap.get(name);
975
+ if (!targetAbs) continue;
976
+ const targetId2 = toNodeId(srcDir, targetAbs);
977
+ if (!nodeIdSet.has(targetId2)) continue;
978
+ const key2 = `${externalId}\u2192${targetId2}`;
979
+ if (seen.has(key2)) continue;
980
+ seen.add(key2);
981
+ edgesFromThis.push({ source: externalId, target: targetId2, type: "imports" });
982
+ }
983
+ continue;
984
+ }
985
+ resolved = resolveImport(srcDir, specifier);
986
+ } else if (specifier.startsWith(".")) {
987
+ resolved = resolveRelativeImport(absPath, specifier);
988
+ }
989
+ if (!resolved) continue;
990
+ const targetId = toNodeId(srcDir, resolved);
991
+ if (!nodeIdSet.has(targetId)) continue;
992
+ if (targetId.endsWith("/index.ts") || targetId.endsWith("/index.tsx")) continue;
993
+ const key = `${externalId}\u2192${targetId}\u2192${isTypeOnly ? "type" : "value"}`;
994
+ if (seen.has(key)) continue;
995
+ seen.add(key);
996
+ edgesFromThis.push({ source: externalId, target: targetId, type: "imports" });
997
+ }
998
+ if (edgesFromThis.length === 0) continue;
999
+ nodes.push({
1000
+ id: externalId,
1001
+ type: "external",
1002
+ name: parsed.name || nameFromFilename(absPath),
1003
+ route: null,
1004
+ module: "external",
1005
+ exports: parsed.exports
1006
+ });
1007
+ nodeIdSet.add(externalId);
1008
+ nodeTypeMap.set(externalId, "external");
1009
+ allEdges.push(...edgesFromThis);
1010
+ }
1011
+ const flaggedSet = /* @__PURE__ */ new Set();
1012
+ const dedupedFlagged = allFlagged.filter((f) => {
1013
+ const key = `${f.source}\u2192${f.target}\u2192${f.label}`;
1014
+ if (flaggedSet.has(key)) return false;
1015
+ flaggedSet.add(key);
1016
+ return true;
1017
+ });
1018
+ const typePriority = {
1019
+ layout: 0,
1020
+ page: 1,
1021
+ component: 2,
1022
+ ui: 3,
1023
+ context: 4,
1024
+ config: 5,
1025
+ util: 6,
1026
+ hook: 7,
1027
+ lib: 8
1028
+ };
1029
+ nodes.sort((a, b) => (typePriority[a.type] ?? 99) - (typePriority[b.type] ?? 99) || a.id.localeCompare(b.id));
1030
+ allEdges.sort((a, b) => a.source.localeCompare(b.source) || a.target.localeCompare(b.target));
1031
+ const byType = (t) => nodes.filter((n) => n.type === t).length;
1032
+ const stats = {
1033
+ total_pages: byType("page"),
1034
+ total_layouts: byType("layout"),
1035
+ total_components: byType("component"),
1036
+ total_ui: byType("ui"),
1037
+ total_hooks: byType("hook"),
1038
+ total_contexts: byType("context"),
1039
+ total_configs: byType("config"),
1040
+ total_utils: byType("util"),
1041
+ total_libs: byType("lib"),
1042
+ total_external: byType("external"),
1043
+ total_edges: allEdges.length,
1044
+ total_flagged: dedupedFlagged.length
1045
+ };
1046
+ return {
1047
+ metadata: {
1048
+ generated: (/* @__PURE__ */ new Date()).toISOString().slice(0, 10),
1049
+ scope: "main-app-only",
1050
+ app_root: "src/",
1051
+ layer: "ui",
1052
+ parser: "react-nextjs-ast",
1053
+ ...stats,
1054
+ api_call_detection: {
1055
+ includeExternalFetches,
1056
+ includeConcatFetches: process.env.LAUNCH_CHART_INCLUDE_CONCAT_FETCHES === "1",
1057
+ apiRoutesLoaded: apiRoutes.length,
1058
+ resolved: fetchResolvedCount,
1059
+ dynamic: fetchDynamicCount,
1060
+ unresolved: fetchUnresolvedCount,
1061
+ external: fetchExternalCount
1062
+ },
1063
+ notes: "Auto-generated via TypeScript AST \u2014 edges derived from actual imports, renders from JSX usage, navigations from router/Link calls."
1064
+ },
1065
+ nodes,
1066
+ edges: allEdges,
1067
+ cross_refs: crossRefs,
1068
+ contradictions: [],
1069
+ warnings: [],
1070
+ flagged_edges: dedupedFlagged,
1071
+ patterns: {
1072
+ total_nodes: nodes.length,
1073
+ by_type: stats,
1074
+ by_edge_type: {
1075
+ renders: allEdges.filter((e) => e.type === "renders").length,
1076
+ imports: allEdges.filter((e) => e.type === "imports").length,
1077
+ navigates: allEdges.filter((e) => e.type === "navigates").length
1078
+ }
1079
+ }
1080
+ };
1081
+ }
1082
+ var reactNextjsParser = {
1083
+ id: "react-nextjs",
1084
+ layer: "ui",
1085
+ detect,
1086
+ generate
1087
+ };
1088
+
1089
+ // src/server/graph/parsers/api/nextjs-routes.ts
1090
+ var import_node_fs3 = require("node:fs");
1091
+ var import_node_path3 = require("node:path");
1092
+ var HTTP_METHODS2 = /* @__PURE__ */ new Set(["GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS"]);
1093
+ function walk2(dir) {
1094
+ const results = [];
1095
+ if (!(0, import_node_fs3.existsSync)(dir)) return results;
1096
+ for (const entry of (0, import_node_fs3.readdirSync)(dir, { withFileTypes: true })) {
1097
+ const full = (0, import_node_path3.join)(dir, entry.name);
1098
+ if (entry.isDirectory()) {
1099
+ results.push(...walk2(full));
1100
+ } else if (entry.name === "route.ts" || entry.name === "route.tsx") {
1101
+ results.push(full);
1102
+ }
1103
+ }
1104
+ return results;
1105
+ }
1106
+ function filePathToRoute(apiDir, absPath) {
1107
+ let route = "/" + (0, import_node_path3.relative)(apiDir, absPath).replace(/\\/g, "/").replace(/\/route\.tsx?$/, "");
1108
+ route = route.replace(/\[([^\]]+)\]/g, ":$1");
1109
+ route = route.replace(/\/+/g, "/");
1110
+ if (route === "/") return "/api";
1111
+ return "/api" + route;
1112
+ }
1113
+ function camelToPascal(s) {
1114
+ if (!s) return s;
1115
+ return s.charAt(0).toUpperCase() + s.slice(1);
1116
+ }
1117
+ function detect2(rootDir) {
1118
+ return (0, import_node_fs3.existsSync)((0, import_node_path3.join)(rootDir, "src", "app", "api"));
1119
+ }
1120
+ function generate2(rootDir) {
1121
+ const apiDir = (0, import_node_path3.join)(rootDir, "src", "app", "api");
1122
+ const routeFiles = walk2(apiDir);
1123
+ const nodes = [];
1124
+ const edges = [];
1125
+ const crossRefs = [];
1126
+ const mutatorCount = {};
1127
+ const authUsage = {};
1128
+ let endpointsWithAuth = 0;
1129
+ let endpointsWithDbAccess = 0;
1130
+ for (const absPath of routeFiles) {
1131
+ const parsed = parseFile(absPath);
1132
+ const dbCalls = extractDbCalls(absPath);
1133
+ const authWrappers = extractAuthWrappers(absPath);
1134
+ const methods = [];
1135
+ for (const exp of parsed.exports) {
1136
+ if (HTTP_METHODS2.has(exp)) methods.push(exp);
1137
+ }
1138
+ const routePath = filePathToRoute(apiDir, absPath);
1139
+ const relPath = (0, import_node_path3.relative)(rootDir, absPath).replace(/\\/g, "/");
1140
+ const mutations = dbCalls.filter((c) => c.isMutation);
1141
+ const reads = dbCalls.filter((c) => !c.isMutation);
1142
+ const mutates = mutations.length > 0;
1143
+ if (mutates) {
1144
+ for (const m of mutations) {
1145
+ mutatorCount[m.method] = (mutatorCount[m.method] ?? 0) + 1;
1146
+ }
1147
+ }
1148
+ if (dbCalls.length > 0) endpointsWithDbAccess++;
1149
+ const authStrategy = [];
1150
+ for (const w of authWrappers) {
1151
+ authStrategy.push(w);
1152
+ authUsage[w] = (authUsage[w] ?? 0) + 1;
1153
+ }
1154
+ if (authStrategy.length > 0) endpointsWithAuth++;
1155
+ nodes.push({
1156
+ id: relPath,
1157
+ type: "endpoint",
1158
+ name: routePath,
1159
+ path: routePath,
1160
+ methods,
1161
+ handler: relPath,
1162
+ // Behavioral classification from handler body (AST-derived).
1163
+ mutates,
1164
+ auth: authStrategy.length > 0 ? authStrategy : ["public"],
1165
+ db_models: [...new Set(dbCalls.map((c) => c.model))],
1166
+ db_operations: [...new Set(dbCalls.map((c) => `${c.model}.${c.method}`))]
1167
+ });
1168
+ const seenModels = /* @__PURE__ */ new Set();
1169
+ for (const call of dbCalls) {
1170
+ if (seenModels.has(call.model)) continue;
1171
+ seenModels.add(call.model);
1172
+ crossRefs.push({
1173
+ source: relPath,
1174
+ target: camelToPascal(call.model),
1175
+ type: call.isMutation ? "mutates" : "reads",
1176
+ layer: "db"
1177
+ });
1178
+ }
1179
+ }
1180
+ nodes.sort((a, b) => a.path.localeCompare(b.path));
1181
+ crossRefs.sort((a, b) => a.source.localeCompare(b.source) || a.target.localeCompare(b.target));
1182
+ const mutatorNodes = nodes.filter((n) => n.mutates).length;
1183
+ const readOnlyNodes = nodes.filter((n) => !n.mutates).length;
1184
+ return {
1185
+ metadata: {
1186
+ generated: (/* @__PURE__ */ new Date()).toISOString().slice(0, 10),
1187
+ scope: "main-app-only",
1188
+ stack: "nextjs-app-router",
1189
+ layer: "api",
1190
+ parser: "nextjs-routes-ast",
1191
+ total_endpoints: nodes.length,
1192
+ total_methods: nodes.reduce((sum, n) => sum + n.methods.length, 0),
1193
+ endpoints_with_auth: endpointsWithAuth,
1194
+ endpoints_with_db_access: endpointsWithDbAccess,
1195
+ mutator_endpoints: mutatorNodes,
1196
+ read_only_endpoints: readOnlyNodes
1197
+ },
1198
+ nodes,
1199
+ edges,
1200
+ cross_refs: crossRefs,
1201
+ contradictions: [],
1202
+ warnings: [],
1203
+ flagged_edges: [],
1204
+ patterns: {
1205
+ total_endpoints: nodes.length,
1206
+ methods_breakdown: [...HTTP_METHODS2].reduce((acc, m) => {
1207
+ acc[m] = nodes.filter((n) => n.methods.includes(m)).length;
1208
+ return acc;
1209
+ }, {}),
1210
+ auth_strategies: authUsage,
1211
+ mutation_operations: mutatorCount,
1212
+ mutator_vs_reader: { mutators: mutatorNodes, readers: readOnlyNodes }
1213
+ }
1214
+ };
1215
+ }
1216
+ var nextjsRoutesParser = {
1217
+ id: "nextjs-routes",
1218
+ layer: "api",
1219
+ detect: detect2,
1220
+ generate: generate2
1221
+ };
1222
+
1223
+ // src/server/graph/parsers/db/prisma-schema.ts
1224
+ var import_node_fs4 = require("node:fs");
1225
+ var import_node_path4 = require("node:path");
1226
+ function parseModels(content) {
1227
+ const nodes = [];
1228
+ const relations = [];
1229
+ const modelRe = /model\s+(\w+)\s*\{([^}]+)\}/g;
1230
+ let m;
1231
+ while ((m = modelRe.exec(content)) !== null) {
1232
+ const modelName = m[1];
1233
+ const body = m[2];
1234
+ const columns = [];
1235
+ const lines = body.split("\n").map((l) => l.trim()).filter((l) => l && !l.startsWith("//") && !l.startsWith("@@"));
1236
+ for (const line of lines) {
1237
+ const fieldMatch = line.match(/^(\w+)\s+(\S+)(.*)/);
1238
+ if (!fieldMatch) continue;
1239
+ const fieldName = fieldMatch[1];
1240
+ const fieldType = fieldMatch[2];
1241
+ const rest = fieldMatch[3] ?? "";
1242
+ const commentMatch = rest.match(/\/\/\s*(.+)$/);
1243
+ const comment = commentMatch ? commentMatch[1].trim() : null;
1244
+ const restNoComment = commentMatch ? rest.slice(0, commentMatch.index).trim() : rest;
1245
+ const isPrimary = restNoComment.includes("@id");
1246
+ const isUnique = restNoComment.includes("@unique");
1247
+ const isNullable = fieldType.endsWith("?");
1248
+ const baseType = fieldType.replace(/[?\[\]]/g, "");
1249
+ const defaultMatch = restNoComment.match(/@default\(([^)]+)\)/);
1250
+ const defaultVal = defaultMatch ? defaultMatch[1] : null;
1251
+ const relationMatch = restNoComment.match(/@relation\(([^)]*)\)/);
1252
+ const isRelationField = !!relationMatch;
1253
+ columns.push({
1254
+ name: fieldName,
1255
+ type: fieldType,
1256
+ primary: isPrimary,
1257
+ unique: isUnique,
1258
+ nullable: isNullable,
1259
+ default: defaultVal,
1260
+ isRelation: isRelationField,
1261
+ comment
1262
+ });
1263
+ if (relationMatch) {
1264
+ const relArgs = relationMatch[1];
1265
+ const fieldsMatch = relArgs.match(/fields:\s*\[([^\]]+)\]/);
1266
+ const refsMatch = relArgs.match(/references:\s*\[([^\]]+)\]/);
1267
+ const onDeleteMatch = relArgs.match(/onDelete:\s*(\w+)/);
1268
+ if (fieldsMatch && refsMatch) {
1269
+ const fk = fieldsMatch[1].trim();
1270
+ relations.push({
1271
+ source: modelName,
1272
+ target: baseType,
1273
+ type: "belongs_to",
1274
+ fk,
1275
+ onDelete: onDeleteMatch ? onDeleteMatch[1] : null
1276
+ });
1277
+ }
1278
+ }
1279
+ if (fieldType.endsWith("[]") && !relationMatch) {
1280
+ relations.push({
1281
+ source: modelName,
1282
+ target: baseType,
1283
+ type: "has_many",
1284
+ fk: null,
1285
+ onDelete: null
1286
+ });
1287
+ }
1288
+ }
1289
+ nodes.push({
1290
+ id: modelName,
1291
+ type: "table",
1292
+ name: modelName,
1293
+ columns: columns.filter((c) => !c.isRelation || c.primary)
1294
+ });
1295
+ }
1296
+ return { nodes, relations };
1297
+ }
1298
+ function parseEnums(content) {
1299
+ const nodes = [];
1300
+ const enumRe = /enum\s+(\w+)\s*\{([^}]+)\}/g;
1301
+ let m;
1302
+ while ((m = enumRe.exec(content)) !== null) {
1303
+ const enumName = m[1];
1304
+ const body = m[2];
1305
+ const values = body.split("\n").map((l) => l.trim()).filter((l) => l && !l.startsWith("//"));
1306
+ nodes.push({
1307
+ id: enumName,
1308
+ type: "enum",
1309
+ name: enumName,
1310
+ values
1311
+ });
1312
+ }
1313
+ return nodes;
1314
+ }
1315
+ function detect3(rootDir) {
1316
+ return (0, import_node_fs4.existsSync)((0, import_node_path4.join)(rootDir, "prisma", "schema.prisma"));
1317
+ }
1318
+ function generate3(rootDir) {
1319
+ const schemaPath = (0, import_node_path4.join)(rootDir, "prisma", "schema.prisma");
1320
+ const content = (0, import_node_fs4.readFileSync)(schemaPath, "utf-8");
1321
+ const { nodes: modelNodes, relations } = parseModels(content);
1322
+ const enumNodes = parseEnums(content);
1323
+ const allNodes = [...modelNodes, ...enumNodes];
1324
+ const edges = relations.map((r) => ({
1325
+ source: r.source,
1326
+ target: r.target,
1327
+ type: r.type,
1328
+ fk: r.fk,
1329
+ onDelete: r.onDelete
1330
+ }));
1331
+ allNodes.sort((a, b) => {
1332
+ if (a.type !== b.type) return a.type === "table" ? -1 : 1;
1333
+ return a.name.localeCompare(b.name);
1334
+ });
1335
+ edges.sort((a, b) => a.source.localeCompare(b.source) || a.target.localeCompare(b.target));
1336
+ return {
1337
+ metadata: {
1338
+ generated: (/* @__PURE__ */ new Date()).toISOString().slice(0, 10),
1339
+ scope: "prisma-schema",
1340
+ source: "prisma/schema.prisma",
1341
+ provider: "postgresql",
1342
+ layer: "db",
1343
+ total_models: modelNodes.length,
1344
+ total_enums: enumNodes.length,
1345
+ total_relations: edges.length
1346
+ },
1347
+ nodes: allNodes,
1348
+ edges,
1349
+ cross_refs: [],
1350
+ contradictions: [],
1351
+ warnings: [
1352
+ {
1353
+ type: "schema_file_only",
1354
+ detail: "Live DB introspection not yet implemented. Graph derived from prisma/schema.prisma."
1355
+ }
1356
+ ],
1357
+ flagged_edges: [],
1358
+ patterns: {
1359
+ total_tables: modelNodes.length,
1360
+ total_enums: enumNodes.length,
1361
+ total_relations: edges.length,
1362
+ relation_types: {
1363
+ belongs_to: edges.filter((e) => e.type === "belongs_to").length,
1364
+ has_many: edges.filter((e) => e.type === "has_many").length
1365
+ }
1366
+ }
1367
+ };
1368
+ }
1369
+ var prismaSchemaParser = {
1370
+ id: "prisma-schema",
1371
+ layer: "db",
1372
+ detect: detect3,
1373
+ generate: generate3
1374
+ };
1375
+
1376
+ // src/server/graph/core/graph-builder.ts
1377
+ var ALL_PARSERS = [
1378
+ reactNextjsParser,
1379
+ nextjsRoutesParser,
1380
+ prismaSchemaParser
1381
+ ];
1382
+ function getParser(layer) {
1383
+ return ALL_PARSERS.find((p) => p.layer === layer);
1384
+ }
1385
+ function generateLayer(rootDir, layer) {
1386
+ const parser = getParser(layer);
1387
+ if (!parser) return null;
1388
+ if (!parser.detect(rootDir)) return null;
1389
+ const output = parser.generate(rootDir);
1390
+ return {
1391
+ layer,
1392
+ output,
1393
+ nodeCount: output.nodes.length,
1394
+ edgeCount: output.edges.length
1395
+ };
1396
+ }
1397
+ function generateAll(rootDir) {
1398
+ const layers = ["api", "db", "ui"];
1399
+ const results = [];
1400
+ for (const layer of layers) {
1401
+ const result = generateLayer(rootDir, layer);
1402
+ if (result) results.push(result);
1403
+ }
1404
+ const byLayer = new Map(results.map((r) => [r.layer, r]));
1405
+ return ["ui", "api", "db"].map((l) => byLayer.get(l)).filter((r) => !!r);
1406
+ }
1407
+
1408
+ // src/server/graph/index.ts
1409
+ var GRAPHS_DIR = ".launchsecure/graphs";
1410
+ var LAYERS = ["ui", "api", "db"];
1411
+ var graphCache = /* @__PURE__ */ new Map();
1412
+ function graphsDir(rootDir) {
1413
+ return (0, import_node_path5.join)(rootDir, GRAPHS_DIR);
1414
+ }
1415
+ function graphFilePath(rootDir, layer) {
1416
+ return (0, import_node_path5.join)(graphsDir(rootDir), `${layer}.json`);
1417
+ }
1418
+ function invalidateCache(filePath) {
1419
+ graphCache.delete(filePath);
1420
+ }
1421
+ function readGraph(rootDir, layer) {
1422
+ const filePath = graphFilePath(rootDir, layer);
1423
+ if (!(0, import_node_fs5.existsSync)(filePath)) return null;
1424
+ const stat = (0, import_node_fs5.statSync)(filePath);
1425
+ const cached = graphCache.get(filePath);
1426
+ if (cached && cached.mtimeMs === stat.mtimeMs) {
1427
+ return cached.graph;
1428
+ }
1429
+ const content = (0, import_node_fs5.readFileSync)(filePath, "utf-8");
1430
+ const graph = JSON.parse(content);
1431
+ graphCache.set(filePath, { mtimeMs: stat.mtimeMs, graph });
1432
+ return graph;
1433
+ }
1434
+ function readAllGraphs(rootDir) {
1435
+ const result = {};
1436
+ for (const layer of LAYERS) {
1437
+ const graph = readGraph(rootDir, layer);
1438
+ if (graph) result[layer] = graph;
1439
+ }
1440
+ return result;
1441
+ }
1442
+ function generateGraph(rootDir, layer) {
1443
+ const dir = graphsDir(rootDir);
1444
+ (0, import_node_fs5.mkdirSync)(dir, { recursive: true });
1445
+ const results = layer ? [generateLayer(rootDir, layer)].filter((r) => r !== null) : generateAll(rootDir);
1446
+ for (const result of results) {
1447
+ const filePath = graphFilePath(rootDir, result.layer);
1448
+ (0, import_node_fs5.writeFileSync)(filePath, JSON.stringify(result.output, null, 2) + "\n", "utf-8");
1449
+ invalidateCache(filePath);
1450
+ }
1451
+ return results;
1452
+ }
1453
+
1454
+ // src/server/lockfile.ts
1455
+ var import_node_child_process = require("node:child_process");
1456
+ var import_node_fs6 = require("node:fs");
1457
+ var import_node_os = require("node:os");
1458
+ var import_node_path6 = require("node:path");
1459
+ function lockDir() {
1460
+ return (0, import_node_path6.join)((0, import_node_os.homedir)(), ".launchsecure");
1461
+ }
1462
+ function lockPath() {
1463
+ return (0, import_node_path6.join)(lockDir(), "launch-chart.lock");
1464
+ }
1465
+ function readLock() {
1466
+ const p = lockPath();
1467
+ if (!(0, import_node_fs6.existsSync)(p)) return null;
1468
+ try {
1469
+ const data = JSON.parse((0, import_node_fs6.readFileSync)(p, "utf-8"));
1470
+ if (typeof data.pid !== "number" || typeof data.port !== "number") return null;
1471
+ return data;
1472
+ } catch {
1473
+ return null;
1474
+ }
1475
+ }
1476
+ function isPidAlive(pid) {
1477
+ try {
1478
+ process.kill(pid, 0);
1479
+ return true;
1480
+ } catch {
1481
+ return false;
1482
+ }
1483
+ }
1484
+ function getListenerPid(port) {
1485
+ try {
1486
+ const out = (0, import_node_child_process.execFileSync)("lsof", ["-nP", "-iTCP:" + port, "-sTCP:LISTEN", "-t"], {
1487
+ encoding: "utf-8",
1488
+ stdio: ["ignore", "pipe", "ignore"],
1489
+ timeout: 500
1490
+ }).trim();
1491
+ if (!out) return null;
1492
+ const pid = parseInt(out.split("\n")[0], 10);
1493
+ return Number.isFinite(pid) ? pid : null;
1494
+ } catch {
1495
+ return null;
1496
+ }
1497
+ }
1498
+ function getLiveLock() {
1499
+ const lock = readLock();
1500
+ if (!lock) return null;
1501
+ const listenerPid = getListenerPid(lock.port);
1502
+ const live = listenerPid !== null ? listenerPid === lock.pid : isPidAlive(lock.pid);
1503
+ if (!live) {
1504
+ try {
1505
+ (0, import_node_fs6.unlinkSync)(lockPath());
1506
+ } catch {
1507
+ }
1508
+ return null;
1509
+ }
1510
+ return lock;
1511
+ }
1512
+ function writeLock(data) {
1513
+ (0, import_node_fs6.mkdirSync)(lockDir(), { recursive: true });
1514
+ (0, import_node_fs6.writeFileSync)(lockPath(), JSON.stringify(data, null, 2) + "\n", "utf-8");
1515
+ }
1516
+ function clearLock() {
1517
+ try {
1518
+ (0, import_node_fs6.unlinkSync)(lockPath());
1519
+ } catch {
1520
+ }
1521
+ }
1522
+
1523
+ // src/server/chart-serve.ts
1524
+ var DEFAULT_PORT = 52819;
1525
+ var MAX_PORT_SCAN = 20;
1526
+ var MIME_TYPES = {
1527
+ ".html": "text/html; charset=utf-8",
1528
+ ".js": "application/javascript; charset=utf-8",
1529
+ ".css": "text/css; charset=utf-8",
1530
+ ".json": "application/json; charset=utf-8",
1531
+ ".png": "image/png",
1532
+ ".svg": "image/svg+xml",
1533
+ ".ico": "image/x-icon",
1534
+ ".woff": "font/woff",
1535
+ ".woff2": "font/woff2"
1536
+ };
1537
+ function findProjectRoot(startDir) {
1538
+ let dir = startDir;
1539
+ for (let i = 0; i < 8; i++) {
1540
+ const graphsDir2 = import_node_path7.default.join(dir, ".launchsecure", "graphs");
1541
+ if (import_node_fs7.default.existsSync(import_node_path7.default.join(graphsDir2, "ui.json")) || import_node_fs7.default.existsSync(import_node_path7.default.join(graphsDir2, "api.json")) || import_node_fs7.default.existsSync(import_node_path7.default.join(graphsDir2, "db.json"))) return dir;
1542
+ const parent = import_node_path7.default.dirname(dir);
1543
+ if (parent === dir) break;
1544
+ dir = parent;
1545
+ }
1546
+ dir = startDir;
1547
+ for (let i = 0; i < 8; i++) {
1548
+ if (import_node_fs7.default.existsSync(import_node_path7.default.join(dir, ".git"))) return dir;
1549
+ const parent = import_node_path7.default.dirname(dir);
1550
+ if (parent === dir) break;
1551
+ dir = parent;
1552
+ }
1553
+ return startDir;
1554
+ }
1555
+ function buildMergedGraph(projectRoot) {
1556
+ let graphs = readAllGraphs(projectRoot);
1557
+ if (!graphs.ui && !graphs.api && !graphs.db) {
1558
+ generateGraph(projectRoot);
1559
+ graphs = readAllGraphs(projectRoot);
1560
+ }
1561
+ const nodes = [];
1562
+ const rawLinks = [];
1563
+ const LAYERS2 = ["ui", "api", "db"];
1564
+ for (const layer of LAYERS2) {
1565
+ const g = graphs[layer];
1566
+ if (!g) continue;
1567
+ for (const n of g.nodes) {
1568
+ nodes.push({
1569
+ id: `${layer}:${n.id}`,
1570
+ name: n.name,
1571
+ type: n.type,
1572
+ layer,
1573
+ module: n.module ?? null,
1574
+ path: n.path ?? n.id
1575
+ });
1576
+ }
1577
+ for (const e of g.edges) {
1578
+ rawLinks.push({ source: `${layer}:${e.source}`, target: `${layer}:${e.target}`, type: e.type, layer, cross: false });
1579
+ }
1580
+ for (const c of g.cross_refs ?? []) {
1581
+ rawLinks.push({ source: `${layer}:${c.source}`, target: `${c.layer}:${c.target}`, type: c.type, layer, cross: true });
1582
+ }
1583
+ }
1584
+ const nodeIds = new Set(nodes.map((n) => n.id));
1585
+ const links = rawLinks.filter((l) => nodeIds.has(l.source) && nodeIds.has(l.target));
1586
+ return {
1587
+ nodes,
1588
+ links,
1589
+ stats: {
1590
+ nodes: nodes.length,
1591
+ links: links.length,
1592
+ byLayer: {
1593
+ ui: graphs.ui ? graphs.ui.nodes.length : 0,
1594
+ api: graphs.api ? graphs.api.nodes.length : 0,
1595
+ db: graphs.db ? graphs.db.nodes.length : 0
1596
+ }
1597
+ }
1598
+ };
1599
+ }
1600
+ function serveStatic(res, filePath) {
1601
+ if (!import_node_fs7.default.existsSync(filePath) || !import_node_fs7.default.statSync(filePath).isFile()) return false;
1602
+ const ext = import_node_path7.default.extname(filePath).toLowerCase();
1603
+ const mime = MIME_TYPES[ext] ?? "application/octet-stream";
1604
+ res.writeHead(200, { "Content-Type": mime, "Cache-Control": "no-cache" });
1605
+ import_node_fs7.default.createReadStream(filePath).pipe(res);
1606
+ return true;
1607
+ }
1608
+ function serveIndex(res, clientDir) {
1609
+ const indexPath = import_node_path7.default.join(clientDir, "index.html");
1610
+ if (!import_node_fs7.default.existsSync(indexPath)) {
1611
+ res.writeHead(500, { "Content-Type": "text/plain" });
1612
+ res.end(`LaunchChart client bundle not found at ${clientDir}. Run 'npm run build:chart-client'.`);
1613
+ return;
1614
+ }
1615
+ serveStatic(res, indexPath);
1616
+ }
1617
+ function tryListen(server, port) {
1618
+ return new Promise((resolve, reject) => {
1619
+ const onError = (err) => {
1620
+ server.off("listening", onListening);
1621
+ reject(err);
1622
+ };
1623
+ const onListening = () => {
1624
+ server.off("error", onError);
1625
+ resolve(port);
1626
+ };
1627
+ server.once("error", onError);
1628
+ server.once("listening", onListening);
1629
+ server.listen(port, "127.0.0.1");
1630
+ });
1631
+ }
1632
+ async function bindWithFallback(server, startPort) {
1633
+ let lastErr = null;
1634
+ for (let i = 0; i < MAX_PORT_SCAN; i++) {
1635
+ const port = startPort + i;
1636
+ try {
1637
+ return await tryListen(server, port);
1638
+ } catch (err) {
1639
+ const code = err.code;
1640
+ if (code === "EADDRINUSE") {
1641
+ lastErr = err;
1642
+ continue;
1643
+ }
1644
+ throw err;
1645
+ }
1646
+ }
1647
+ throw lastErr ?? new Error("Failed to bind any port");
1648
+ }
1649
+ async function startChartServer(opts = {}) {
1650
+ const cwd = opts.cwd ?? process.cwd();
1651
+ const projectRoot = findProjectRoot(cwd);
1652
+ const existing = getLiveLock();
1653
+ if (existing) {
1654
+ if (!opts.quiet) {
1655
+ process.stderr.write(
1656
+ `[launch-chart] already running (pid ${existing.pid}) at ${existing.url}
1657
+ `
1658
+ );
1659
+ }
1660
+ return { port: existing.port, url: existing.url };
1661
+ }
1662
+ const clientDir = opts.clientDir ?? import_node_path7.default.join(__dirname, "..", "chart-client");
1663
+ const server = import_node_http.default.createServer((req, res) => {
1664
+ try {
1665
+ const url2 = new URL(req.url ?? "/", `http://${req.headers.host}`);
1666
+ if (req.method === "GET" && url2.pathname === "/api/project-graph") {
1667
+ const regenerate = url2.searchParams.get("regenerate") === "1";
1668
+ if (regenerate) generateGraph(projectRoot);
1669
+ const merged = buildMergedGraph(projectRoot);
1670
+ res.writeHead(200, { "Content-Type": "application/json" });
1671
+ res.end(JSON.stringify({
1672
+ ...merged,
1673
+ debug: { cwd, projectRoot }
1674
+ }));
1675
+ return;
1676
+ }
1677
+ if (req.method === "GET" && url2.pathname === "/api/raw-graphs") {
1678
+ const graphs = readAllGraphs(projectRoot);
1679
+ res.writeHead(200, { "Content-Type": "application/json" });
1680
+ res.end(JSON.stringify({ ui: graphs.ui ?? null, api: graphs.api ?? null, db: graphs.db ?? null }));
1681
+ return;
1682
+ }
1683
+ if (req.method === "POST" && url2.pathname === "/api/generate-graph") {
1684
+ try {
1685
+ generateGraph(projectRoot);
1686
+ const graphs = readAllGraphs(projectRoot);
1687
+ res.writeHead(200, { "Content-Type": "application/json" });
1688
+ res.end(JSON.stringify({
1689
+ ok: true,
1690
+ ui: graphs.ui ?? null,
1691
+ api: graphs.api ?? null,
1692
+ db: graphs.db ?? null
1693
+ }));
1694
+ } catch (err) {
1695
+ res.writeHead(500, { "Content-Type": "application/json" });
1696
+ res.end(JSON.stringify({ ok: false, error: String(err) }));
1697
+ }
1698
+ return;
1699
+ }
1700
+ if (req.method === "GET" && url2.pathname === "/api/health") {
1701
+ res.writeHead(200, { "Content-Type": "application/json" });
1702
+ res.end(JSON.stringify({ ok: true, projectRoot }));
1703
+ return;
1704
+ }
1705
+ if (url2.pathname !== "/") {
1706
+ const staticPath = import_node_path7.default.join(clientDir, url2.pathname);
1707
+ if (serveStatic(res, staticPath)) return;
1708
+ }
1709
+ serveIndex(res, clientDir);
1710
+ } catch (err) {
1711
+ res.writeHead(500, { "Content-Type": "application/json" });
1712
+ res.end(JSON.stringify({ error: String(err) }));
1713
+ }
1714
+ });
1715
+ const port = await bindWithFallback(server, opts.port ?? DEFAULT_PORT);
1716
+ const url = `http://localhost:${port}`;
1717
+ writeLock({
1718
+ pid: process.pid,
1719
+ port,
1720
+ cwd,
1721
+ url,
1722
+ startedAt: (/* @__PURE__ */ new Date()).toISOString()
1723
+ });
1724
+ const cleanup = () => {
1725
+ clearLock();
1726
+ server.close();
1727
+ };
1728
+ process.once("SIGINT", () => {
1729
+ cleanup();
1730
+ process.exit(0);
1731
+ });
1732
+ process.once("SIGTERM", () => {
1733
+ cleanup();
1734
+ process.exit(0);
1735
+ });
1736
+ process.once("exit", cleanup);
1737
+ if (!opts.quiet) {
1738
+ process.stderr.write(`[launch-chart] serving ${url}
1739
+ `);
1740
+ process.stderr.write(`[launch-chart] project root: ${projectRoot}
1741
+ `);
1742
+ }
1743
+ return { port, url };
1744
+ }
1745
+ function runServeCli(argv) {
1746
+ let port;
1747
+ for (let i = 0; i < argv.length; i++) {
1748
+ if (argv[i] === "--port" && argv[i + 1]) {
1749
+ port = parseInt(argv[++i], 10);
1750
+ } else if (argv[i].startsWith("--port=")) {
1751
+ port = parseInt(argv[i].slice("--port=".length), 10);
1752
+ }
1753
+ }
1754
+ startChartServer({ port }).catch((err) => {
1755
+ process.stderr.write(`[launch-chart] failed to start: ${err}
1756
+ `);
1757
+ process.exit(1);
1758
+ });
1759
+ }
1760
+ // Annotate the CommonJS export names for ESM import in node:
1761
+ 0 && (module.exports = {
1762
+ runServeCli,
1763
+ startChartServer
1764
+ });