@emeryld/rrroutes-export 1.0.1

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/index.cjs ADDED
@@ -0,0 +1,1386 @@
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/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ DEFAULT_VIEWER_TEMPLATE: () => DEFAULT_VIEWER_TEMPLATE,
34
+ clearSchemaIntrospectionHandlers: () => clearSchemaIntrospectionHandlers,
35
+ createSchemaIntrospector: () => createSchemaIntrospector,
36
+ exportFinalizedLeaves: () => exportFinalizedLeaves,
37
+ extractLeafSourceByAst: () => extractLeafSourceByAst,
38
+ flattenLeafSchemas: () => flattenLeafSchemas,
39
+ flattenSerializableSchema: () => flattenSerializableSchema,
40
+ introspectSchema: () => introspectSchema,
41
+ loadFinalizedLeavesInput: () => loadFinalizedLeavesInput,
42
+ parseFinalizedLeavesCliArgs: () => parseFinalizedLeavesCliArgs,
43
+ registerSchemaIntrospectionHandler: () => registerSchemaIntrospectionHandler,
44
+ runExportFinalizedLeavesCli: () => runExportFinalizedLeavesCli,
45
+ serializableSchemaKinds: () => serializableSchemaKinds,
46
+ serializeLeafContract: () => serializeLeafContract,
47
+ serializeLeavesContract: () => serializeLeavesContract,
48
+ writeFinalizedLeavesExport: () => writeFinalizedLeavesExport
49
+ });
50
+ module.exports = __toCommonJS(index_exports);
51
+
52
+ // src/schemaIntrospection.ts
53
+ var z = __toESM(require("zod"), 1);
54
+ var serializableSchemaKinds = [
55
+ "object",
56
+ "string",
57
+ "number",
58
+ "boolean",
59
+ "bigint",
60
+ "date",
61
+ "array",
62
+ "enum",
63
+ "literal",
64
+ "union",
65
+ "record",
66
+ "tuple",
67
+ "unknown",
68
+ "any"
69
+ ];
70
+ var globalHandlers = {};
71
+ function registerSchemaIntrospectionHandler(kind, handler) {
72
+ globalHandlers[kind] = handler;
73
+ }
74
+ function clearSchemaIntrospectionHandlers() {
75
+ for (const key of Object.keys(globalHandlers)) {
76
+ delete globalHandlers[key];
77
+ }
78
+ }
79
+ function getDef(schema) {
80
+ if (!schema || typeof schema !== "object") return void 0;
81
+ const anySchema = schema;
82
+ return anySchema._zod?.def ?? anySchema._def;
83
+ }
84
+ function getDescription(schema) {
85
+ const anyZ = z;
86
+ const registry = anyZ.globalRegistry?.get ? anyZ.globalRegistry.get(schema) : void 0;
87
+ if (registry && typeof registry.description === "string") {
88
+ return registry.description;
89
+ }
90
+ const def = getDef(schema);
91
+ if (def && typeof def.description === "string") {
92
+ return def.description;
93
+ }
94
+ return void 0;
95
+ }
96
+ function unwrap(schema) {
97
+ let current = schema;
98
+ let optional = false;
99
+ let nullable = false;
100
+ const ZodEffectsCtor = z.ZodEffects;
101
+ while (true) {
102
+ if (ZodEffectsCtor && current instanceof ZodEffectsCtor) {
103
+ const def = getDef(current) || {};
104
+ const sourceType = typeof current.sourceType === "function" ? current.sourceType() : def.schema;
105
+ if (!sourceType) break;
106
+ current = sourceType;
107
+ continue;
108
+ }
109
+ if (current instanceof z.ZodOptional) {
110
+ optional = true;
111
+ const def = getDef(current);
112
+ current = def && def.innerType || current;
113
+ continue;
114
+ }
115
+ if (current instanceof z.ZodNullable) {
116
+ nullable = true;
117
+ const def = getDef(current);
118
+ current = def && def.innerType || current;
119
+ continue;
120
+ }
121
+ if (current instanceof z.ZodDefault) {
122
+ const def = getDef(current);
123
+ current = def && def.innerType || current;
124
+ continue;
125
+ }
126
+ break;
127
+ }
128
+ return { base: current, optional, nullable };
129
+ }
130
+ function mergeProps(a, b) {
131
+ if (!a && !b) return void 0;
132
+ return { ...a ?? {}, ...b ?? {} };
133
+ }
134
+ function inferKind(schema) {
135
+ if (schema instanceof z.ZodString) return "string";
136
+ if (schema instanceof z.ZodNumber) return "number";
137
+ if (schema instanceof z.ZodBoolean) return "boolean";
138
+ if (schema instanceof z.ZodBigInt) return "bigint";
139
+ if (schema instanceof z.ZodDate) return "date";
140
+ if (schema instanceof z.ZodArray) return "array";
141
+ if (schema instanceof z.ZodObject) return "object";
142
+ if (schema instanceof z.ZodUnion) return "union";
143
+ if (schema instanceof z.ZodLiteral) return "literal";
144
+ if (schema instanceof z.ZodEnum) return "enum";
145
+ if (schema instanceof z.ZodRecord) return "record";
146
+ if (schema instanceof z.ZodTuple) return "tuple";
147
+ if (schema instanceof z.ZodUnknown) return "unknown";
148
+ if (schema instanceof z.ZodAny) return "any";
149
+ return "unknown";
150
+ }
151
+ var defaultHandlers = {
152
+ intersection({ base, def, node }, ctx) {
153
+ const left = def?.left;
154
+ const right = def?.right;
155
+ const leftNode = left ? ctx.introspect(left) : void 0;
156
+ const rightNode = right ? ctx.introspect(right) : void 0;
157
+ const leftIsObj = leftNode?.kind === "object" && !!leftNode.properties;
158
+ const rightIsObj = rightNode?.kind === "object" && !!rightNode.properties;
159
+ if (leftIsObj && rightIsObj) {
160
+ node.kind = "object";
161
+ node.description = node.description ?? leftNode.description ?? rightNode.description;
162
+ node.properties = mergeProps(leftNode.properties, rightNode.properties);
163
+ return node;
164
+ }
165
+ if (leftNode && rightNode) {
166
+ node.properties = {
167
+ left: leftNode,
168
+ right: rightNode
169
+ };
170
+ }
171
+ return node;
172
+ },
173
+ object({ base, def, node }, ctx) {
174
+ const rawShape = base.shape ?? (def && typeof def.shape === "function" ? def.shape() : def?.shape);
175
+ const shape = typeof rawShape === "function" ? rawShape() : rawShape ?? {};
176
+ const props = {};
177
+ for (const key of Object.keys(shape)) {
178
+ const child = shape[key];
179
+ const childNode = ctx.introspect(child);
180
+ if (childNode) props[key] = childNode;
181
+ }
182
+ node.properties = props;
183
+ return node;
184
+ },
185
+ array({ def, node }, ctx) {
186
+ const inner = def && def.element || def && def.type || void 0;
187
+ if (inner) {
188
+ node.element = ctx.introspect(inner);
189
+ }
190
+ return node;
191
+ },
192
+ union({ def, node }, ctx) {
193
+ const options = def && def.options || [];
194
+ node.union = options.map((opt) => ctx.introspect(opt)).filter(Boolean);
195
+ return node;
196
+ },
197
+ literal({ def, node }) {
198
+ if (def) {
199
+ if (Array.isArray(def.values)) {
200
+ node.literal = def.values.length === 1 ? def.values[0] : def.values.slice();
201
+ } else {
202
+ node.literal = def.value;
203
+ }
204
+ }
205
+ return node;
206
+ },
207
+ enum({ def, node }) {
208
+ if (def) {
209
+ if (Array.isArray(def.values)) {
210
+ node.enumValues = def.values.slice();
211
+ } else if (def.entries && typeof def.entries === "object") {
212
+ node.enumValues = Object.values(def.entries).map((v) => String(v));
213
+ }
214
+ }
215
+ return node;
216
+ }
217
+ };
218
+ function createSchemaIntrospector(options = {}) {
219
+ const handlers = {
220
+ ...defaultHandlers,
221
+ ...globalHandlers,
222
+ ...options.handlers ?? {}
223
+ };
224
+ const introspect = (schema) => {
225
+ if (!schema) return void 0;
226
+ const unwrapped = unwrap(schema);
227
+ const base = unwrapped.base;
228
+ const def = getDef(base);
229
+ const kind = base instanceof z.ZodIntersection ? "intersection" : inferKind(base);
230
+ const node = {
231
+ kind: kind === "intersection" ? "unknown" : kind,
232
+ optional: unwrapped.optional || void 0,
233
+ nullable: unwrapped.nullable || void 0,
234
+ description: getDescription(base)
235
+ };
236
+ const handler = handlers[kind];
237
+ if (!handler) return node;
238
+ return handler(
239
+ {
240
+ schema,
241
+ base,
242
+ def,
243
+ kind,
244
+ optional: unwrapped.optional,
245
+ nullable: unwrapped.nullable,
246
+ node
247
+ },
248
+ {
249
+ zod: z,
250
+ introspect,
251
+ getDef,
252
+ unwrap,
253
+ getDescription
254
+ }
255
+ );
256
+ };
257
+ return introspect;
258
+ }
259
+ function introspectSchema(schema, options = {}) {
260
+ const introspect = createSchemaIntrospector(options);
261
+ return introspect(schema);
262
+ }
263
+
264
+ // src/serializeLeafContract.ts
265
+ var import_rrroutes_contract = require("@emeryld/rrroutes-contract");
266
+ function serializeContractSchema(schema, options) {
267
+ return schema ? introspectSchema((0, import_rrroutes_contract.routeSchemaParse)(schema), options) : void 0;
268
+ }
269
+ function serializeBodyFiles(cfg) {
270
+ if (!Array.isArray(cfg.bodyFiles) || cfg.bodyFiles.length === 0) {
271
+ return void 0;
272
+ }
273
+ return cfg.bodyFiles.map(({ name, maxCount }) => ({ name, maxCount }));
274
+ }
275
+ function serializeLeafContract(leaf, options = {}) {
276
+ const cfg = leaf.cfg;
277
+ return {
278
+ key: `${leaf.method.toUpperCase()} ${leaf.path}`,
279
+ method: leaf.method,
280
+ path: leaf.path,
281
+ cfg: {
282
+ description: cfg.description,
283
+ summary: cfg.summary,
284
+ docsGroup: cfg.docsGroup,
285
+ tags: Array.isArray(cfg.tags) ? cfg.tags.slice() : void 0,
286
+ deprecated: cfg.deprecated,
287
+ stability: cfg.stability,
288
+ docsHidden: cfg.docsHidden,
289
+ docsMeta: cfg.docsMeta,
290
+ feed: cfg.feed,
291
+ bodyFiles: serializeBodyFiles(cfg),
292
+ schemas: {
293
+ body: serializeContractSchema(cfg.bodySchema, options),
294
+ query: serializeContractSchema(cfg.querySchema, options),
295
+ params: serializeContractSchema(cfg.paramsSchema, options),
296
+ output: serializeContractSchema(cfg.outputSchema, options),
297
+ outputMeta: serializeContractSchema(cfg.outputMetaSchema, options),
298
+ queryExtension: serializeContractSchema(cfg.queryExtensionSchema, options)
299
+ }
300
+ }
301
+ };
302
+ }
303
+ function serializeLeavesContract(leaves, options = {}) {
304
+ return leaves.map((leaf) => serializeLeafContract(leaf, options));
305
+ }
306
+
307
+ // src/flattenSchema.ts
308
+ function formatLiteralType(literal) {
309
+ if (typeof literal === "string") return literal;
310
+ if (typeof literal === "number" || typeof literal === "boolean" || typeof literal === "bigint") {
311
+ return String(literal);
312
+ }
313
+ if (literal === null) return "null";
314
+ if (Array.isArray(literal)) {
315
+ return literal.map((item) => formatLiteralType(item)).join("|");
316
+ }
317
+ if (typeof literal === "object") {
318
+ try {
319
+ return JSON.stringify(literal);
320
+ } catch {
321
+ return "object";
322
+ }
323
+ }
324
+ return "unknown";
325
+ }
326
+ function normalizeType(schema) {
327
+ switch (schema.kind) {
328
+ case "string":
329
+ case "number":
330
+ case "date":
331
+ case "boolean":
332
+ case "object":
333
+ case "array":
334
+ return schema.kind;
335
+ case "enum": {
336
+ if (Array.isArray(schema.enumValues) && schema.enumValues.length > 0) {
337
+ return schema.enumValues.join("|");
338
+ }
339
+ return "unknown";
340
+ }
341
+ case "literal": {
342
+ return formatLiteralType(schema.literal);
343
+ }
344
+ default:
345
+ return "unknown";
346
+ }
347
+ }
348
+ function isNonEmptyPath(path4) {
349
+ return typeof path4 === "string" && path4.length > 0;
350
+ }
351
+ function setNode(out, path4, schema, inherited) {
352
+ if (!isNonEmptyPath(path4)) return;
353
+ out[path4] = {
354
+ type: normalizeType(schema),
355
+ nullable: inherited.nullable || Boolean(schema.nullable),
356
+ optional: inherited.optional || Boolean(schema.optional),
357
+ literal: schema.kind === "literal" ? schema.literal : void 0
358
+ };
359
+ }
360
+ function flattenInto(out, schema, path4, inherited) {
361
+ if (!schema || !isNonEmptyPath(path4)) return;
362
+ const nextInherited = {
363
+ optional: inherited.optional || Boolean(schema.optional),
364
+ nullable: inherited.nullable || Boolean(schema.nullable)
365
+ };
366
+ if (schema.kind === "union" && Array.isArray(schema.union) && schema.union.length > 0) {
367
+ schema.union.forEach((option, index) => {
368
+ const optionPath = `${path4}-${index + 1}`;
369
+ flattenInto(out, option, optionPath, inherited);
370
+ });
371
+ return;
372
+ }
373
+ setNode(out, path4, schema, inherited);
374
+ if (schema.kind === "object" && schema.properties) {
375
+ for (const [key, child] of Object.entries(schema.properties)) {
376
+ const childPath = `${path4}.${key}`;
377
+ flattenInto(out, child, childPath, nextInherited);
378
+ }
379
+ return;
380
+ }
381
+ if (schema.kind === "array" && schema.element) {
382
+ flattenInto(out, schema.element, `${path4}[]`, nextInherited);
383
+ }
384
+ }
385
+ function flattenSerializableSchema(schema, path4) {
386
+ const out = {};
387
+ flattenInto(out, schema, path4, { optional: false, nullable: false });
388
+ return out;
389
+ }
390
+ function isSerializedLeaf(value) {
391
+ if (!value || typeof value !== "object") return false;
392
+ const item = value;
393
+ return typeof item.key === "string" && !!item.cfg && typeof item.cfg === "object";
394
+ }
395
+ function flattenLeafSchemas(leaf) {
396
+ const serialized = isSerializedLeaf(leaf) ? leaf : serializeLeafContract(leaf);
397
+ const out = {};
398
+ const sections = serialized.cfg.schemas;
399
+ Object.assign(out, flattenSerializableSchema(sections.params, "params"));
400
+ Object.assign(out, flattenSerializableSchema(sections.query, "query"));
401
+ Object.assign(out, flattenSerializableSchema(sections.body, "body"));
402
+ Object.assign(out, flattenSerializableSchema(sections.output, "output"));
403
+ return out;
404
+ }
405
+
406
+ // src/exportFinalizedLeaves.ts
407
+ var import_promises = __toESM(require("fs/promises"), 1);
408
+ var import_node_path2 = __toESM(require("path"), 1);
409
+ var import_node_child_process = require("child_process");
410
+
411
+ // src/defaultViewerTemplate.ts
412
+ var DEFAULT_VIEWER_TEMPLATE = `<!doctype html>
413
+ <html lang="en">
414
+ <head>
415
+ <meta charset="UTF-8" />
416
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
417
+ <title>Finalized Leaves Viewer</title>
418
+ <style>
419
+ :root {
420
+ --bg: #212121;
421
+ --surface: #2a2a2a;
422
+ --border: #4a4a4a;
423
+ --text: #fffafa;
424
+ --muted: #c8c2c2;
425
+ --accent: #a764d3;
426
+ --schema-accent: #fbbd23;
427
+ }
428
+ body {
429
+ margin: 0;
430
+ font-family: 'Iosevka Web', 'SFMono-Regular', Menlo, Consolas, monospace;
431
+ color: var(--text);
432
+ background: var(--bg);
433
+ }
434
+ a { color: var(--schema-accent); }
435
+ .wrap { max-width: 1100px; margin: 0 auto; padding: 20px; }
436
+ .card { background: var(--surface); border: 1px solid var(--border); border-radius: 12px; padding: 14px; }
437
+ .meta { color: var(--muted); font-size: 12px; }
438
+ #results { margin-top: 12px; display: grid; gap: 8px; }
439
+ details { background: var(--surface); border: 1px solid var(--border); border-radius: 10px; padding: 8px 10px; }
440
+ summary { cursor: pointer; font-weight: 700; color: var(--accent); }
441
+ pre { margin: 10px 0 0; overflow: auto; border: 1px solid var(--border); border-radius: 8px; padding: 10px; background: #303030; color: var(--text); }
442
+ </style>
443
+ </head>
444
+ <body>
445
+ <div class="wrap">
446
+ <h1>Finalized Leaves Viewer (Baked)</h1>
447
+ <div class="card">
448
+ <div id="status" class="meta">Waiting for baked payload...</div>
449
+ </div>
450
+ <div id="results"></div>
451
+ </div>
452
+
453
+ <!--__FINALIZED_LEAVES_BAKED_PAYLOAD__-->
454
+
455
+ <script>
456
+ const statusEl = document.getElementById('status')
457
+ const resultsEl = document.getElementById('results')
458
+ const payload = window.__FINALIZED_LEAVES_PAYLOAD
459
+
460
+ if (!payload || !Array.isArray(payload.leaves)) {
461
+ statusEl.textContent = 'No baked payload found in this HTML file.'
462
+ } else {
463
+ statusEl.textContent = 'Loaded baked payload with ' + payload.leaves.length + ' routes.'
464
+
465
+ const toHref = (source) => {
466
+ if (!source || !source.file) return null
467
+ const normalizedPath = String(source.file).replace(/\\\\/g, '/')
468
+ const platform =
469
+ (navigator.userAgentData && navigator.userAgentData.platform) ||
470
+ navigator.platform ||
471
+ ''
472
+ const isWindows = /win/i.test(platform)
473
+ const vscodePath = isWindows
474
+ ? normalizedPath.replace(/^\\/+/, '')
475
+ : normalizedPath.startsWith('/')
476
+ ? normalizedPath
477
+ : '/' + normalizedPath
478
+ const line = Number.isFinite(source.line) ? source.line : 1
479
+ const column = Number.isFinite(source.column) ? source.column : 1
480
+ return 'vscode://file/' + encodeURI(vscodePath) + ':' + line + ':' + column
481
+ }
482
+
483
+ const sourceDisplay = (source) => {
484
+ return ''
485
+ }
486
+
487
+ payload.leaves.forEach((leaf) => {
488
+ const details = document.createElement('details')
489
+ const summary = document.createElement('summary')
490
+ summary.textContent = String(leaf.method || '').toUpperCase() + ' ' + (leaf.path || '')
491
+
492
+ const pre = document.createElement('pre')
493
+ pre.textContent = JSON.stringify(leaf, null, 2)
494
+
495
+ const source = payload.sourceByLeaf && payload.sourceByLeaf[leaf.key]
496
+ let sourceWrap = null
497
+ if (source) {
498
+ sourceWrap = document.createElement('div')
499
+ sourceWrap.className = 'meta'
500
+
501
+ const definitionHref = toHref(source.definition)
502
+ if (definitionHref) {
503
+ const label = document.createElement('div')
504
+ const link = document.createElement('a')
505
+ link.href = definitionHref
506
+ link.target = '_blank'
507
+ link.rel = 'noopener noreferrer'
508
+ link.textContent = 'definition'
509
+ label.appendChild(link)
510
+ sourceWrap.appendChild(label)
511
+ }
512
+
513
+ if (source.schemas && typeof source.schemas === 'object') {
514
+ Object.entries(source.schemas).forEach(([name, schema]) => {
515
+ if (!schema) return
516
+ const href = toHref(schema)
517
+ const row = document.createElement('div')
518
+ if (href) {
519
+ const link = document.createElement('a')
520
+ link.href = href
521
+ link.target = '_blank'
522
+ link.rel = 'noopener noreferrer'
523
+ link.textContent =
524
+ name + ': ' + (schema.sourceName || schema.tag || '<anonymous>')
525
+ row.appendChild(link)
526
+ } else {
527
+ row.textContent = name + ': ' + (schema.sourceName || schema.tag || '<anonymous>')
528
+ }
529
+ sourceWrap.appendChild(row)
530
+ })
531
+ }
532
+
533
+ }
534
+
535
+ details.appendChild(summary)
536
+ if (sourceWrap) details.appendChild(sourceWrap)
537
+ details.appendChild(pre)
538
+ resultsEl.appendChild(details)
539
+ })
540
+ }
541
+ </script>
542
+ </body>
543
+ </html>
544
+ `;
545
+
546
+ // src/extractLeafSourceByAst.ts
547
+ var import_node_path = __toESM(require("path"), 1);
548
+ var import_typescript = __toESM(require("typescript"), 1);
549
+ var SCHEMA_KEYS = [
550
+ "bodySchema",
551
+ "querySchema",
552
+ "paramsSchema",
553
+ "outputSchema",
554
+ "outputMetaSchema",
555
+ "queryExtensionSchema"
556
+ ];
557
+ var HTTP_METHODS = /* @__PURE__ */ new Set(["get", "post", "put", "patch", "delete"]);
558
+ var MAX_RECURSION_DEPTH = 120;
559
+ function toLocation(node) {
560
+ const sourceFile = node.getSourceFile();
561
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(
562
+ node.getStart(sourceFile)
563
+ );
564
+ return {
565
+ file: import_node_path.default.resolve(sourceFile.fileName),
566
+ line: line + 1,
567
+ column: character + 1
568
+ };
569
+ }
570
+ function markFile(ctx, sourceFile) {
571
+ if (!sourceFile) return;
572
+ ctx.visitedFilePaths.add(import_node_path.default.resolve(sourceFile.fileName));
573
+ }
574
+ function trimPreview(text, max = 80) {
575
+ const normalized = text.replace(/\s+/g, " ").trim();
576
+ return normalized.length > max ? `${normalized.slice(0, max)}...` : normalized;
577
+ }
578
+ function unwrapExpression(expression) {
579
+ let current = expression;
580
+ while (true) {
581
+ if (import_typescript.default.isParenthesizedExpression(current) || import_typescript.default.isAsExpression(current) || import_typescript.default.isTypeAssertionExpression(current) || import_typescript.default.isNonNullExpression(current) || import_typescript.default.isSatisfiesExpression(current)) {
582
+ current = current.expression;
583
+ continue;
584
+ }
585
+ break;
586
+ }
587
+ return current;
588
+ }
589
+ function getTextName(name) {
590
+ if (import_typescript.default.isIdentifier(name) || import_typescript.default.isStringLiteral(name) || import_typescript.default.isNumericLiteral(name)) {
591
+ return name.text;
592
+ }
593
+ return void 0;
594
+ }
595
+ function joinPaths(parent, child) {
596
+ if (!parent) return child;
597
+ if (!child) return parent;
598
+ const trimmedParent = parent.endsWith("/") ? parent.replace(/\/+$/, "") : parent;
599
+ const trimmedChild = child.startsWith("/") ? child.replace(/^\/+/, "") : child;
600
+ if (!trimmedChild) return trimmedParent;
601
+ return `${trimmedParent}/${trimmedChild}`;
602
+ }
603
+ function buildLeafKey(method, leafPath) {
604
+ return `${method.toUpperCase()} ${leafPath}`;
605
+ }
606
+ function normalizeResourceBase(raw) {
607
+ if (raw === "") return "";
608
+ if (raw.startsWith("/") || raw.startsWith(":") || raw.startsWith("*")) {
609
+ return raw;
610
+ }
611
+ return `/${raw}`;
612
+ }
613
+ function getModuleSymbol(checker, sourceFile) {
614
+ return checker.getSymbolAtLocation(sourceFile);
615
+ }
616
+ function getAliasedSymbolIfNeeded(checker, symbol) {
617
+ if ((symbol.flags & import_typescript.default.SymbolFlags.Alias) !== 0) {
618
+ try {
619
+ return checker.getAliasedSymbol(symbol);
620
+ } catch {
621
+ return symbol;
622
+ }
623
+ }
624
+ return symbol;
625
+ }
626
+ function findSourceFile(program, filePath) {
627
+ const wanted = import_node_path.default.resolve(filePath);
628
+ const normalizedWanted = import_node_path.default.normalize(wanted);
629
+ return program.getSourceFiles().find((file) => import_node_path.default.normalize(import_node_path.default.resolve(file.fileName)) === normalizedWanted);
630
+ }
631
+ function declarationToExpression(declaration) {
632
+ if (!declaration) return void 0;
633
+ if (import_typescript.default.isVariableDeclaration(declaration)) {
634
+ return declaration.initializer;
635
+ }
636
+ if (import_typescript.default.isExportAssignment(declaration)) {
637
+ return declaration.expression;
638
+ }
639
+ if (import_typescript.default.isPropertyAssignment(declaration)) {
640
+ return declaration.initializer;
641
+ }
642
+ if (import_typescript.default.isShorthandPropertyAssignment(declaration)) {
643
+ return declaration.name;
644
+ }
645
+ if (import_typescript.default.isBindingElement(declaration)) {
646
+ return declaration.initializer;
647
+ }
648
+ if (import_typescript.default.isEnumMember(declaration)) {
649
+ return declaration.initializer;
650
+ }
651
+ return void 0;
652
+ }
653
+ function symbolKey(symbol) {
654
+ const decl = symbol.declarations?.[0];
655
+ if (!decl) return `${symbol.getName()}#${symbol.flags}`;
656
+ const file = import_node_path.default.resolve(decl.getSourceFile().fileName);
657
+ return `${file}:${decl.getStart()}:${symbol.getName()}`;
658
+ }
659
+ function resolveSymbolFromNode(node, ctx) {
660
+ const symbol = ctx.checker.getSymbolAtLocation(node);
661
+ if (!symbol) {
662
+ ctx.unresolvedReferences += 1;
663
+ return void 0;
664
+ }
665
+ const target = getAliasedSymbolIfNeeded(ctx.checker, symbol);
666
+ const key = symbolKey(target);
667
+ ctx.visitedSymbolKeys.add(key);
668
+ return target;
669
+ }
670
+ function getExpressionFromSymbol(symbol, ctx, depth) {
671
+ const key = symbolKey(symbol);
672
+ if (ctx.activeSymbols.has(key)) return void 0;
673
+ if (depth > MAX_RECURSION_DEPTH) return void 0;
674
+ ctx.activeSymbols.add(key);
675
+ try {
676
+ const declaration = symbol.declarations?.[0];
677
+ markFile(ctx, declaration?.getSourceFile());
678
+ const direct = declarationToExpression(declaration);
679
+ if (direct) return direct;
680
+ if (declaration && import_typescript.default.isImportSpecifier(declaration)) {
681
+ const target = getAliasedSymbolIfNeeded(ctx.checker, symbol);
682
+ if (target !== symbol) {
683
+ return getExpressionFromSymbol(target, ctx, depth + 1);
684
+ }
685
+ }
686
+ return void 0;
687
+ } finally {
688
+ ctx.activeSymbols.delete(key);
689
+ }
690
+ }
691
+ function resolveIdentifierExpression(identifier, ctx, depth) {
692
+ const symbol = resolveSymbolFromNode(identifier, ctx);
693
+ if (!symbol) return void 0;
694
+ return getExpressionFromSymbol(symbol, ctx, depth);
695
+ }
696
+ function resolvePropertyExpression(expression, ctx, depth) {
697
+ if (depth > MAX_RECURSION_DEPTH) return void 0;
698
+ if (import_typescript.default.isPropertyAccessExpression(expression)) {
699
+ const symbol = resolveSymbolFromNode(expression.name, ctx);
700
+ if (symbol) {
701
+ const fromSymbol = getExpressionFromSymbol(symbol, ctx, depth + 1);
702
+ if (fromSymbol) return fromSymbol;
703
+ }
704
+ } else if (expression.argumentExpression) {
705
+ const symbol = resolveSymbolFromNode(expression.argumentExpression, ctx);
706
+ if (symbol) {
707
+ const fromSymbol = getExpressionFromSymbol(symbol, ctx, depth + 1);
708
+ if (fromSymbol) return fromSymbol;
709
+ }
710
+ }
711
+ const ownerExpr = evaluateExpressionReference(expression.expression, ctx, depth + 1);
712
+ const owner = ownerExpr ? maybeObjectLiteral(ownerExpr, ctx, depth + 1) : void 0;
713
+ if (!owner) return void 0;
714
+ const propName = import_typescript.default.isPropertyAccessExpression(expression) ? expression.name.text : expression.argumentExpression && import_typescript.default.isStringLiteralLike(expression.argumentExpression) ? expression.argumentExpression.text : void 0;
715
+ if (!propName) return void 0;
716
+ for (const property of owner.properties) {
717
+ if (import_typescript.default.isPropertyAssignment(property) && getTextName(property.name) === propName) {
718
+ return property.initializer;
719
+ }
720
+ if (import_typescript.default.isShorthandPropertyAssignment(property) && property.name.text === propName) {
721
+ return property.name;
722
+ }
723
+ }
724
+ return void 0;
725
+ }
726
+ function evaluateExpressionReference(expression, ctx, depth) {
727
+ const resolved = unwrapExpression(expression);
728
+ markFile(ctx, resolved.getSourceFile());
729
+ if (depth > MAX_RECURSION_DEPTH) return void 0;
730
+ if (import_typescript.default.isIdentifier(resolved)) {
731
+ return resolveIdentifierExpression(resolved, ctx, depth + 1);
732
+ }
733
+ if (import_typescript.default.isPropertyAccessExpression(resolved) || import_typescript.default.isElementAccessExpression(resolved)) {
734
+ return resolvePropertyExpression(resolved, ctx, depth + 1);
735
+ }
736
+ return void 0;
737
+ }
738
+ function resolveExportExpression(sourceFile, exportName, checker) {
739
+ const moduleSymbol = getModuleSymbol(checker, sourceFile);
740
+ if (!moduleSymbol) return void 0;
741
+ const exports2 = checker.getExportsOfModule(moduleSymbol);
742
+ const explicit = exports2.find((entry) => entry.getName() === exportName);
743
+ if (explicit) {
744
+ const declaration = getAliasedSymbolIfNeeded(checker, explicit).declarations?.[0];
745
+ return declarationToExpression(declaration);
746
+ }
747
+ const defaultExport = exports2.find((entry) => entry.getName() === "default");
748
+ if (!defaultExport) return void 0;
749
+ const defaultDecl = getAliasedSymbolIfNeeded(checker, defaultExport).declarations?.[0];
750
+ const defaultExpr = declarationToExpression(defaultDecl);
751
+ if (!defaultExpr) return void 0;
752
+ const resolved = unwrapExpression(defaultExpr);
753
+ if (!import_typescript.default.isObjectLiteralExpression(resolved)) return void 0;
754
+ for (const property of resolved.properties) {
755
+ if (!import_typescript.default.isPropertyAssignment(property)) continue;
756
+ const propertyName = getTextName(property.name);
757
+ if (propertyName !== exportName) continue;
758
+ return property.initializer;
759
+ }
760
+ return void 0;
761
+ }
762
+ function maybeObjectLiteral(expression, ctx, depth = 0) {
763
+ if (!expression || depth > MAX_RECURSION_DEPTH) return void 0;
764
+ const resolved = unwrapExpression(expression);
765
+ markFile(ctx, resolved.getSourceFile());
766
+ if (import_typescript.default.isObjectLiteralExpression(resolved)) return resolved;
767
+ const referenced = evaluateExpressionReference(resolved, ctx, depth + 1);
768
+ if (!referenced) return void 0;
769
+ return maybeObjectLiteral(referenced, ctx, depth + 1);
770
+ }
771
+ function collectSchemaExpressionsFromObject(objectLiteral, ctx, depth) {
772
+ const schemas = {};
773
+ for (const property of objectLiteral.properties) {
774
+ if (import_typescript.default.isSpreadAssignment(property)) {
775
+ const spreadObject = maybeObjectLiteral(property.expression, ctx, depth + 1);
776
+ if (!spreadObject) continue;
777
+ Object.assign(
778
+ schemas,
779
+ collectSchemaExpressionsFromObject(spreadObject, ctx, depth + 1)
780
+ );
781
+ continue;
782
+ }
783
+ if (import_typescript.default.isPropertyAssignment(property)) {
784
+ const key = getTextName(property.name);
785
+ if (!key || !SCHEMA_KEYS.includes(key)) continue;
786
+ schemas[key] = property.initializer;
787
+ continue;
788
+ }
789
+ if (import_typescript.default.isShorthandPropertyAssignment(property)) {
790
+ const key = property.name.text;
791
+ if (!SCHEMA_KEYS.includes(key)) continue;
792
+ schemas[key] = property.name;
793
+ }
794
+ }
795
+ return schemas;
796
+ }
797
+ function extractSchemaExpressions(cfgExpression, ctx, depth) {
798
+ const objectLiteral = maybeObjectLiteral(cfgExpression, ctx, depth);
799
+ if (!objectLiteral) return {};
800
+ return collectSchemaExpressionsFromObject(objectLiteral, ctx, depth);
801
+ }
802
+ function getNearestVariableName(node) {
803
+ let current = node;
804
+ while (current) {
805
+ if (import_typescript.default.isVariableDeclaration(current) && import_typescript.default.isIdentifier(current.name)) {
806
+ return current.name.text;
807
+ }
808
+ current = current.parent;
809
+ }
810
+ return void 0;
811
+ }
812
+ function isAllAccess(expression) {
813
+ if (import_typescript.default.isPropertyAccessExpression(expression)) {
814
+ return expression.name.text === "all";
815
+ }
816
+ return Boolean(
817
+ expression.argumentExpression && import_typescript.default.isStringLiteralLike(expression.argumentExpression) && expression.argumentExpression.text === "all"
818
+ );
819
+ }
820
+ function evaluateBranchExpression(expression, ctx, depth) {
821
+ const resolved = unwrapExpression(expression);
822
+ markFile(ctx, resolved.getSourceFile());
823
+ if (depth > MAX_RECURSION_DEPTH) return void 0;
824
+ if (import_typescript.default.isIdentifier(resolved)) {
825
+ const valueExpr = resolveIdentifierExpression(resolved, ctx, depth + 1);
826
+ if (!valueExpr) return void 0;
827
+ return evaluateBranchExpression(valueExpr, ctx, depth + 1);
828
+ }
829
+ if (!import_typescript.default.isCallExpression(resolved)) return void 0;
830
+ const call = resolved;
831
+ if (import_typescript.default.isIdentifier(call.expression) && call.expression.text === "resource") {
832
+ const firstArg = call.arguments[0];
833
+ if (!firstArg || !import_typescript.default.isStringLiteralLike(firstArg)) {
834
+ ctx.unsupportedShapeSeen = true;
835
+ return void 0;
836
+ }
837
+ return { base: normalizeResourceBase(firstArg.text), leaves: [] };
838
+ }
839
+ if (!import_typescript.default.isPropertyAccessExpression(call.expression)) {
840
+ ctx.unsupportedShapeSeen = true;
841
+ return void 0;
842
+ }
843
+ const owner = call.expression.expression;
844
+ const method = call.expression.name.text;
845
+ const branch = evaluateBranchExpression(owner, ctx, depth + 1);
846
+ if (!branch) return void 0;
847
+ if (method === "with") return branch;
848
+ if (HTTP_METHODS.has(method)) {
849
+ const cfgExpression = call.arguments[0];
850
+ const schemas = extractSchemaExpressions(cfgExpression, ctx, depth + 1);
851
+ const nextLeaf = {
852
+ method,
853
+ path: branch.base,
854
+ definitionNode: call.expression.name,
855
+ schemas
856
+ };
857
+ return {
858
+ ...branch,
859
+ leaves: [...branch.leaves, nextLeaf]
860
+ };
861
+ }
862
+ if (method === "sub") {
863
+ const mountedLeaves = call.arguments.flatMap(
864
+ (arg) => evaluateLeavesFromExpression(arg, ctx, depth + 1)
865
+ );
866
+ const prefixed = mountedLeaves.map((leaf) => ({
867
+ ...leaf,
868
+ path: joinPaths(branch.base, leaf.path)
869
+ }));
870
+ return {
871
+ ...branch,
872
+ leaves: [...branch.leaves, ...prefixed]
873
+ };
874
+ }
875
+ ctx.unsupportedShapeSeen = true;
876
+ return void 0;
877
+ }
878
+ function expressionKey(expression) {
879
+ const source = expression.getSourceFile();
880
+ return `${import_node_path.default.resolve(source.fileName)}:${expression.getStart(source)}:${expression.getEnd()}:${expression.kind}`;
881
+ }
882
+ function evaluateLeavesFromExpression(expression, ctx, depth = 0) {
883
+ const resolved = unwrapExpression(expression);
884
+ markFile(ctx, resolved.getSourceFile());
885
+ const key = expressionKey(resolved);
886
+ if (ctx.activeExpressionKeys.has(key)) return [];
887
+ if (depth > MAX_RECURSION_DEPTH) return [];
888
+ ctx.activeExpressionKeys.add(key);
889
+ try {
890
+ if (import_typescript.default.isIdentifier(resolved)) {
891
+ const valueExpr = resolveIdentifierExpression(resolved, ctx, depth + 1);
892
+ if (!valueExpr) return [];
893
+ return evaluateLeavesFromExpression(valueExpr, ctx, depth + 1);
894
+ }
895
+ if (import_typescript.default.isPropertyAccessExpression(resolved) || import_typescript.default.isElementAccessExpression(resolved)) {
896
+ if (isAllAccess(resolved)) {
897
+ return evaluateLeavesFromExpression(resolved.expression, ctx, depth + 1);
898
+ }
899
+ const refExpr = resolvePropertyExpression(resolved, ctx, depth + 1);
900
+ if (refExpr) {
901
+ return evaluateLeavesFromExpression(refExpr, ctx, depth + 1);
902
+ }
903
+ return [];
904
+ }
905
+ if (import_typescript.default.isArrayLiteralExpression(resolved)) {
906
+ const leaves = [];
907
+ for (const element of resolved.elements) {
908
+ if (import_typescript.default.isSpreadElement(element)) {
909
+ leaves.push(...evaluateLeavesFromExpression(element.expression, ctx, depth + 1));
910
+ continue;
911
+ }
912
+ leaves.push(...evaluateLeavesFromExpression(element, ctx, depth + 1));
913
+ }
914
+ return leaves;
915
+ }
916
+ if (import_typescript.default.isCallExpression(resolved)) {
917
+ if (import_typescript.default.isIdentifier(resolved.expression)) {
918
+ const callName = resolved.expression.text;
919
+ if (callName === "finalize") {
920
+ const arg = resolved.arguments[0];
921
+ if (!arg) return [];
922
+ return evaluateLeavesFromExpression(arg, ctx, depth + 1);
923
+ }
924
+ if (callName === "mergeArrays") {
925
+ return resolved.arguments.flatMap(
926
+ (arg) => evaluateLeavesFromExpression(arg, ctx, depth + 1)
927
+ );
928
+ }
929
+ }
930
+ if (import_typescript.default.isPropertyAccessExpression(resolved.expression)) {
931
+ const prop = resolved.expression.name.text;
932
+ if (prop === "done") {
933
+ const branch2 = evaluateBranchExpression(
934
+ resolved.expression.expression,
935
+ ctx,
936
+ depth + 1
937
+ );
938
+ return branch2?.leaves ?? [];
939
+ }
940
+ }
941
+ const refExpr = evaluateExpressionReference(resolved, ctx, depth + 1);
942
+ if (refExpr) return evaluateLeavesFromExpression(refExpr, ctx, depth + 1);
943
+ ctx.unsupportedShapeSeen = true;
944
+ return [];
945
+ }
946
+ const branch = evaluateBranchExpression(resolved, ctx, depth + 1);
947
+ if (branch) return branch.leaves;
948
+ ctx.unsupportedShapeSeen = true;
949
+ return [];
950
+ } finally {
951
+ ctx.activeExpressionKeys.delete(key);
952
+ }
953
+ }
954
+ function resolveSchemaMetadata(expression, ctx) {
955
+ const resolved = unwrapExpression(expression);
956
+ if (import_typescript.default.isIdentifier(resolved)) {
957
+ const symbol = resolveSymbolFromNode(resolved, ctx);
958
+ const declaration = symbol?.declarations?.[0];
959
+ const locationNode = declaration ? import_typescript.default.isVariableDeclaration(declaration) ? declaration.name : declaration : resolved;
960
+ const sourceName = declaration && import_typescript.default.isVariableDeclaration(declaration) && import_typescript.default.isIdentifier(declaration.name) ? declaration.name.text : resolved.text;
961
+ return {
962
+ ...toLocation(locationNode),
963
+ sourceName,
964
+ tag: declaration ? void 0 : "<anonymous>"
965
+ };
966
+ }
967
+ if (import_typescript.default.isPropertyAccessExpression(resolved) || import_typescript.default.isElementAccessExpression(resolved)) {
968
+ return {
969
+ ...toLocation(resolved),
970
+ sourceName: trimPreview(resolved.getText()),
971
+ tag: "<expression>"
972
+ };
973
+ }
974
+ return {
975
+ ...toLocation(resolved),
976
+ sourceName: trimPreview(resolved.getText()),
977
+ tag: "<inline>"
978
+ };
979
+ }
980
+ function parseTsConfig(cwd, tsconfigPath) {
981
+ const resolvedTsconfig = tsconfigPath ? import_node_path.default.resolve(cwd, tsconfigPath) : import_typescript.default.findConfigFile(cwd, import_typescript.default.sys.fileExists, "tsconfig.json");
982
+ if (!resolvedTsconfig) {
983
+ return void 0;
984
+ }
985
+ const read = import_typescript.default.readConfigFile(resolvedTsconfig, import_typescript.default.sys.readFile);
986
+ if (read.error) {
987
+ throw new Error(import_typescript.default.flattenDiagnosticMessageText(read.error.messageText, "\n"));
988
+ }
989
+ const parsed = import_typescript.default.parseJsonConfigFileContent(
990
+ read.config,
991
+ import_typescript.default.sys,
992
+ import_node_path.default.dirname(resolvedTsconfig),
993
+ void 0,
994
+ resolvedTsconfig
995
+ );
996
+ const nonEmptyInputErrors = parsed.errors.filter((entry) => entry.code !== 18003);
997
+ if (nonEmptyInputErrors.length > 0) {
998
+ throw new Error(
999
+ nonEmptyInputErrors.map((entry) => import_typescript.default.flattenDiagnosticMessageText(entry.messageText, "\n")).join("\n")
1000
+ );
1001
+ }
1002
+ return { resolvedTsconfig, parsed };
1003
+ }
1004
+ function createProgramWithFallback(parsed, moduleFileAbs) {
1005
+ const base = import_typescript.default.createProgram({
1006
+ rootNames: parsed.fileNames,
1007
+ options: parsed.options
1008
+ });
1009
+ if (findSourceFile(base, moduleFileAbs)) {
1010
+ return base;
1011
+ }
1012
+ const rootNames = Array.from(/* @__PURE__ */ new Set([...parsed.fileNames, moduleFileAbs]));
1013
+ return import_typescript.default.createProgram({ rootNames, options: parsed.options });
1014
+ }
1015
+ function extractLeafSourceByAst({
1016
+ modulePath,
1017
+ exportName,
1018
+ tsconfigPath,
1019
+ cwd = process.cwd()
1020
+ }) {
1021
+ const parsedConfig = parseTsConfig(cwd, tsconfigPath);
1022
+ if (!parsedConfig) {
1023
+ return {
1024
+ sourceByLeaf: {},
1025
+ reason: "module_not_in_program",
1026
+ stats: { visitedSymbols: 0, visitedFiles: 0, unresolvedReferences: 0 }
1027
+ };
1028
+ }
1029
+ const moduleAbs = import_node_path.default.resolve(cwd, modulePath);
1030
+ const program = createProgramWithFallback(parsedConfig.parsed, moduleAbs);
1031
+ const checker = program.getTypeChecker();
1032
+ const moduleFile = findSourceFile(program, moduleAbs);
1033
+ if (!moduleFile) {
1034
+ return {
1035
+ sourceByLeaf: {},
1036
+ tsconfigPath: parsedConfig.resolvedTsconfig,
1037
+ reason: "module_not_in_program",
1038
+ stats: { visitedSymbols: 0, visitedFiles: 0, unresolvedReferences: 0 }
1039
+ };
1040
+ }
1041
+ const exportedExpression = resolveExportExpression(moduleFile, exportName, checker);
1042
+ if (!exportedExpression) {
1043
+ return {
1044
+ sourceByLeaf: {},
1045
+ tsconfigPath: parsedConfig.resolvedTsconfig,
1046
+ reason: "export_not_found",
1047
+ stats: { visitedSymbols: 0, visitedFiles: 1, unresolvedReferences: 0 }
1048
+ };
1049
+ }
1050
+ const ctx = {
1051
+ checker,
1052
+ activeExpressionKeys: /* @__PURE__ */ new Set(),
1053
+ activeSymbols: /* @__PURE__ */ new Set(),
1054
+ visitedSymbolKeys: /* @__PURE__ */ new Set(),
1055
+ visitedFilePaths: /* @__PURE__ */ new Set([import_node_path.default.resolve(moduleFile.fileName)]),
1056
+ unresolvedReferences: 0,
1057
+ unsupportedShapeSeen: false
1058
+ };
1059
+ const evaluatedLeaves = evaluateLeavesFromExpression(exportedExpression, ctx, 0);
1060
+ const sourceByLeaf = {};
1061
+ for (const leaf of evaluatedLeaves) {
1062
+ const key = buildLeafKey(leaf.method, leaf.path);
1063
+ const definition = {
1064
+ ...toLocation(leaf.definitionNode),
1065
+ symbolName: getNearestVariableName(leaf.definitionNode)
1066
+ };
1067
+ ctx.visitedFilePaths.add(definition.file);
1068
+ const schemas = {};
1069
+ for (const schemaKey of SCHEMA_KEYS) {
1070
+ const schemaExpression = leaf.schemas[schemaKey];
1071
+ if (!schemaExpression) continue;
1072
+ const schemaMeta = resolveSchemaMetadata(schemaExpression, ctx);
1073
+ ctx.visitedFilePaths.add(schemaMeta.file);
1074
+ schemas[schemaKey] = schemaMeta;
1075
+ }
1076
+ sourceByLeaf[key] = { definition, schemas };
1077
+ }
1078
+ const reason = Object.keys(sourceByLeaf).length > 0 ? void 0 : ctx.unsupportedShapeSeen ? "unsupported_expression_shape" : "resolved_zero_leaves";
1079
+ return {
1080
+ sourceByLeaf,
1081
+ tsconfigPath: parsedConfig.resolvedTsconfig,
1082
+ reason,
1083
+ stats: {
1084
+ visitedSymbols: ctx.visitedSymbolKeys.size,
1085
+ visitedFiles: ctx.visitedFilePaths.size,
1086
+ unresolvedReferences: ctx.unresolvedReferences
1087
+ }
1088
+ };
1089
+ }
1090
+
1091
+ // src/exportFinalizedLeaves.ts
1092
+ function isRegistry(value) {
1093
+ return typeof value === "object" && value !== null && "all" in value && "byKey" in value;
1094
+ }
1095
+ function getLeaves(input) {
1096
+ return isRegistry(input) ? input.all : input;
1097
+ }
1098
+ function buildMeta(sourceExtraction) {
1099
+ return {
1100
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
1101
+ description: "Finalized RRRoutes leaves export with serialized schemas and flattened schema paths for downstream processing.",
1102
+ sourceExtraction,
1103
+ fieldCatalog: {
1104
+ leaf: ["key", "method", "path", "cfg"],
1105
+ cfg: [
1106
+ "description?",
1107
+ "summary?",
1108
+ "docsGroup?",
1109
+ "tags?",
1110
+ "deprecated?",
1111
+ "stability?",
1112
+ "docsHidden?",
1113
+ "docsMeta?",
1114
+ "feed?",
1115
+ "bodyFiles?",
1116
+ "schemas"
1117
+ ],
1118
+ schemaNode: [
1119
+ "kind",
1120
+ "optional?",
1121
+ "nullable?",
1122
+ "description?",
1123
+ "properties?",
1124
+ "element?",
1125
+ "union?",
1126
+ "literal?",
1127
+ "enumValues?"
1128
+ ],
1129
+ flatSchemaEntry: ["type", "nullable", "optional", "literal?"]
1130
+ },
1131
+ flattening: {
1132
+ notation: "dot+[]",
1133
+ unionBranchSuffix: "-N",
1134
+ sections: ["params", "query", "body", "output"]
1135
+ }
1136
+ };
1137
+ }
1138
+ var BAKED_PAYLOAD_MARKER = "<!--__FINALIZED_LEAVES_BAKED_PAYLOAD__-->";
1139
+ function escapePayloadForInlineScript(payload) {
1140
+ return JSON.stringify(payload).replace(/<\//g, "<\\/").replace(/<!--/g, "<\\!--");
1141
+ }
1142
+ function injectPayloadIntoViewerHtml(htmlTemplate, payload) {
1143
+ const payloadScript = `${BAKED_PAYLOAD_MARKER}
1144
+ <script id="finalized-leaves-baked-payload">window.__FINALIZED_LEAVES_PAYLOAD = ${escapePayloadForInlineScript(
1145
+ payload
1146
+ )};</script>`;
1147
+ if (htmlTemplate.includes(BAKED_PAYLOAD_MARKER)) {
1148
+ return htmlTemplate.replace(BAKED_PAYLOAD_MARKER, payloadScript);
1149
+ }
1150
+ if (htmlTemplate.includes("</body>")) {
1151
+ return htmlTemplate.replace("</body>", `${payloadScript}
1152
+ </body>`);
1153
+ }
1154
+ return `${payloadScript}
1155
+ ${htmlTemplate}`;
1156
+ }
1157
+ async function resolveViewerTemplatePath(viewerTemplateFile) {
1158
+ if (viewerTemplateFile) {
1159
+ const resolved = import_node_path2.default.resolve(viewerTemplateFile);
1160
+ await import_promises.default.access(resolved);
1161
+ return resolved;
1162
+ }
1163
+ const candidates = [
1164
+ import_node_path2.default.resolve(
1165
+ process.cwd(),
1166
+ "node_modules/@emeryld/rrroutes-export/tools/finalized-leaves-viewer.html"
1167
+ ),
1168
+ import_node_path2.default.resolve(
1169
+ process.cwd(),
1170
+ "tools/finalized-leaves-viewer.html"
1171
+ ),
1172
+ import_node_path2.default.resolve(
1173
+ process.cwd(),
1174
+ "packages/export/tools/finalized-leaves-viewer.html"
1175
+ )
1176
+ ];
1177
+ for (const candidate of candidates) {
1178
+ try {
1179
+ await import_promises.default.access(candidate);
1180
+ return candidate;
1181
+ } catch {
1182
+ }
1183
+ }
1184
+ return void 0;
1185
+ }
1186
+ async function writeJsonExport(payload, outFile) {
1187
+ const resolved = import_node_path2.default.resolve(outFile);
1188
+ await import_promises.default.mkdir(import_node_path2.default.dirname(resolved), { recursive: true });
1189
+ await import_promises.default.writeFile(resolved, `${JSON.stringify(payload, null, 2)}
1190
+ `, "utf8");
1191
+ return resolved;
1192
+ }
1193
+ async function writeBakedHtmlExport(payload, htmlFile, viewerTemplateFile) {
1194
+ const templatePath = await resolveViewerTemplatePath(viewerTemplateFile);
1195
+ const template = templatePath ? await import_promises.default.readFile(templatePath, "utf8") : DEFAULT_VIEWER_TEMPLATE;
1196
+ const baked = injectPayloadIntoViewerHtml(template, payload);
1197
+ const resolved = import_node_path2.default.resolve(htmlFile);
1198
+ await import_promises.default.mkdir(import_node_path2.default.dirname(resolved), { recursive: true });
1199
+ await import_promises.default.writeFile(resolved, baked, "utf8");
1200
+ return resolved;
1201
+ }
1202
+ async function openHtmlInBrowser(filePath) {
1203
+ const resolved = import_node_path2.default.resolve(filePath);
1204
+ const platform = process.platform;
1205
+ if (platform === "darwin") {
1206
+ (0, import_node_child_process.spawn)("open", [resolved], { detached: true, stdio: "ignore" }).unref();
1207
+ return;
1208
+ }
1209
+ if (platform === "win32") {
1210
+ (0, import_node_child_process.spawn)("cmd", ["/c", "start", "", resolved], {
1211
+ detached: true,
1212
+ stdio: "ignore"
1213
+ }).unref();
1214
+ return;
1215
+ }
1216
+ (0, import_node_child_process.spawn)("xdg-open", [resolved], { detached: true, stdio: "ignore" }).unref();
1217
+ }
1218
+ async function writeFinalizedLeavesExport(payload, outFileOrOptions) {
1219
+ const options = typeof outFileOrOptions === "string" ? { outFile: outFileOrOptions } : outFileOrOptions;
1220
+ const written = {};
1221
+ if (options.outFile) {
1222
+ written.outFile = await writeJsonExport(payload, options.outFile);
1223
+ }
1224
+ if (options.htmlFile) {
1225
+ written.htmlFile = await writeBakedHtmlExport(
1226
+ payload,
1227
+ options.htmlFile,
1228
+ options.viewerTemplateFile
1229
+ );
1230
+ }
1231
+ if (options.openOnFinish) {
1232
+ if (!written.htmlFile) {
1233
+ throw new Error(
1234
+ "openOnFinish requires htmlFile. Provide htmlFile to open the baked viewer."
1235
+ );
1236
+ }
1237
+ await openHtmlInBrowser(written.htmlFile);
1238
+ }
1239
+ return written;
1240
+ }
1241
+ async function exportFinalizedLeaves(input, options = {}) {
1242
+ const leaves = getLeaves(input);
1243
+ const serializedLeaves = serializeLeavesContract(leaves, options);
1244
+ const schemaFlatByLeaf = Object.fromEntries(
1245
+ serializedLeaves.map((leaf) => [leaf.key, flattenLeafSchemas(leaf)])
1246
+ );
1247
+ const sourceByLeaf = {};
1248
+ let sourceExtraction;
1249
+ if (options.includeSource) {
1250
+ const modulePath = options.sourceModulePath;
1251
+ const exportName = options.sourceExportName ?? "leaves";
1252
+ if (modulePath) {
1253
+ const extracted = extractLeafSourceByAst({
1254
+ modulePath,
1255
+ exportName,
1256
+ tsconfigPath: options.tsconfigPath
1257
+ });
1258
+ const allowedLeafKeys = new Set(serializedLeaves.map((leaf) => leaf.key));
1259
+ for (const [key, source] of Object.entries(extracted.sourceByLeaf)) {
1260
+ if (allowedLeafKeys.has(key)) {
1261
+ sourceByLeaf[key] = source;
1262
+ }
1263
+ }
1264
+ sourceExtraction = {
1265
+ mode: "ast",
1266
+ enabled: true,
1267
+ modulePath: import_node_path2.default.resolve(modulePath),
1268
+ exportName,
1269
+ tsconfigPath: extracted.tsconfigPath,
1270
+ resolvedLeafCount: Object.keys(sourceByLeaf).length,
1271
+ reason: extracted.reason,
1272
+ stats: extracted.stats
1273
+ };
1274
+ } else {
1275
+ sourceExtraction = {
1276
+ mode: "ast",
1277
+ enabled: false,
1278
+ exportName,
1279
+ tsconfigPath: options.tsconfigPath ? import_node_path2.default.resolve(options.tsconfigPath) : void 0,
1280
+ resolvedLeafCount: 0,
1281
+ reason: "resolved_zero_leaves",
1282
+ stats: {
1283
+ visitedSymbols: 0,
1284
+ visitedFiles: 0,
1285
+ unresolvedReferences: 0
1286
+ }
1287
+ };
1288
+ }
1289
+ }
1290
+ const payload = {
1291
+ _meta: buildMeta(sourceExtraction),
1292
+ leaves: serializedLeaves,
1293
+ schemaFlatByLeaf,
1294
+ sourceByLeaf: options.includeSource && Object.keys(sourceByLeaf).length > 0 ? sourceByLeaf : void 0
1295
+ };
1296
+ if (options.outFile || options.htmlFile) {
1297
+ await writeFinalizedLeavesExport(payload, {
1298
+ outFile: options.outFile,
1299
+ htmlFile: options.htmlFile,
1300
+ viewerTemplateFile: options.viewerTemplateFile,
1301
+ openOnFinish: options.openOnFinish
1302
+ });
1303
+ }
1304
+ return payload;
1305
+ }
1306
+
1307
+ // src/exportFinalizedLeaves.cli.ts
1308
+ var import_node_path3 = __toESM(require("path"), 1);
1309
+ var import_node_url = require("url");
1310
+ function parseFinalizedLeavesCliArgs(argv) {
1311
+ const args = /* @__PURE__ */ new Map();
1312
+ let withSource = false;
1313
+ for (let i = 0; i < argv.length; i += 1) {
1314
+ const key = argv[i];
1315
+ if (key === "--") continue;
1316
+ if (!key.startsWith("--")) continue;
1317
+ if (key === "--with-source") {
1318
+ withSource = true;
1319
+ continue;
1320
+ }
1321
+ const value = argv[i + 1];
1322
+ if (!value || value.startsWith("--")) {
1323
+ throw new Error(`Missing value for ${key}`);
1324
+ }
1325
+ args.set(key, value);
1326
+ i += 1;
1327
+ }
1328
+ const modulePath = args.get("--module");
1329
+ if (!modulePath) {
1330
+ throw new Error("Missing required --module argument");
1331
+ }
1332
+ return {
1333
+ modulePath,
1334
+ exportName: args.get("--export") ?? "leaves",
1335
+ outFile: args.get("--out") ?? "finalized-leaves.export.json",
1336
+ withSource,
1337
+ tsconfigPath: args.get("--tsconfig") ?? void 0
1338
+ };
1339
+ }
1340
+ async function loadFinalizedLeavesInput({
1341
+ modulePath,
1342
+ exportName
1343
+ }) {
1344
+ const resolvedModule = import_node_path3.default.resolve(process.cwd(), modulePath);
1345
+ const mod = await import((0, import_node_url.pathToFileURL)(resolvedModule).href);
1346
+ const value = mod[exportName] ?? (mod.default && mod.default[exportName]);
1347
+ if (!value) {
1348
+ throw new Error(`Export "${exportName}" not found in module: ${resolvedModule}`);
1349
+ }
1350
+ return value;
1351
+ }
1352
+ async function runExportFinalizedLeavesCli(argv) {
1353
+ const args = parseFinalizedLeavesCliArgs(argv);
1354
+ const input = await loadFinalizedLeavesInput(args);
1355
+ const payload = await exportFinalizedLeaves(input, {
1356
+ outFile: args.outFile,
1357
+ includeSource: args.withSource,
1358
+ tsconfigPath: args.tsconfigPath,
1359
+ sourceModulePath: args.modulePath,
1360
+ sourceExportName: args.exportName
1361
+ });
1362
+ return {
1363
+ payload,
1364
+ outFile: import_node_path3.default.resolve(args.outFile)
1365
+ };
1366
+ }
1367
+ // Annotate the CommonJS export names for ESM import in node:
1368
+ 0 && (module.exports = {
1369
+ DEFAULT_VIEWER_TEMPLATE,
1370
+ clearSchemaIntrospectionHandlers,
1371
+ createSchemaIntrospector,
1372
+ exportFinalizedLeaves,
1373
+ extractLeafSourceByAst,
1374
+ flattenLeafSchemas,
1375
+ flattenSerializableSchema,
1376
+ introspectSchema,
1377
+ loadFinalizedLeavesInput,
1378
+ parseFinalizedLeavesCliArgs,
1379
+ registerSchemaIntrospectionHandler,
1380
+ runExportFinalizedLeavesCli,
1381
+ serializableSchemaKinds,
1382
+ serializeLeafContract,
1383
+ serializeLeavesContract,
1384
+ writeFinalizedLeavesExport
1385
+ });
1386
+ //# sourceMappingURL=index.cjs.map