@t0.labs/daxta 0.4.5 → 0.4.7

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/README.md CHANGED
@@ -39,27 +39,51 @@ Jest finishes — Docs ready on /docs
39
39
 
40
40
 
41
41
 
42
- ## Install
42
+ ## CLI ile kurulum
43
+
44
+ Tek komut — dependency, `apiDocs(app)`, Jest plugin, `daxta.config.ts` ve sidebar tercihler:
43
45
 
44
46
  ```bash
45
47
  pnpm dlx @t0.labs/daxta install
46
- # or
48
+ # veya
47
49
  npx @t0.labs/daxta install
48
50
  ```
49
51
 
50
- Wires `apiDocs(app)` into your Nest entry and hooks Jest. Then:
52
+ Kurulum sırasında sorulur: Nest entry, test script, docs folder order (`role-resource` / `resource-role`), `{id}` fold, example label stili.
53
+
54
+ Sonra:
55
+
56
+ ```bash
57
+ pnpm run test:integration # test bitince Docs ready
58
+ DAXTA_DOCS=true pnpm start:dev # app portunda /docs
59
+ ```
51
60
 
52
61
  ```ts
53
62
  import { apiDocs } from '@t0.labs/daxta';
54
63
 
55
- apiDocs(app); // requires DAXTA_DOCS in the environment
64
+ apiDocs(app); // DAXTA_DOCS zorunlu (true | false)
56
65
  ```
57
66
 
67
+ Flags: `--yes` · `--dry-run` · `--skip-main` · `--skip-dep` · `--main <path>` · `--fast`
68
+
69
+ ## CLI ile kaldırma
70
+
58
71
  ```bash
59
- pnpm run test:integration # Docs ready when Jest finishes
60
- DAXTA_DOCS=true pnpm start:dev # open /docs on the app port
72
+ pnpm dlx @t0.labs/daxta uninstall
73
+ # veya
74
+ npx @t0.labs/daxta uninstall
61
75
  ```
62
76
 
77
+ Otomatik temizler:
78
+
79
+ - `apiDocs` + `@t0.labs/daxta` import (`main.ts`)
80
+ - Jest `setup` + `jest-reporter` hooks
81
+ - `daxta.config.*` ve `daxta/` output
82
+ - `.gitignore` / `.env` içindeki DAxTA satırları
83
+ - `@t0.labs/daxta` paketi
84
+
85
+ Flags: `--yes` · `--dry-run` · `--keep-dep` (paketi bırakıp sadece wiring’i sök) · `--fast`
86
+
63
87
 
64
88
 
65
89
  ## Docs UI
@@ -87,13 +111,14 @@ DAXTA_DOCS=false # no-op (must still be set)
87
111
  ## Commands
88
112
 
89
113
  ```bash
90
- daxta install # one-shot setup (+ sidebar layout prompts)
91
- daxta migrate # after a package bump (+ same sidebar prompts)
92
- daxta build # rebuild OpenAPI/HTML from recorded hits
93
- daxta serve # optional standalone viewer (prefer apiDocs on the app)
94
- daxta tree # re-run sidebar folder prompts anytime
95
- daxta fields … # export field map for an operation
96
- daxta call … # CLI Try-it
114
+ daxta install # CLI kurulum (+ sidebar prompts)
115
+ daxta uninstall # CLI kaldırma (komple)
116
+ daxta migrate # paket bump sonrası upgrade (+ sidebar prompts)
117
+ daxta build # OpenAPI/HTML rebuild
118
+ daxta serve # standalone viewer (opsiyonel)
119
+ daxta tree # sidebar / example tercihlerini yeniden sor
120
+ daxta fields … # field map export
121
+ daxta call … # CLI Try-it
97
122
  ```
98
123
 
99
124
  ### Docs presentation (`daxta install` / `daxta migrate` / `daxta tree`)
@@ -102,11 +127,12 @@ Company-wide choices (saved in `daxta.config.ts`):
102
127
 
103
128
  | Option | Meaning |
104
129
  | --- | --- |
105
- | `treeLayout` | `role-resource` (`v1 › admin › baskets`) or `resource-role` (`v1 › baskets › admin`) |
130
+ | `treeLayout` | `role-resource` (`v1 › admin › baskets`) or `resource-role` (`v1 › baskets › admin`) — sidebar **and** OpenAPI export path keys |
106
131
  | `treeSkipParams` | Don’t nest folders under `{id}` (recommended `true`) |
107
- | `treeMaxDepth` | Optional max folder depth (e.g. `3`) |
108
132
  | `exampleLabelStyle` | OpenAPI example labels: `status-title-case` / `status-case` / `full` |
109
133
 
134
+ OpenAPI export remaps path keys to match the sidebar tree. Real URLs are kept on `x-daxta-url-path` when the layout differs (e.g. `/v1/admin/baskets` → export `/v1/baskets/admin`).
135
+
110
136
  Example label (`status-title-case`):
111
137
 
112
138
  ```text
@@ -1256,7 +1256,21 @@
1256
1256
  return out;
1257
1257
  };
1258
1258
 
1259
- /** Real URL paths + tags from sidebar tree segments. */
1259
+ /** Path keys follow sidebar tree; real URL kept on x-daxta-url-path when remapped. */
1260
+ const exportPathFromTree = (urlPath, treeSegments) => {
1261
+ const originalParts = urlPath.split("/").filter(Boolean);
1262
+ const paramIdx = originalParts.findIndex((part) => String(part).startsWith("{"));
1263
+ const tail = paramIdx >= 0 ? originalParts.slice(paramIdx) : [];
1264
+ const treeHasParam = treeSegments.some((part) => String(part).startsWith("{"));
1265
+ const parts =
1266
+ treeSegments.length === 0
1267
+ ? originalParts
1268
+ : treeHasParam || paramIdx < 0
1269
+ ? treeSegments
1270
+ : [...treeSegments, ...tail];
1271
+ return "/" + parts.join("/");
1272
+ };
1273
+
1260
1274
  const toExportSpec = (source) => {
1261
1275
  const pathsIn = source.paths || {};
1262
1276
  const pathsOut = {};
@@ -1264,10 +1278,23 @@
1264
1278
 
1265
1279
  for (const [urlPath, pathItem] of Object.entries(pathsIn)) {
1266
1280
  if (!pathItem || typeof pathItem !== "object") continue;
1267
- const itemOut = {};
1281
+
1282
+ let treeSegments = null;
1283
+ for (const [method, operation] of Object.entries(pathItem)) {
1284
+ if (!HTTP_EXPORT.includes(method) || !operation || typeof operation !== "object") continue;
1285
+ treeSegments = operation["x-tree-segments"] || urlPath.split("/").filter(Boolean);
1286
+ break;
1287
+ }
1288
+ if (!treeSegments) treeSegments = urlPath.split("/").filter(Boolean);
1289
+
1290
+ const exportPath = exportPathFromTree(urlPath, treeSegments);
1291
+ const itemOut = { ...(pathsOut[exportPath] || {}) };
1292
+
1268
1293
  for (const [method, operation] of Object.entries(pathItem)) {
1269
1294
  if (!HTTP_EXPORT.includes(method) || !operation || typeof operation !== "object") {
1270
- if (!HTTP_EXPORT.includes(method)) itemOut[method] = stripExt(operation);
1295
+ if (!HTTP_EXPORT.includes(method) && itemOut[method] === undefined) {
1296
+ itemOut[method] = stripExt(operation);
1297
+ }
1271
1298
  continue;
1272
1299
  }
1273
1300
  const segments = operation["x-tree-segments"] || urlPath.split("/").filter(Boolean);
@@ -1276,9 +1303,10 @@
1276
1303
  const tag = tagParts.length ? tagParts.join(" / ") : "API";
1277
1304
  cleaned.tags = [tag];
1278
1305
  tagNames.add(tag);
1306
+ if (exportPath !== urlPath) cleaned["x-daxta-url-path"] = urlPath;
1279
1307
  itemOut[method] = cleaned;
1280
1308
  }
1281
- pathsOut[urlPath] = itemOut;
1309
+ pathsOut[exportPath] = itemOut;
1282
1310
  }
1283
1311
 
1284
1312
  const ordered = {};
@@ -15,7 +15,7 @@ export declare function declaredMethods(test?: string): string[] | null;
15
15
  export declare function pathSegments(pathTemplate: string): string[];
16
16
  /**
17
17
  * Sidebar / export-tag folder segments for a path.
18
- * Honors treeLayout, treeSkipParams, treeMaxDepth, and per-path overrides.
18
+ * Honors treeLayout, treeSkipParams, and per-path overrides.
19
19
  */
20
20
  export declare function treePathSegments(pathTemplate: string): string[];
21
21
  export declare function viewerTreeConfig(): {
@@ -24,7 +24,6 @@ export declare function viewerTreeConfig(): {
24
24
  docsPath: string;
25
25
  treeLayout: TreeLayout;
26
26
  treeSkipParams: boolean;
27
- treeMaxDepth: number | null;
28
27
  treePathOverrides: Record<string, string[]>;
29
28
  exampleLabelStyle: "status-case" | "status-title-case" | "full";
30
29
  };
@@ -49,21 +49,17 @@ function applyLayout(parts, layout) {
49
49
  }
50
50
  return parts;
51
51
  }
52
- function applyFold(parts, skipParams, maxDepth) {
53
- let next = parts;
54
- if (skipParams) {
55
- const paramIdx = next.findIndex((part) => part.startsWith('{'));
56
- if (paramIdx >= 0)
57
- next = next.slice(0, paramIdx);
58
- }
59
- if (typeof maxDepth === 'number' && maxDepth > 0) {
60
- next = next.slice(0, maxDepth);
61
- }
62
- return next;
52
+ function applyFold(parts, skipParams) {
53
+ if (!skipParams)
54
+ return parts;
55
+ const paramIdx = parts.findIndex((part) => part.startsWith('{'));
56
+ if (paramIdx < 0)
57
+ return parts;
58
+ return parts.slice(0, paramIdx);
63
59
  }
64
60
  /**
65
61
  * Sidebar / export-tag folder segments for a path.
66
- * Honors treeLayout, treeSkipParams, treeMaxDepth, and per-path overrides.
62
+ * Honors treeLayout, treeSkipParams, and per-path overrides.
67
63
  */
68
64
  function treePathSegments(pathTemplate) {
69
65
  const config = (0, config_1.getConfig)();
@@ -75,7 +71,7 @@ function treePathSegments(pathTemplate) {
75
71
  return exact;
76
72
  const layout = (0, config_1.normalizeTreeLayout)(config.treeLayout);
77
73
  const parts = applyLayout(pathTemplate.split('/').filter(Boolean), layout);
78
- return applyFold(parts, config.treeSkipParams !== false, config.treeMaxDepth);
74
+ return applyFold(parts, config.treeSkipParams !== false);
79
75
  }
80
76
  function viewerTreeConfig() {
81
77
  const config = (0, config_1.getConfig)();
@@ -85,7 +81,6 @@ function viewerTreeConfig() {
85
81
  docsPath: config.docsPath,
86
82
  treeLayout: (0, config_1.normalizeTreeLayout)(config.treeLayout),
87
83
  treeSkipParams: config.treeSkipParams !== false,
88
- treeMaxDepth: config.treeMaxDepth ?? null,
89
84
  treePathOverrides: config.treePathOverrides,
90
85
  exampleLabelStyle: config.exampleLabelStyle ?? 'status-title-case',
91
86
  };
@@ -5,6 +5,8 @@ export declare function findMainCandidates(cwd: string): string[];
5
5
  */
6
6
  export declare function resolveMainPath(cwd: string, candidates: string[]): Promise<string | null>;
7
7
  export declare function injectApiDocs(filePath: string, dryRun?: boolean): string;
8
+ /** Remove `apiDocs(...)` calls and `@t0.labs/daxta` imports from a Nest entry file. */
9
+ export declare function removeApiDocs(filePath: string, dryRun?: boolean): string;
8
10
  export type InjectMainOptions = {
9
11
  cwd?: string;
10
12
  dryRun?: boolean;
@@ -36,6 +36,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.findMainCandidates = findMainCandidates;
37
37
  exports.resolveMainPath = resolveMainPath;
38
38
  exports.injectApiDocs = injectApiDocs;
39
+ exports.removeApiDocs = removeApiDocs;
39
40
  exports.resolveMainTarget = resolveMainTarget;
40
41
  const readline_1 = require("readline");
41
42
  const fs_1 = require("fs");
@@ -191,6 +192,31 @@ function injectApiDocs(filePath, dryRun = false) {
191
192
  (0, fs_1.writeFileSync)(filePath, next);
192
193
  return `injected apiDocs() into ${path.relative(process.cwd(), filePath)}`;
193
194
  }
195
+ /** Remove `apiDocs(...)` calls and `@t0.labs/daxta` imports from a Nest entry file. */
196
+ function removeApiDocs(filePath, dryRun = false) {
197
+ const before = (0, fs_1.readFileSync)(filePath, 'utf8');
198
+ let next = before;
199
+ next = next.replace(/^[ \t]*apiDocs\s*\([^;]*\)\s*;?[ \t]*\n?/gm, '');
200
+ next = next.replace(/^[ \t]*\b(?:mountDaxtaDocs|docs)\s*\([^;]*\)\s*;?[ \t]*\n?/gm, '');
201
+ next = next.replace(/^[ \t]*import\s*\{[^}]*\bapiDocs\b[^}]*\}\s*from\s*['"]@t0\.labs\/daxta['"]\s*;?[ \t]*\n?/gm, (line) => {
202
+ // Drop whole import if only apiDocs (and legacy aliases); otherwise strip the name
203
+ const names = line.match(/\{([^}]*)\}/)?.[1] ?? '';
204
+ const remaining = names
205
+ .split(',')
206
+ .map((part) => part.trim())
207
+ .filter((part) => part && !/^(apiDocs|mountDaxtaDocs|docs)$/.test(part));
208
+ if (!remaining.length)
209
+ return '';
210
+ return line.replace(/\{[^}]*\}/, `{ ${remaining.join(', ')} }`);
211
+ });
212
+ // Orphan blank lines left after removals — light tidy
213
+ next = next.replace(/\n{3,}/g, '\n\n');
214
+ if (next === before)
215
+ return `no apiDocs in ${path.relative(process.cwd(), filePath)}`;
216
+ if (!dryRun)
217
+ (0, fs_1.writeFileSync)(filePath, next);
218
+ return `removed apiDocs from ${path.relative(process.cwd(), filePath)}`;
219
+ }
194
220
  /** Resolve which file to inject into (prompt / --main / --yes). Null = skip. */
195
221
  async function resolveMainTarget(options = {}) {
196
222
  const cwd = options.cwd ?? process.cwd();
@@ -116,7 +116,6 @@ export default defineConfig({
116
116
  docsPath: '/docs',
117
117
  treeLayout: 'role-resource',
118
118
  treeSkipParams: true,
119
- treeMaxDepth: null,
120
119
  exampleLabelStyle: 'status-title-case',
121
120
  fieldsFile: 'daxta/out/daxta.fields.json',
122
121
  });
@@ -11,4 +11,6 @@ export declare function resolveJestConfigPath(cwd: string, options: {
11
11
  export declare function injectJestHooks(jestConfigPath: string, dryRun?: boolean): string[];
12
12
  /** Restore package.json script if it was wrapped as `daxta test --yes`. */
13
13
  export declare function unwrapDaxtaTestScript(scripts: Record<string, string>, scriptName: string, originalCommand: string): boolean;
14
+ /** Remove DAxTA Jest setup + reporter from a JSON/JS config. */
15
+ export declare function removeJestHooks(jestConfigPath: string, dryRun?: boolean): string[];
14
16
  export {};
@@ -37,6 +37,7 @@ exports.loadJestJson = loadJestJson;
37
37
  exports.resolveJestConfigPath = resolveJestConfigPath;
38
38
  exports.injectJestHooks = injectJestHooks;
39
39
  exports.unwrapDaxtaTestScript = unwrapDaxtaTestScript;
40
+ exports.removeJestHooks = removeJestHooks;
40
41
  const fs_1 = require("fs");
41
42
  const path = __importStar(require("path"));
42
43
  const discover_test_1 = require("./discover-test");
@@ -209,3 +210,102 @@ function unwrapDaxtaTestScript(scripts, scriptName, originalCommand) {
209
210
  scripts[scriptName] = originalCommand;
210
211
  return true;
211
212
  }
213
+ function removeStringFromArrayLiteral(source, key, needle) {
214
+ const range = findArrayPropRange(source, key);
215
+ if (!range)
216
+ return { source, removed: false };
217
+ const inner = source.slice(range.open + 1, range.close);
218
+ if (!inner.includes(needle))
219
+ return { source, removed: false };
220
+ let nextInner = inner
221
+ .replace(new RegExp(`(['"])${needle.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\1\\s*,\\s*`), '')
222
+ .replace(new RegExp(`,\\s*(['"])${needle.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\1`), '')
223
+ .replace(new RegExp(`(['"])${needle.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\1`), '');
224
+ return {
225
+ source: `${source.slice(0, range.open + 1)}${nextInner}${source.slice(range.close)}`,
226
+ removed: true,
227
+ };
228
+ }
229
+ function removeReporterFromJsSource(source) {
230
+ // Single-string reporter entry
231
+ let { source: next, removed } = removeStringFromArrayLiteral(source, 'reporters', REPORTER);
232
+ // Array tuple reporter: [ '@t0.labs/daxta/jest-reporter', { ... } ],
233
+ const tupleRe = new RegExp(`,?\\s*\\[\\s*['"]${REPORTER.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}['"]\\s*,\\s*\\{[\\s\\S]*?\\}\\s*\\]\\s*,?`);
234
+ if (tupleRe.test(next)) {
235
+ next = next.replace(tupleRe, (match) => (match.trim().startsWith(',') ? '' : ''));
236
+ // Clean double commas / leading commas in array
237
+ const range = findArrayPropRange(next, 'reporters');
238
+ if (range) {
239
+ let inner = next.slice(range.open + 1, range.close);
240
+ inner = inner.replace(/,\s*,/g, ',').replace(/^\s*,/, '').replace(/,\s*$/, '');
241
+ next = `${next.slice(0, range.open + 1)}${inner}${next.slice(range.close)}`;
242
+ }
243
+ removed = true;
244
+ }
245
+ return { source: next, removed };
246
+ }
247
+ function removeFromJsSource(source) {
248
+ const notes = [];
249
+ let next = source;
250
+ const setup = removeStringFromArrayLiteral(next, 'setupFilesAfterEnv', SETUP);
251
+ next = setup.source;
252
+ if (setup.removed)
253
+ notes.push(`setupFilesAfterEnv -= ${SETUP}`);
254
+ const reporters = removeReporterFromJsSource(next);
255
+ next = reporters.source;
256
+ if (reporters.removed)
257
+ notes.push(`reporters -= ${REPORTER}`);
258
+ else {
259
+ const plain = removeStringFromArrayLiteral(next, 'reporters', REPORTER);
260
+ next = plain.source;
261
+ if (plain.removed)
262
+ notes.push(`reporters -= ${REPORTER}`);
263
+ }
264
+ return { source: next, notes };
265
+ }
266
+ function removeFromJsonConfig(filePath, dryRun) {
267
+ const notes = [];
268
+ const data = loadJestJson(filePath);
269
+ if (Array.isArray(data.setupFilesAfterEnv)) {
270
+ const before = data.setupFilesAfterEnv;
271
+ const after = before.filter((entry) => entry !== SETUP);
272
+ if (after.length !== before.length) {
273
+ data.setupFilesAfterEnv = after;
274
+ notes.push(`setupFilesAfterEnv -= ${SETUP}`);
275
+ }
276
+ }
277
+ if (Array.isArray(data.reporters)) {
278
+ const before = data.reporters;
279
+ const after = before.filter((entry) => {
280
+ if (entry === REPORTER)
281
+ return false;
282
+ if (Array.isArray(entry) && entry[0] === REPORTER)
283
+ return false;
284
+ return true;
285
+ });
286
+ if (after.length !== before.length) {
287
+ data.reporters = after.length ? after : ['default'];
288
+ notes.push(`reporters -= ${REPORTER}`);
289
+ }
290
+ }
291
+ if (!dryRun && notes.length) {
292
+ (0, fs_1.writeFileSync)(filePath, `${JSON.stringify(data, null, 2)}\n`);
293
+ }
294
+ return notes;
295
+ }
296
+ /** Remove DAxTA Jest setup + reporter from a JSON/JS config. */
297
+ function removeJestHooks(jestConfigPath, dryRun = false) {
298
+ if (!(0, fs_1.existsSync)(jestConfigPath))
299
+ return [];
300
+ if (isJsonConfigPath(jestConfigPath)) {
301
+ return removeFromJsonConfig(jestConfigPath, dryRun);
302
+ }
303
+ if (!isJsLikeConfigPath(jestConfigPath))
304
+ return [];
305
+ const original = (0, fs_1.readFileSync)(jestConfigPath, 'utf8');
306
+ const { source, notes } = removeFromJsSource(original);
307
+ if (!dryRun && notes.length && source !== original) {
308
+ (0, fs_1.writeFileSync)(jestConfigPath, source);
309
+ }
310
+ return notes;
311
+ }
package/dist/cli/main.js CHANGED
@@ -9,12 +9,14 @@ const install_1 = require("./install");
9
9
  const migrate_1 = require("./migrate");
10
10
  const test_1 = require("./test");
11
11
  const tree_1 = require("./tree");
12
+ const uninstall_1 = require("./uninstall");
12
13
  function usage() {
13
14
  console.log(`DAxTA CLI (@t0.labs/daxta)
14
15
 
15
16
  Usage:
16
17
  daxta install [--dry-run] [--skip-dep] [--skip-main] [--yes] [--main <path>] [--fast]
17
18
  daxta init (alias of install)
19
+ daxta uninstall [--yes] [--dry-run] [--keep-dep] [--fast]
18
20
  daxta migrate [--yes] (force upgrade + sidebar prompts)
19
21
  daxta test [--script <name>] [--config <jest.json>] [--serve] [--port <n>] [--yes]
20
22
  daxta build
@@ -28,6 +30,10 @@ One-shot setup:
28
30
  pnpm dlx @t0.labs/daxta install
29
31
  npx @t0.labs/daxta install
30
32
 
33
+ Remove completely:
34
+ pnpm dlx @t0.labs/daxta uninstall
35
+ npx @t0.labs/daxta uninstall
36
+
31
37
  daxta test = forwards to your package script (Jest stays parent; DAxTA is a plugin)
32
38
  daxta tree = choose how paths appear in the /docs sidebar
33
39
  `);
@@ -80,6 +86,15 @@ async function main() {
80
86
  await (0, tree_1.runTreeWizard)({ embedded: true, yes: Boolean(flags.yes) });
81
87
  return;
82
88
  }
89
+ if (command === 'uninstall' || command === 'remove') {
90
+ await (0, uninstall_1.uninstallDaxta)({
91
+ dryRun: Boolean(flags['dry-run']),
92
+ yes: Boolean(flags.yes),
93
+ fast: Boolean(flags.fast),
94
+ keepDep: Boolean(flags['keep-dep']),
95
+ });
96
+ return;
97
+ }
83
98
  (0, migrate_1.reportMigration)((0, migrate_1.migrateProject)());
84
99
  (0, config_1.resetConfig)();
85
100
  (0, config_1.getConfig)(true);
package/dist/cli/tree.js CHANGED
@@ -23,7 +23,7 @@ function normalizePathInput(raw) {
23
23
  return trimmed;
24
24
  return trimmed.startsWith('/') ? trimmed.replace(/\/+$/, '') || '/' : `/${trimmed.replace(/\/+$/, '')}`;
25
25
  }
26
- function layoutSegments(pathTemplate, layout, skipParams, maxDepth) {
26
+ function layoutSegments(pathTemplate, layout, skipParams) {
27
27
  let parts = pathTemplate.split('/').filter(Boolean);
28
28
  if (parts.length >= 3 && /^v\d+$/i.test(parts[0]) && layout === 'resource-role') {
29
29
  parts = [parts[0], parts[2], parts[1], ...parts.slice(3)];
@@ -33,8 +33,6 @@ function layoutSegments(pathTemplate, layout, skipParams, maxDepth) {
33
33
  if (idx >= 0)
34
34
  parts = parts.slice(0, idx);
35
35
  }
36
- if (typeof maxDepth === 'number' && maxDepth > 0)
37
- parts = parts.slice(0, maxDepth);
38
36
  return parts;
39
37
  }
40
38
  function listKnownPaths() {
@@ -94,11 +92,11 @@ async function pickLayout(current) {
94
92
  console.log(` ${ui_1.c.dim('sample')} ${ui_1.c.cyan(sample)}`);
95
93
  console.log('');
96
94
  console.log(` ${ui_1.c.cyan('1')} role → resource ${ui_1.c.dim('recommended')}`);
97
- console.log(` ${(0, config_edit_1.previewTree)(layoutSegments(sample, 'role-resource', true, null))}`);
95
+ console.log(` ${(0, config_edit_1.previewTree)(layoutSegments(sample, 'role-resource', true))}`);
98
96
  console.log(` ${ui_1.c.dim('v1 › admin › baskets (ops under baskets, not under {id})')}`);
99
97
  console.log('');
100
98
  console.log(` ${ui_1.c.cyan('2')} resource → role`);
101
- console.log(` ${(0, config_edit_1.previewTree)(layoutSegments(sample, 'resource-role', true, null))}`);
99
+ console.log(` ${(0, config_edit_1.previewTree)(layoutSegments(sample, 'resource-role', true))}`);
102
100
  console.log(` ${ui_1.c.dim('v1 › baskets › admin')}`);
103
101
  console.log('');
104
102
  console.log(` ${ui_1.c.cyan('3')} keep ${ui_1.c.dim(`(${current})`)}`);
@@ -127,22 +125,6 @@ async function pickSkipParams(current) {
127
125
  return false;
128
126
  throw new Error(`Unknown choice: ${answer}`);
129
127
  }
130
- async function pickMaxDepth(current) {
131
- console.log('');
132
- console.log(` ${ui_1.c.bold('Max folder depth')} ${ui_1.c.dim('(optional)')}`);
133
- console.log(` ${ui_1.c.dim('Counts version. Empty = no limit beyond param fold.')}`);
134
- console.log(` ${ui_1.c.dim('e.g. 3 → v1 / admin / baskets')}`);
135
- const hint = current == null ? 'none' : String(current);
136
- const answer = await prompt(` ${ui_1.c.yellow('?')} Depth ${ui_1.c.dim(`[${hint}]`)}\n ${ui_1.c.cyan('›')} `);
137
- if (!answer)
138
- return current ?? null;
139
- if (/^(none|null|n)$/i.test(answer))
140
- return null;
141
- const n = Number(answer);
142
- if (!Number.isFinite(n) || n < 1)
143
- throw new Error(`Invalid depth: ${answer}`);
144
- return Math.floor(n);
145
- }
146
128
  async function pickExampleStyle(current) {
147
129
  console.log('');
148
130
  console.log(` ${ui_1.c.bold('Example / scenario labels')}`);
@@ -164,9 +146,9 @@ async function pickExampleStyle(current) {
164
146
  return 'full';
165
147
  throw new Error(`Unknown style: ${answer}`);
166
148
  }
167
- function layoutChoicesFor(pathTemplate, layout, skipParams, maxDepth) {
168
- const role = layoutSegments(pathTemplate, 'role-resource', skipParams, maxDepth);
169
- const resource = layoutSegments(pathTemplate, 'resource-role', skipParams, maxDepth);
149
+ function layoutChoicesFor(pathTemplate, layout, skipParams) {
150
+ const role = layoutSegments(pathTemplate, 'role-resource', skipParams);
151
+ const resource = layoutSegments(pathTemplate, 'resource-role', skipParams);
170
152
  const choices = [
171
153
  { id: 'role', label: 'role → resource', segments: role },
172
154
  { id: 'resource', label: 'resource → role', segments: resource },
@@ -174,8 +156,8 @@ function layoutChoicesFor(pathTemplate, layout, skipParams, maxDepth) {
174
156
  ];
175
157
  return choices;
176
158
  }
177
- async function pickSegments(pathTemplate, layout, skipParams, maxDepth) {
178
- const choices = layoutChoicesFor(pathTemplate, layout, skipParams, maxDepth);
159
+ async function pickSegments(pathTemplate, layout, skipParams) {
160
+ const choices = layoutChoicesFor(pathTemplate, layout, skipParams);
179
161
  console.log('');
180
162
  console.log(` ${ui_1.c.bold('Override')} ${ui_1.c.cyan(pathTemplate)}`);
181
163
  choices.forEach((choice, index) => {
@@ -226,9 +208,6 @@ async function runTreeWizard(options = {}) {
226
208
  const skipParams = await pickSkipParams(config.treeSkipParams !== false);
227
209
  (0, config_edit_1.upsertConfigValue)(configPath, 'treeSkipParams', skipParams ? 'true' : 'false');
228
210
  console.log(` ${ui_1.c.green('✔')} treeSkipParams → ${ui_1.c.cyan(String(skipParams))}`);
229
- const maxDepth = await pickMaxDepth(config.treeMaxDepth ?? null);
230
- (0, config_edit_1.upsertConfigValue)(configPath, 'treeMaxDepth', maxDepth == null ? 'null' : String(maxDepth));
231
- console.log(` ${ui_1.c.green('✔')} treeMaxDepth → ${ui_1.c.cyan(maxDepth == null ? 'null' : String(maxDepth))}`);
232
211
  const exampleStyle = await pickExampleStyle(config.exampleLabelStyle ?? 'status-title-case');
233
212
  (0, config_edit_1.upsertConfigValue)(configPath, 'exampleLabelStyle', (0, config_edit_1.formatTsString)(exampleStyle));
234
213
  console.log(` ${ui_1.c.green('✔')} exampleLabelStyle → ${ui_1.c.cyan(exampleStyle)}`);
@@ -239,7 +218,7 @@ async function runTreeWizard(options = {}) {
239
218
  if (customize && !/^n(o)?$/i.test(customize)) {
240
219
  const pathTemplate = await pickPath(options.path);
241
220
  if (pathTemplate) {
242
- const segments = await pickSegments(pathTemplate, layout, skipParams, maxDepth);
221
+ const segments = await pickSegments(pathTemplate, layout, skipParams);
243
222
  if (segments?.length) {
244
223
  const overrides = (0, config_edit_1.readTreePathOverrides)();
245
224
  overrides[pathTemplate] = segments;
@@ -0,0 +1,12 @@
1
+ export type UninstallOptions = {
2
+ cwd?: string;
3
+ dryRun?: boolean;
4
+ yes?: boolean;
5
+ fast?: boolean;
6
+ /** Keep @t0.labs/daxta in package.json (only unwind project wiring) */
7
+ keepDep?: boolean;
8
+ };
9
+ /**
10
+ * Fully unwind DAxTA from a consumer project.
11
+ */
12
+ export declare function uninstallDaxta(options?: UninstallOptions): Promise<void>;
@@ -0,0 +1,281 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.uninstallDaxta = uninstallDaxta;
37
+ const readline_1 = require("readline");
38
+ const fs_1 = require("fs");
39
+ const path = __importStar(require("path"));
40
+ const child_process_1 = require("child_process");
41
+ const config_edit_1 = require("./config-edit");
42
+ const inject_main_1 = require("./inject-main");
43
+ const jest_hooks_1 = require("./jest-hooks");
44
+ const ui_1 = require("./ui");
45
+ function readJson(filePath) {
46
+ return JSON.parse((0, fs_1.readFileSync)(filePath, 'utf8'));
47
+ }
48
+ function writeJson(filePath, value) {
49
+ (0, fs_1.writeFileSync)(filePath, `${JSON.stringify(value, null, 2)}\n`);
50
+ }
51
+ function prompt(question) {
52
+ const rl = (0, readline_1.createInterface)({ input: process.stdin, output: process.stdout });
53
+ return new Promise((resolve) => {
54
+ rl.question(question, (answer) => {
55
+ rl.close();
56
+ resolve(answer.trim());
57
+ });
58
+ });
59
+ }
60
+ function detectPackageManager(cwd, pkg) {
61
+ if ((0, fs_1.existsSync)(path.join(cwd, 'pnpm-lock.yaml')) || pkg.packageManager?.startsWith('pnpm'))
62
+ return 'pnpm';
63
+ if ((0, fs_1.existsSync)(path.join(cwd, 'yarn.lock')))
64
+ return 'yarn';
65
+ return 'npm';
66
+ }
67
+ function readConfigString(configText, key) {
68
+ const m = configText.match(new RegExp(`${key}\\s*:\\s*['\`"]([^'\`"]+)['\`"]`));
69
+ return m?.[1] ?? null;
70
+ }
71
+ function stripGitignore(cwd, dryRun) {
72
+ const gitignorePath = path.join(cwd, '.gitignore');
73
+ if (!(0, fs_1.existsSync)(gitignorePath))
74
+ return [];
75
+ const remove = new Set(['daxta/out/', 'daxta/', '**/.jest.daxta.runtime.json']);
76
+ const before = (0, fs_1.readFileSync)(gitignorePath, 'utf8');
77
+ const lines = before.split(/\r?\n/);
78
+ const kept = lines.filter((line) => !remove.has(line.trim()));
79
+ if (kept.length === lines.length)
80
+ return [];
81
+ if (!dryRun)
82
+ (0, fs_1.writeFileSync)(gitignorePath, `${kept.join('\n').replace(/\n+$/, '')}\n`);
83
+ return [...remove].filter((entry) => lines.some((line) => line.trim() === entry));
84
+ }
85
+ function stripEnvDaxta(cwd, dryRun) {
86
+ const notes = [];
87
+ for (const name of ['.env', '.env.local', '.env.development', '.env.development.local']) {
88
+ const filePath = path.join(cwd, name);
89
+ if (!(0, fs_1.existsSync)(filePath))
90
+ continue;
91
+ const before = (0, fs_1.readFileSync)(filePath, 'utf8');
92
+ const lines = before.split(/\r?\n/);
93
+ const kept = lines.filter((line) => !/^\s*DAXTA_DOCS\s*=/.test(line));
94
+ if (kept.length === lines.length)
95
+ continue;
96
+ if (!dryRun)
97
+ (0, fs_1.writeFileSync)(filePath, `${kept.join('\n').replace(/\n+$/, '')}\n`);
98
+ notes.push(name);
99
+ }
100
+ return notes;
101
+ }
102
+ function stripRegisterScripts(scripts) {
103
+ const changed = [];
104
+ const re = /^NODE_OPTIONS=(['"])?(?:[^'"]*\s)?--require\s+@t0\.labs\/daxta\/register\s*([^'"]*)\1\s+/i;
105
+ for (const [key, value] of Object.entries(scripts)) {
106
+ if (!value.includes('@t0.labs/daxta/register') && !/\bdaxta\s+test\b/.test(value))
107
+ continue;
108
+ let next = value
109
+ .replace(re, '')
110
+ .replace(/\s*--require\s+@t0\.labs\/daxta\/register\b/g, '')
111
+ .replace(/NODE_OPTIONS=(['"])\s*\1\s*/g, '')
112
+ .replace(/NODE_OPTIONS=\s+/g, '')
113
+ .trim();
114
+ if (/\bdaxta\s+test\b/.test(next)) {
115
+ // can't unwrap without testCommand — leave a marker note via caller
116
+ continue;
117
+ }
118
+ if (next !== value) {
119
+ scripts[key] = next;
120
+ changed.push(key);
121
+ }
122
+ }
123
+ return changed;
124
+ }
125
+ function removePackage(cwd, pm, dryRun) {
126
+ if (dryRun)
127
+ return `${pm} remove @t0.labs/daxta (dry-run)`;
128
+ const args = pm === 'pnpm' ? ['remove', '@t0.labs/daxta'] : pm === 'yarn' ? ['remove', '@t0.labs/daxta'] : ['uninstall', '@t0.labs/daxta'];
129
+ const result = (0, child_process_1.spawnSync)(pm, args, { cwd, stdio: 'inherit', shell: process.platform === 'win32' });
130
+ if (result.status !== 0)
131
+ throw new Error(`${pm} ${args.join(' ')} failed`);
132
+ return `${pm} ${args.join(' ')}`;
133
+ }
134
+ /**
135
+ * Fully unwind DAxTA from a consumer project.
136
+ */
137
+ async function uninstallDaxta(options = {}) {
138
+ const cwd = options.cwd ?? process.cwd();
139
+ const dryRun = Boolean(options.dryRun);
140
+ const paceMs = options.fast ? 0 : 280;
141
+ const pkgPath = path.join(cwd, 'package.json');
142
+ if (!(0, fs_1.existsSync)(pkgPath))
143
+ throw new Error('package.json not found');
144
+ let pkg = readJson(pkgPath);
145
+ const project = pkg.name || path.basename(cwd);
146
+ const pm = detectPackageManager(cwd, pkg);
147
+ (0, ui_1.banner)('DAxTA uninstall', project);
148
+ if (!options.yes && process.stdin.isTTY) {
149
+ const answer = await prompt(` ${ui_1.c.yellow('?')} Remove DAxTA from ${ui_1.c.bold(project)}?\n` +
150
+ ` ${ui_1.c.dim('Y')} yes · ${ui_1.c.dim('n')} cancel\n ${ui_1.c.cyan('›')} `);
151
+ if (answer && !/^y(es)?$/i.test(answer)) {
152
+ console.log(` ${ui_1.c.dim('cancelled')}`);
153
+ return;
154
+ }
155
+ }
156
+ if (paceMs)
157
+ await (0, ui_1.sleep)(400);
158
+ const configPath = (0, config_edit_1.findDaxtaConfigPath)(cwd);
159
+ let configText = '';
160
+ if (configPath && (0, fs_1.existsSync)(configPath)) {
161
+ configText = (0, fs_1.readFileSync)(configPath, 'utf8');
162
+ }
163
+ await (0, ui_1.step)('Remove apiDocs from Nest entry', () => {
164
+ const details = [];
165
+ for (const file of (0, inject_main_1.findMainCandidates)(cwd).slice(0, 8)) {
166
+ try {
167
+ const source = (0, fs_1.readFileSync)(file, 'utf8');
168
+ if (!source.includes('@t0.labs/daxta') && !source.includes('apiDocs('))
169
+ continue;
170
+ details.push((0, inject_main_1.removeApiDocs)(file, dryRun));
171
+ }
172
+ catch {
173
+ // ignore
174
+ }
175
+ }
176
+ if (!details.length)
177
+ return 'nothing to remove';
178
+ return { summary: `${details.length} file(s)`, details };
179
+ }, { paceMs });
180
+ await (0, ui_1.step)('Remove Jest plugin hooks', () => {
181
+ const details = [];
182
+ const testScript = readConfigString(configText, 'testScript');
183
+ const testCommand = readConfigString(configText, 'testCommand');
184
+ const jestConfigField = readConfigString(configText, 'jestConfig');
185
+ const scriptCommand = testCommand ||
186
+ (testScript && pkg.scripts?.[testScript] ? pkg.scripts[testScript] : undefined);
187
+ const jestPath = (0, jest_hooks_1.resolveJestConfigPath)(cwd, {
188
+ jestConfig: jestConfigField ?? undefined,
189
+ scriptCommand,
190
+ });
191
+ const candidates = [
192
+ jestPath,
193
+ path.join(cwd, 'jest.config.integration.js'),
194
+ path.join(cwd, 'jest.config.integration.ts'),
195
+ path.join(cwd, 'jest.config.js'),
196
+ path.join(cwd, 'jest.config.ts'),
197
+ path.join(cwd, 'jest.config.json'),
198
+ ].filter((p) => Boolean(p && (0, fs_1.existsSync)(p)));
199
+ const seen = new Set();
200
+ for (const file of candidates) {
201
+ if (seen.has(file))
202
+ continue;
203
+ seen.add(file);
204
+ try {
205
+ const notes = (0, jest_hooks_1.removeJestHooks)(file, dryRun);
206
+ if (notes.length)
207
+ details.push(`${path.relative(cwd, file)}: ${notes.join(', ')}`);
208
+ }
209
+ catch (error) {
210
+ details.push(`${path.relative(cwd, file)}: ${error instanceof Error ? error.message : error}`);
211
+ }
212
+ }
213
+ if (!details.length)
214
+ return 'nothing to remove';
215
+ return { summary: `${details.length} config(s)`, details };
216
+ }, { paceMs });
217
+ await (0, ui_1.step)('Clean package.json scripts', () => {
218
+ pkg.scripts ??= {};
219
+ const details = [];
220
+ const testScript = readConfigString(configText, 'testScript');
221
+ const testCommand = readConfigString(configText, 'testCommand');
222
+ if (testScript && testCommand && (0, jest_hooks_1.unwrapDaxtaTestScript)(pkg.scripts, testScript, testCommand)) {
223
+ details.push(`unwrapped ${testScript}`);
224
+ }
225
+ details.push(...stripRegisterScripts(pkg.scripts).map((key) => `cleaned ${key}`));
226
+ for (const key of Object.keys(pkg.scripts)) {
227
+ if (!key.startsWith('daxta:'))
228
+ continue;
229
+ delete pkg.scripts[key];
230
+ details.push(`removed script ${key}`);
231
+ }
232
+ if (!dryRun && details.length)
233
+ writeJson(pkgPath, pkg);
234
+ if (!details.length)
235
+ return 'no script changes';
236
+ return { summary: `${details.length} change(s)`, details };
237
+ }, { paceMs });
238
+ await (0, ui_1.step)('Remove daxta.config + output', () => {
239
+ const details = [];
240
+ if (configPath && (0, fs_1.existsSync)(configPath)) {
241
+ if (!dryRun)
242
+ (0, fs_1.rmSync)(configPath, { force: true });
243
+ details.push(path.relative(cwd, configPath));
244
+ }
245
+ const outDir = path.join(cwd, 'daxta');
246
+ if ((0, fs_1.existsSync)(outDir)) {
247
+ if (!dryRun)
248
+ (0, fs_1.rmSync)(outDir, { recursive: true, force: true });
249
+ details.push('daxta/');
250
+ }
251
+ if (!details.length)
252
+ return 'already gone';
253
+ return { summary: 'deleted', details };
254
+ }, { paceMs });
255
+ await (0, ui_1.step)('Clean .gitignore / .env', () => {
256
+ const details = [];
257
+ const gi = stripGitignore(cwd, dryRun);
258
+ if (gi.length)
259
+ details.push(`.gitignore − ${gi.join(', ')}`);
260
+ const env = stripEnvDaxta(cwd, dryRun);
261
+ if (env.length)
262
+ details.push(`DAXTA_DOCS removed from ${env.join(', ')}`);
263
+ if (!details.length)
264
+ return 'nothing to clean';
265
+ return { summary: 'cleaned', details };
266
+ }, { paceMs });
267
+ if (!options.keepDep) {
268
+ const listed = Boolean(pkg.dependencies?.['@t0.labs/daxta'] || pkg.devDependencies?.['@t0.labs/daxta']) ||
269
+ (0, fs_1.existsSync)(path.join(cwd, 'node_modules', '@t0.labs', 'daxta'));
270
+ if (listed) {
271
+ await (0, ui_1.step)(`Remove @t0.labs/daxta via ${pm}`, () => removePackage(cwd, pm, dryRun), { paceMs: paceMs ? 500 : 0 });
272
+ }
273
+ else {
274
+ await (0, ui_1.step)('Package dependency', () => 'not listed — skip', { paceMs });
275
+ }
276
+ }
277
+ (0, ui_1.box)('Done', [
278
+ `${ui_1.c.green('✔')} DAxTA removed from ${ui_1.c.bold(project)}`,
279
+ `${ui_1.c.dim('check')} Nest main + Jest config if anything custom remained`,
280
+ ]);
281
+ }
package/dist/config.d.ts CHANGED
@@ -24,12 +24,6 @@ export type DaxtaConfig = {
24
24
  * Ops like POST …/{id}/lock sit under the parent resource. Default true.
25
25
  */
26
26
  treeSkipParams?: boolean;
27
- /**
28
- * Max folder segments after (and including) version.
29
- * e.g. 3 → v1 / admin / baskets — deeper segments are not folders.
30
- * null/undefined = no extra limit (treeSkipParams still applies).
31
- */
32
- treeMaxDepth?: number | null;
33
27
  treePathOverrides?: Record<string, string[]>;
34
28
  /**
35
29
  * OpenAPI example + scenario labels:
package/dist/config.js CHANGED
@@ -48,7 +48,6 @@ const DEFAULTS = {
48
48
  outDir: 'daxta/out',
49
49
  treeLayout: 'role-resource',
50
50
  treeSkipParams: true,
51
- treeMaxDepth: null,
52
51
  treePathOverrides: {},
53
52
  exampleLabelStyle: 'status-title-case',
54
53
  port: 5199,
@@ -1,7 +1,13 @@
1
1
  export declare function stripViewerExtensions(value: unknown): unknown;
2
2
  /**
3
- * Export OpenAPI with real URL paths (correct for clients) and tags/folders
4
- * matching the docs sidebar (`x-tree-segments`).
3
+ * Build export path keys from sidebar tree segments (same order as docs),
4
+ * appending any `{param}` tail from the real URL so templates stay complete.
5
+ * Real URL is preserved on `x-daxta-url-path` when it differs.
6
+ */
7
+ export declare function exportPathFromTree(urlPath: string, treeSegments: string[]): string;
8
+ /**
9
+ * Export OpenAPI with path keys ordered like the docs sidebar (`x-tree-segments`).
10
+ * Real request URLs stay on `x-daxta-url-path` when remapped.
5
11
  */
6
12
  export declare function toTreeOrderedOpenApi(raw: Record<string, unknown>): Record<string, unknown>;
7
13
  export declare function readStrippedOpenApiJson(): string | null;
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.stripViewerExtensions = stripViewerExtensions;
4
+ exports.exportPathFromTree = exportPathFromTree;
4
5
  exports.toTreeOrderedOpenApi = toTreeOrderedOpenApi;
5
6
  exports.readStrippedOpenApiJson = readStrippedOpenApiJson;
6
7
  const fs_1 = require("fs");
@@ -28,8 +29,25 @@ function treeSegmentsForOperation(urlPath, operation) {
28
29
  return urlPath.split('/').filter(Boolean);
29
30
  }
30
31
  /**
31
- * Export OpenAPI with real URL paths (correct for clients) and tags/folders
32
- * matching the docs sidebar (`x-tree-segments`).
32
+ * Build export path keys from sidebar tree segments (same order as docs),
33
+ * appending any `{param}` tail from the real URL so templates stay complete.
34
+ * Real URL is preserved on `x-daxta-url-path` when it differs.
35
+ */
36
+ function exportPathFromTree(urlPath, treeSegments) {
37
+ const originalParts = urlPath.split('/').filter(Boolean);
38
+ const paramIdx = originalParts.findIndex((part) => part.startsWith('{'));
39
+ const tail = paramIdx >= 0 ? originalParts.slice(paramIdx) : [];
40
+ const treeHasParam = treeSegments.some((part) => part.startsWith('{'));
41
+ const parts = treeSegments.length === 0
42
+ ? originalParts
43
+ : treeHasParam || paramIdx < 0
44
+ ? treeSegments
45
+ : [...treeSegments, ...tail];
46
+ return `/${parts.join('/')}`;
47
+ }
48
+ /**
49
+ * Export OpenAPI with path keys ordered like the docs sidebar (`x-tree-segments`).
50
+ * Real request URLs stay on `x-daxta-url-path` when remapped.
33
51
  */
34
52
  function toTreeOrderedOpenApi(raw) {
35
53
  const sourcePaths = (raw.paths ?? {});
@@ -38,11 +56,22 @@ function toTreeOrderedOpenApi(raw) {
38
56
  for (const [urlPath, pathItem] of Object.entries(sourcePaths)) {
39
57
  if (!pathItem || typeof pathItem !== 'object')
40
58
  continue;
41
- const exportPathItem = {};
59
+ let treeSegments = null;
60
+ for (const [key, value] of Object.entries(pathItem)) {
61
+ if (!HTTP_METHODS.has(key) || !value || typeof value !== 'object')
62
+ continue;
63
+ treeSegments = treeSegmentsForOperation(urlPath, value);
64
+ break;
65
+ }
66
+ if (!treeSegments)
67
+ treeSegments = urlPath.split('/').filter(Boolean);
68
+ const exportPath = exportPathFromTree(urlPath, treeSegments);
69
+ const exportPathItem = { ...(exportPaths[exportPath] ?? {}) };
42
70
  for (const [key, value] of Object.entries(pathItem)) {
43
71
  if (!HTTP_METHODS.has(key) || !value || typeof value !== 'object') {
44
- if (!HTTP_METHODS.has(key))
72
+ if (!HTTP_METHODS.has(key) && exportPathItem[key] === undefined) {
45
73
  exportPathItem[key] = stripViewerExtensions(value);
74
+ }
46
75
  continue;
47
76
  }
48
77
  const operation = value;
@@ -52,9 +81,12 @@ function toTreeOrderedOpenApi(raw) {
52
81
  const tag = tagParts.length ? tagParts.join(' / ') : 'API';
53
82
  cleaned.tags = [tag];
54
83
  tagNames.add(tag);
84
+ if (exportPath !== urlPath) {
85
+ cleaned['x-daxta-url-path'] = urlPath;
86
+ }
55
87
  exportPathItem[key] = cleaned;
56
88
  }
57
- exportPaths[urlPath] = exportPathItem;
89
+ exportPaths[exportPath] = exportPathItem;
58
90
  }
59
91
  const orderedPaths = {};
60
92
  for (const key of Object.keys(exportPaths).sort((a, b) => a.localeCompare(b))) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@t0.labs/daxta",
3
- "version": "0.4.5",
3
+ "version": "0.4.7",
4
4
  "description": "DAxTA \u2014 docs from Nest integration traffic + DTO field CLI / Try-it",
5
5
  "license": "MIT",
6
6
  "repository": {