@t0.labs/daxta 0.4.1 → 0.4.3

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
@@ -91,10 +91,24 @@ daxta install # one-shot setup
91
91
  daxta migrate # after a package bump
92
92
  daxta build # rebuild OpenAPI/HTML from recorded hits
93
93
  daxta serve # optional standalone viewer (prefer apiDocs on the app)
94
+ daxta tree # choose sidebar folder order for a path
94
95
  daxta fields … # export field map for an operation
95
96
  daxta call … # CLI Try-it
96
97
  ```
97
98
 
99
+ ### Sidebar order (`daxta tree`)
100
+
101
+ Pick a path and how it should nest under `/docs`:
102
+
103
+ ```text
104
+ /v1/admin/baskets
105
+ 1) URL order v1 › admin › baskets
106
+ 2) Resource-first v1 › baskets › admin
107
+ 3) Custom …
108
+ ```
109
+
110
+ Saves `treeLayout` / `treePathOverrides` in `daxta.config.ts`. Then `daxta build`.
111
+
98
112
 
99
113
 
100
114
  ## API
@@ -44,6 +44,24 @@ const dto_fields_1 = require("../fields/dto-fields");
44
44
  const path_util_1 = require("../path.util");
45
45
  const paths_1 = require("../serve/paths");
46
46
  const METHOD_RANK = { get: 0, post: 1, put: 2, patch: 3, delete: 4 };
47
+ /** Re-map old/mis-templated hits onto Nest routes (or stronger heuristics). */
48
+ function canonicalizeHit(hit) {
49
+ const concrete = hit.path.includes('{') ? (0, path_util_1.materializePath)(hit.path, hit.pathParams) : hit.path;
50
+ const nextPath = (0, path_util_1.templatize)(concrete, hit.test, hit.method);
51
+ if (!nextPath)
52
+ return null;
53
+ const pathParams = concrete !== nextPath || !hit.pathParams || !Object.keys(hit.pathParams).length
54
+ ? (0, path_util_1.extractPathParams)(nextPath, concrete)
55
+ : hit.pathParams;
56
+ return {
57
+ ...hit,
58
+ path: nextPath,
59
+ pathParams: Object.keys(pathParams).length ? pathParams : hit.pathParams,
60
+ };
61
+ }
62
+ function canonicalizeHits(hits) {
63
+ return hits.map(canonicalizeHit).filter((hit) => hit != null);
64
+ }
47
65
  function readPackageMeta() {
48
66
  try {
49
67
  const pkg = JSON.parse((0, fs_1.readFileSync)(path.join(process.cwd(), 'package.json'), 'utf8'));
@@ -379,7 +397,7 @@ function loadHits() {
379
397
  return [];
380
398
  const workerFiles = (0, fs_1.readdirSync)((0, paths_1.getOutDir)()).filter((fileName) => fileName.startsWith('hits-w') && fileName.endsWith('.json'));
381
399
  if (workerFiles.length) {
382
- return workerFiles.flatMap((fileName) => {
400
+ return canonicalizeHits(workerFiles.flatMap((fileName) => {
383
401
  try {
384
402
  const parsed = JSON.parse((0, fs_1.readFileSync)(path.join((0, paths_1.getOutDir)(), fileName), 'utf8'));
385
403
  return Array.isArray(parsed) ? parsed : [];
@@ -388,14 +406,14 @@ function loadHits() {
388
406
  console.error(`DAxTA: skipped corrupt hits file ${fileName}:`, error);
389
407
  return [];
390
408
  }
391
- });
409
+ }));
392
410
  }
393
411
  // Fallback after workers were cleaned — rebuild from last merged hits.json
394
412
  try {
395
413
  if (!(0, fs_1.existsSync)((0, paths_1.getHitsJsonPath)()))
396
414
  return [];
397
415
  const parsed = JSON.parse((0, fs_1.readFileSync)((0, paths_1.getHitsJsonPath)(), 'utf8'));
398
- return Array.isArray(parsed) ? parsed : [];
416
+ return canonicalizeHits(Array.isArray(parsed) ? parsed : []);
399
417
  }
400
418
  catch (error) {
401
419
  console.error('DAxTA: skipped corrupt hits.json:', error);
@@ -0,0 +1,8 @@
1
+ export declare function findDaxtaConfigPath(cwd?: string): string | null;
2
+ /** Replace or insert a top-level `key: <value>` inside `defineConfig({ ... })`. */
3
+ export declare function upsertConfigValue(configPath: string, key: string, valueLiteral: string): void;
4
+ export declare function formatTsString(value: string): string;
5
+ export declare function formatTsStringArray(values: string[]): string;
6
+ export declare function formatTsStringRecord(record: Record<string, string[]>): string;
7
+ export declare function readTreePathOverrides(cwd?: string): Record<string, string[]>;
8
+ export declare function previewTree(segments: string[]): string;
@@ -0,0 +1,168 @@
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.findDaxtaConfigPath = findDaxtaConfigPath;
37
+ exports.upsertConfigValue = upsertConfigValue;
38
+ exports.formatTsString = formatTsString;
39
+ exports.formatTsStringArray = formatTsStringArray;
40
+ exports.formatTsStringRecord = formatTsStringRecord;
41
+ exports.readTreePathOverrides = readTreePathOverrides;
42
+ exports.previewTree = previewTree;
43
+ const fs_1 = require("fs");
44
+ const path = __importStar(require("path"));
45
+ const ui_1 = require("./ui");
46
+ const CONFIG_NAMES = ['daxta.config.ts', 'daxta.config.js', 'daxta.config.mjs', 'daxta.config.cjs'];
47
+ function findDaxtaConfigPath(cwd = process.cwd()) {
48
+ for (const name of CONFIG_NAMES) {
49
+ const full = path.join(cwd, name);
50
+ if ((0, fs_1.existsSync)(full))
51
+ return full;
52
+ }
53
+ return null;
54
+ }
55
+ /** Replace or insert a top-level `key: <value>` inside `defineConfig({ ... })`. */
56
+ function upsertConfigValue(configPath, key, valueLiteral) {
57
+ let text = (0, fs_1.readFileSync)(configPath, 'utf8');
58
+ const keyRe = new RegExp(`${key}\\s*:`);
59
+ const match = keyRe.exec(text);
60
+ if (!match) {
61
+ const next = text.replace(/defineConfig\(\s*\{/, `defineConfig({\n ${key}: ${valueLiteral},`);
62
+ if (next === text)
63
+ throw new Error(`Could not insert ${key} into ${path.basename(configPath)}`);
64
+ (0, fs_1.writeFileSync)(configPath, next);
65
+ return;
66
+ }
67
+ const afterColon = match.index + match[0].length;
68
+ let i = afterColon;
69
+ while (i < text.length && /\s/.test(text[i]))
70
+ i += 1;
71
+ const start = i;
72
+ let end = i;
73
+ const ch = text[i];
74
+ if (ch === '{' || ch === '[') {
75
+ const open = ch;
76
+ const close = ch === '{' ? '}' : ']';
77
+ let depth = 0;
78
+ let quote = null;
79
+ let escaped = false;
80
+ for (; end < text.length; end += 1) {
81
+ const cur = text[end];
82
+ if (quote) {
83
+ if (escaped) {
84
+ escaped = false;
85
+ continue;
86
+ }
87
+ if (cur === '\\' && quote !== '`') {
88
+ escaped = true;
89
+ continue;
90
+ }
91
+ if (cur === quote)
92
+ quote = null;
93
+ continue;
94
+ }
95
+ if (cur === '"' || cur === "'" || cur === '`') {
96
+ quote = cur;
97
+ continue;
98
+ }
99
+ if (cur === open)
100
+ depth += 1;
101
+ else if (cur === close) {
102
+ depth -= 1;
103
+ if (depth === 0) {
104
+ end += 1;
105
+ break;
106
+ }
107
+ }
108
+ }
109
+ }
110
+ else if (ch === '"' || ch === "'" || ch === '`') {
111
+ const quote = ch;
112
+ end = i + 1;
113
+ let escaped = false;
114
+ for (; end < text.length; end += 1) {
115
+ const cur = text[end];
116
+ if (escaped) {
117
+ escaped = false;
118
+ continue;
119
+ }
120
+ if (cur === '\\') {
121
+ escaped = true;
122
+ continue;
123
+ }
124
+ if (cur === quote) {
125
+ end += 1;
126
+ break;
127
+ }
128
+ }
129
+ }
130
+ else {
131
+ while (end < text.length && !/[,}\n]/.test(text[end]))
132
+ end += 1;
133
+ }
134
+ text = `${text.slice(0, start)}${valueLiteral}${text.slice(end)}`;
135
+ (0, fs_1.writeFileSync)(configPath, text);
136
+ }
137
+ function formatTsString(value) {
138
+ return JSON.stringify(value);
139
+ }
140
+ function formatTsStringArray(values) {
141
+ return `[${values.map((value) => JSON.stringify(value)).join(', ')}]`;
142
+ }
143
+ function formatTsStringRecord(record) {
144
+ const keys = Object.keys(record).sort((a, b) => a.localeCompare(b));
145
+ if (!keys.length)
146
+ return '{}';
147
+ const lines = keys.map((key) => ` ${JSON.stringify(key)}: ${formatTsStringArray(record[key])},`);
148
+ return `{\n${lines.join('\n')}\n }`;
149
+ }
150
+ function readTreePathOverrides(cwd = process.cwd()) {
151
+ try {
152
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
153
+ const { createJiti } = require('jiti');
154
+ const configPath = findDaxtaConfigPath(cwd);
155
+ if (!configPath)
156
+ return {};
157
+ const jiti = createJiti(__filename);
158
+ const mod = jiti(configPath);
159
+ const cfg = (mod.default ?? mod);
160
+ return { ...(cfg.treePathOverrides ?? {}) };
161
+ }
162
+ catch {
163
+ return {};
164
+ }
165
+ }
166
+ function previewTree(segments) {
167
+ return segments.map((part) => ui_1.c.cyan(part)).join(ui_1.c.dim(' › '));
168
+ }
@@ -6,7 +6,7 @@ export declare function resolveJestConfigPath(cwd: string, options: {
6
6
  }): string | null;
7
7
  /**
8
8
  * Inject DAxTA as a Jest plugin (setup + reporter). Does not wrap the test process.
9
- * Leaves existing globalSetup / globalTeardown untouched.
9
+ * Supports JSON and JS/CJS/MJS/TS config files. Leaves globalSetup / globalTeardown untouched.
10
10
  */
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`. */
@@ -40,6 +40,8 @@ exports.unwrapDaxtaTestScript = unwrapDaxtaTestScript;
40
40
  const fs_1 = require("fs");
41
41
  const path = __importStar(require("path"));
42
42
  const discover_test_1 = require("./discover-test");
43
+ const SETUP = '@t0.labs/daxta/setup';
44
+ const REPORTER = '@t0.labs/daxta/jest-reporter';
43
45
  function loadJestJson(filePath) {
44
46
  return JSON.parse((0, fs_1.readFileSync)(filePath, 'utf8'));
45
47
  }
@@ -55,42 +57,147 @@ function resolveJestConfigPath(cwd, options) {
55
57
  }
56
58
  return null;
57
59
  }
58
- /**
59
- * Inject DAxTA as a Jest plugin (setup + reporter). Does not wrap the test process.
60
- * Leaves existing globalSetup / globalTeardown untouched.
61
- */
62
- function injectJestHooks(jestConfigPath, dryRun = false) {
60
+ function isJsonConfigPath(filePath) {
61
+ return path.extname(filePath).toLowerCase() === '.json';
62
+ }
63
+ function isJsLikeConfigPath(filePath) {
64
+ return ['.js', '.cjs', '.mjs', '.ts', '.cts', '.mts'].includes(path.extname(filePath).toLowerCase());
65
+ }
66
+ /** Find `[`…`]` for `key: [` while skipping strings. */
67
+ function findArrayPropRange(source, key) {
68
+ const re = new RegExp(`${key}\\s*:\\s*\\[`);
69
+ const match = re.exec(source);
70
+ if (!match)
71
+ return null;
72
+ const open = match.index + match[0].length - 1;
73
+ let depth = 0;
74
+ let quote = null;
75
+ let escaped = false;
76
+ for (let i = open; i < source.length; i += 1) {
77
+ const ch = source[i];
78
+ if (quote) {
79
+ if (escaped) {
80
+ escaped = false;
81
+ continue;
82
+ }
83
+ if (ch === '\\' && quote !== '`') {
84
+ escaped = true;
85
+ continue;
86
+ }
87
+ if (ch === quote)
88
+ quote = null;
89
+ continue;
90
+ }
91
+ if (ch === '"' || ch === "'" || ch === '`') {
92
+ quote = ch;
93
+ continue;
94
+ }
95
+ if (ch === '[')
96
+ depth += 1;
97
+ else if (ch === ']') {
98
+ depth -= 1;
99
+ if (depth === 0)
100
+ return { open, close: i };
101
+ }
102
+ }
103
+ return null;
104
+ }
105
+ function insertIntoObjectLiteral(source, propertyLine) {
106
+ const anchors = [/module\.exports\s*=\s*\{/, /export\s+default\s+\{/, /exports\s*=\s*\{/];
107
+ for (const re of anchors) {
108
+ const match = re.exec(source);
109
+ if (!match)
110
+ continue;
111
+ const brace = match.index + match[0].length - 1;
112
+ return `${source.slice(0, brace + 1)}\n ${propertyLine}${source.slice(brace + 1)}`;
113
+ }
114
+ return null;
115
+ }
116
+ function injectIntoJsSource(source) {
63
117
  const notes = [];
64
- if (!(0, fs_1.existsSync)(jestConfigPath))
65
- throw new Error(`Jest config not found: ${jestConfigPath}`);
66
- let data;
67
- try {
68
- data = loadJestJson(jestConfigPath);
118
+ let next = source;
119
+ if (!next.includes(SETUP)) {
120
+ const range = findArrayPropRange(next, 'setupFilesAfterEnv');
121
+ if (range) {
122
+ const afterOpen = next.slice(range.open + 1);
123
+ const multiline = /^\s*\n/.test(afterOpen);
124
+ const insertion = multiline ? `\n '${SETUP}',` : `'${SETUP}', `;
125
+ next = `${next.slice(0, range.open + 1)}${insertion}${multiline ? afterOpen : afterOpen.trimStart()}`;
126
+ notes.push(`setupFilesAfterEnv += ${SETUP}`);
127
+ }
128
+ else {
129
+ const inserted = insertIntoObjectLiteral(next, `setupFilesAfterEnv: ['${SETUP}'],`);
130
+ if (!inserted) {
131
+ throw new Error('Could not find setupFilesAfterEnv or module.exports / export default object to inject DAxTA setup');
132
+ }
133
+ next = inserted;
134
+ notes.push(`setupFilesAfterEnv = [${SETUP}]`);
135
+ }
69
136
  }
70
- catch {
71
- throw new Error(`Jest config must be JSON to inject DAxTA hooks: ${jestConfigPath}`);
137
+ if (!next.includes(REPORTER)) {
138
+ const range = findArrayPropRange(next, 'reporters');
139
+ if (range) {
140
+ const beforeClose = next.slice(range.open + 1, range.close);
141
+ const needsComma = beforeClose.trim().length > 0 && !/,\s*$/.test(beforeClose.trim());
142
+ const injection = `${needsComma ? ',' : ''}\n '${REPORTER}',\n `;
143
+ next = `${next.slice(0, range.close)}${injection}${next.slice(range.close)}`;
144
+ notes.push(`reporters += ${REPORTER}`);
145
+ }
146
+ else {
147
+ const inserted = insertIntoObjectLiteral(next, `reporters: ['default', '${REPORTER}'],`);
148
+ if (!inserted) {
149
+ throw new Error('Could not find reporters or module.exports / export default object to inject DAxTA reporter');
150
+ }
151
+ next = inserted;
152
+ notes.push(`reporters = [default, ${REPORTER}]`);
153
+ }
72
154
  }
155
+ return { source: next, notes };
156
+ }
157
+ function injectIntoJsonConfig(filePath, dryRun) {
158
+ const notes = [];
159
+ const data = loadJestJson(filePath);
73
160
  const setup = Array.isArray(data.setupFilesAfterEnv) ? [...data.setupFilesAfterEnv] : [];
74
- if (!setup.includes('@t0.labs/daxta/setup')) {
75
- setup.unshift('@t0.labs/daxta/setup');
161
+ if (!setup.includes(SETUP)) {
162
+ setup.unshift(SETUP);
76
163
  data.setupFilesAfterEnv = setup;
77
- notes.push('setupFilesAfterEnv += @t0.labs/daxta/setup');
164
+ notes.push(`setupFilesAfterEnv += ${SETUP}`);
78
165
  }
79
166
  const reporters = Array.isArray(data.reporters) ? [...data.reporters] : ['default'];
80
167
  const hasReporter = reporters.some((entry) => {
81
- if (entry === '@t0.labs/daxta/jest-reporter')
168
+ if (entry === REPORTER)
82
169
  return true;
83
- if (Array.isArray(entry) && entry[0] === '@t0.labs/daxta/jest-reporter')
170
+ if (Array.isArray(entry) && entry[0] === REPORTER)
84
171
  return true;
85
172
  return false;
86
173
  });
87
174
  if (!hasReporter) {
88
- reporters.push('@t0.labs/daxta/jest-reporter');
175
+ reporters.push(REPORTER);
89
176
  data.reporters = reporters;
90
- notes.push('reporters += @t0.labs/daxta/jest-reporter');
177
+ notes.push(`reporters += ${REPORTER}`);
91
178
  }
92
179
  if (!dryRun && notes.length) {
93
- (0, fs_1.writeFileSync)(jestConfigPath, `${JSON.stringify(data, null, 2)}\n`);
180
+ (0, fs_1.writeFileSync)(filePath, `${JSON.stringify(data, null, 2)}\n`);
181
+ }
182
+ return notes;
183
+ }
184
+ /**
185
+ * Inject DAxTA as a Jest plugin (setup + reporter). Does not wrap the test process.
186
+ * Supports JSON and JS/CJS/MJS/TS config files. Leaves globalSetup / globalTeardown untouched.
187
+ */
188
+ function injectJestHooks(jestConfigPath, dryRun = false) {
189
+ if (!(0, fs_1.existsSync)(jestConfigPath))
190
+ throw new Error(`Jest config not found: ${jestConfigPath}`);
191
+ if (isJsonConfigPath(jestConfigPath)) {
192
+ return injectIntoJsonConfig(jestConfigPath, dryRun);
193
+ }
194
+ if (!isJsLikeConfigPath(jestConfigPath)) {
195
+ throw new Error(`Unsupported Jest config type (${path.extname(jestConfigPath) || 'unknown'}). Use .json, .js, .cjs, .mjs, or .ts: ${jestConfigPath}`);
196
+ }
197
+ const original = (0, fs_1.readFileSync)(jestConfigPath, 'utf8');
198
+ const { source, notes } = injectIntoJsSource(original);
199
+ if (!dryRun && notes.length && source !== original) {
200
+ (0, fs_1.writeFileSync)(jestConfigPath, source);
94
201
  }
95
202
  return notes;
96
203
  }
package/dist/cli/main.js CHANGED
@@ -8,6 +8,7 @@ const serve_1 = require("../serve");
8
8
  const install_1 = require("./install");
9
9
  const migrate_1 = require("./migrate");
10
10
  const test_1 = require("./test");
11
+ const tree_1 = require("./tree");
11
12
  function usage() {
12
13
  console.log(`DAxTA CLI (@t0.labs/daxta)
13
14
 
@@ -18,6 +19,7 @@ Usage:
18
19
  daxta test [--script <name>] [--config <jest.json>] [--serve] [--port <n>] [--yes]
19
20
  daxta build
20
21
  daxta serve [--port <n>]
22
+ daxta tree [PATH] [--layout resource-first|url-order]
21
23
  daxta fields [METHOD] [PATH] [--out <file>]
22
24
  daxta call [METHOD] [PATH] [--fields <file>] [--header k:v ...]
23
25
  daxta call --file <values.json> [--header k:v ...]
@@ -27,6 +29,7 @@ One-shot setup:
27
29
  npx @t0.labs/daxta install
28
30
 
29
31
  daxta test = forwards to your package script (Jest stays parent; DAxTA is a plugin)
32
+ daxta tree = choose how paths appear in the /docs sidebar
30
33
  `);
31
34
  }
32
35
  function parseArgs(argv) {
@@ -40,7 +43,7 @@ function parseArgs(argv) {
40
43
  const token = rest[i];
41
44
  if (token === '--')
42
45
  break;
43
- if (token === '--port' || token === '--out' || token === '--fields' || token === '--file' || token === '--main') {
46
+ if (token === '--port' || token === '--out' || token === '--fields' || token === '--file' || token === '--main' || token === '--layout') {
44
47
  flags[token.slice(2)] = rest[++i];
45
48
  }
46
49
  else if (token === '--header') {
@@ -105,6 +108,13 @@ async function main() {
105
108
  (0, serve_1.serveApiDocs)({ port });
106
109
  return;
107
110
  }
111
+ if (command === 'tree') {
112
+ await (0, tree_1.runTreeWizard)({
113
+ path: positional[0],
114
+ layout: typeof flags.layout === 'string' ? flags.layout : undefined,
115
+ });
116
+ return;
117
+ }
108
118
  if (command === 'fields') {
109
119
  const method = positional[0]?.toLowerCase();
110
120
  const pathTemplate = positional[1];
@@ -0,0 +1,4 @@
1
+ export declare function runTreeWizard(options?: {
2
+ path?: string;
3
+ layout?: string;
4
+ }): Promise<void>;
@@ -0,0 +1,191 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.runTreeWizard = runTreeWizard;
4
+ const readline_1 = require("readline");
5
+ const fs_1 = require("fs");
6
+ const config_1 = require("../config");
7
+ const dto_fields_1 = require("../fields/dto-fields");
8
+ const paths_1 = require("../serve/paths");
9
+ const config_edit_1 = require("./config-edit");
10
+ const ui_1 = require("./ui");
11
+ function prompt(question) {
12
+ const rl = (0, readline_1.createInterface)({ input: process.stdin, output: process.stdout });
13
+ return new Promise((resolve) => {
14
+ rl.question(question, (answer) => {
15
+ rl.close();
16
+ resolve(answer.trim());
17
+ });
18
+ });
19
+ }
20
+ function normalizePathInput(raw) {
21
+ const trimmed = raw.trim();
22
+ if (!trimmed)
23
+ return trimmed;
24
+ return trimmed.startsWith('/') ? trimmed.replace(/\/+$/, '') || '/' : `/${trimmed.replace(/\/+$/, '')}`;
25
+ }
26
+ function urlOrderSegments(pathTemplate) {
27
+ return pathTemplate.split('/').filter(Boolean);
28
+ }
29
+ function resourceFirstSegments(pathTemplate) {
30
+ const parts = urlOrderSegments(pathTemplate);
31
+ if (parts.length >= 3 && /^v\d+$/i.test(parts[0])) {
32
+ return [parts[0], parts[2], parts[1], ...parts.slice(3)];
33
+ }
34
+ return parts;
35
+ }
36
+ /** Put known "area" segments (admin/device/…) right after version. */
37
+ function areaFirstSegments(pathTemplate) {
38
+ const parts = urlOrderSegments(pathTemplate);
39
+ if (parts.length < 3 || !/^v\d+$/i.test(parts[0]))
40
+ return parts;
41
+ const areas = new Set(['admin', 'device', 'devices', 'user', 'users', 'me', 'internal', 'public']);
42
+ const version = parts[0];
43
+ const rest = parts.slice(1);
44
+ const areaIdx = rest.findIndex((part) => areas.has(part.toLowerCase()) && !part.startsWith('{'));
45
+ if (areaIdx <= 0)
46
+ return parts;
47
+ const area = rest[areaIdx];
48
+ const without = [...rest.slice(0, areaIdx), ...rest.slice(areaIdx + 1)];
49
+ return [version, area, ...without];
50
+ }
51
+ function listKnownPaths() {
52
+ const fromSpec = new Set();
53
+ try {
54
+ const specPath = (0, paths_1.getSpecJsonPath)();
55
+ if ((0, fs_1.existsSync)(specPath)) {
56
+ const spec = JSON.parse((0, fs_1.readFileSync)(specPath, 'utf8'));
57
+ for (const key of Object.keys(spec.paths ?? {}))
58
+ fromSpec.add(key);
59
+ }
60
+ }
61
+ catch {
62
+ // ignore
63
+ }
64
+ for (const pathTemplate of (0, dto_fields_1.listControllerPathTemplates)())
65
+ fromSpec.add(pathTemplate);
66
+ return [...fromSpec].sort((a, b) => a.localeCompare(b));
67
+ }
68
+ function printPathChoices(paths, limit = 12) {
69
+ if (!paths.length) {
70
+ console.log(` ${ui_1.c.dim('no paths yet — run tests / daxta build, or type a path')}`);
71
+ return;
72
+ }
73
+ console.log(` ${ui_1.c.dim('known paths')}`);
74
+ paths.slice(0, limit).forEach((item, index) => {
75
+ console.log(` ${ui_1.c.dim(String(index + 1).padStart(2, ' '))} ${ui_1.c.cyan(item)}`);
76
+ });
77
+ if (paths.length > limit)
78
+ console.log(` ${ui_1.c.dim(`… +${paths.length - limit} more`)}`);
79
+ }
80
+ async function pickPath(flagPath) {
81
+ if (flagPath)
82
+ return normalizePathInput(flagPath);
83
+ const known = listKnownPaths();
84
+ printPathChoices(known);
85
+ const answer = await prompt(` ${ui_1.c.yellow('?')} ${ui_1.c.bold('Path')} to arrange in the sidebar\n` +
86
+ ` ${ui_1.c.dim('number, full path, or n to skip')}\n ${ui_1.c.cyan('›')} `);
87
+ if (!answer || /^n(o)?$/i.test(answer))
88
+ return null;
89
+ if (/^\d+$/.test(answer)) {
90
+ const picked = known[Number(answer) - 1];
91
+ if (!picked)
92
+ throw new Error(`No path #${answer}`);
93
+ return picked;
94
+ }
95
+ return normalizePathInput(answer);
96
+ }
97
+ async function pickGlobalLayout(current) {
98
+ console.log('');
99
+ console.log(` ${ui_1.c.bold('Default layout')} ${ui_1.c.dim(`(current: ${current})`)}`);
100
+ console.log(` ${ui_1.c.cyan('1')} resource-first ${ui_1.c.dim('v1 › baskets › admin')}`);
101
+ console.log(` ${ui_1.c.cyan('2')} url-order ${ui_1.c.dim('v1 › admin › baskets')}`);
102
+ console.log(` ${ui_1.c.cyan('3')} keep current`);
103
+ const answer = await prompt(` ${ui_1.c.yellow('?')} Choose default\n ${ui_1.c.cyan('›')} `);
104
+ if (!answer || answer === '3' || /^k(eep)?$/i.test(answer))
105
+ return null;
106
+ if (answer === '1' || /^resource/i.test(answer))
107
+ return 'resource-first';
108
+ if (answer === '2' || /^url/i.test(answer))
109
+ return 'url-order';
110
+ throw new Error(`Unknown layout choice: ${answer}`);
111
+ }
112
+ function layoutChoicesFor(pathTemplate) {
113
+ const url = urlOrderSegments(pathTemplate);
114
+ const resource = resourceFirstSegments(pathTemplate);
115
+ const area = areaFirstSegments(pathTemplate);
116
+ const choices = [
117
+ { id: 'url', label: 'URL order', segments: url },
118
+ { id: 'resource', label: 'Resource-first', segments: resource },
119
+ ];
120
+ if (area.join('/') !== url.join('/') && area.join('/') !== resource.join('/')) {
121
+ choices.push({ id: 'area', label: 'Area-first (admin/device/…)', segments: area });
122
+ }
123
+ choices.push({ id: 'custom', label: 'Custom segments', segments: url });
124
+ return choices;
125
+ }
126
+ async function pickSegments(pathTemplate) {
127
+ const choices = layoutChoicesFor(pathTemplate);
128
+ console.log('');
129
+ console.log(` ${ui_1.c.bold('Sidebar for')} ${ui_1.c.cyan(pathTemplate)}`);
130
+ choices.forEach((choice, index) => {
131
+ const mark = ui_1.c.cyan(String(index + 1));
132
+ console.log(` ${mark} ${ui_1.c.bold(choice.label)}`);
133
+ console.log(` ${(0, config_edit_1.previewTree)(choice.segments)}`);
134
+ });
135
+ const answer = await prompt(` ${ui_1.c.yellow('?')} How should this path appear?\n ${ui_1.c.cyan('›')} `);
136
+ if (!answer || /^n(o)?$/i.test(answer))
137
+ return null;
138
+ const index = /^\d+$/.test(answer) ? Number(answer) - 1 : choices.findIndex((choice) => choice.id === answer || choice.label.toLowerCase().startsWith(answer.toLowerCase()));
139
+ const selected = choices[index];
140
+ if (!selected)
141
+ throw new Error(`Unknown choice: ${answer}`);
142
+ if (selected.id !== 'custom')
143
+ return selected.segments;
144
+ const typed = await prompt(` ${ui_1.c.yellow('?')} Segments in order ${ui_1.c.dim('(space or › separated)')}\n` +
145
+ ` ${ui_1.c.dim(`e.g. v1 baskets admin`)}\n ${ui_1.c.cyan('›')} `);
146
+ if (!typed)
147
+ return null;
148
+ return typed
149
+ .split(/›|>|,|\s+/)
150
+ .map((part) => part.trim())
151
+ .filter(Boolean);
152
+ }
153
+ async function runTreeWizard(options = {}) {
154
+ (0, ui_1.banner)('DAxTA tree', 'sidebar folder order');
155
+ const configPath = (0, config_edit_1.findDaxtaConfigPath)();
156
+ if (!configPath) {
157
+ throw new Error('No daxta.config.ts found. Run `daxta install` first.');
158
+ }
159
+ (0, config_1.resetConfig)();
160
+ const config = (0, config_1.getConfig)(true);
161
+ if (options.layout === 'resource-first' || options.layout === 'url-order') {
162
+ (0, config_edit_1.upsertConfigValue)(configPath, 'treeLayout', (0, config_edit_1.formatTsString)(options.layout));
163
+ console.log(` ${ui_1.c.green('✔')} treeLayout → ${ui_1.c.cyan(options.layout)}`);
164
+ }
165
+ else if (!options.path && process.stdin.isTTY) {
166
+ const layout = await pickGlobalLayout(config.treeLayout);
167
+ if (layout) {
168
+ (0, config_edit_1.upsertConfigValue)(configPath, 'treeLayout', (0, config_edit_1.formatTsString)(layout));
169
+ console.log(` ${ui_1.c.green('✔')} treeLayout → ${ui_1.c.cyan(layout)}`);
170
+ }
171
+ }
172
+ const pathTemplate = await pickPath(options.path);
173
+ if (!pathTemplate) {
174
+ console.log(` ${ui_1.c.dim('done')}`);
175
+ return;
176
+ }
177
+ const segments = await pickSegments(pathTemplate);
178
+ if (!segments?.length) {
179
+ console.log(` ${ui_1.c.dim('skipped path override')}`);
180
+ return;
181
+ }
182
+ const overrides = (0, config_edit_1.readTreePathOverrides)();
183
+ overrides[pathTemplate] = segments;
184
+ (0, config_edit_1.upsertConfigValue)(configPath, 'treePathOverrides', (0, config_edit_1.formatTsStringRecord)(overrides));
185
+ console.log('');
186
+ console.log(` ${ui_1.c.green('✔')} ${ui_1.c.cyan(pathTemplate)}`);
187
+ console.log(` ${(0, config_edit_1.previewTree)(segments)}`);
188
+ console.log(` ${ui_1.c.dim('saved to')} ${configPath}`);
189
+ console.log(` ${ui_1.c.dim('refresh docs:')} ${ui_1.c.cyan('daxta build')}`);
190
+ console.log('');
191
+ }
@@ -1,4 +1,12 @@
1
1
  import 'reflect-metadata';
2
2
  export type FieldLocation = 'path' | 'query' | 'header' | 'body';
3
+ export declare function controllerRouteCount(): number;
4
+ /** Unique Nest controller path templates (may omit URI version prefix). */
5
+ export declare function listControllerPathTemplates(): string[];
6
+ /**
7
+ * Map a concrete request path onto a Nest controller OpenAPI template.
8
+ * Prefers the most specific declared route (longest path, fewest params).
9
+ */
10
+ export declare function matchControllerTemplate(pathname: string, method?: string): string | null;
3
11
  /** Returns required flag from DTO metadata, or undefined when unknown (no DTO / no validators). */
4
12
  export declare function dtoRequired(method: string, pathTemplate: string, location: FieldLocation, fieldName: string): boolean | undefined;
@@ -33,6 +33,9 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.controllerRouteCount = controllerRouteCount;
37
+ exports.listControllerPathTemplates = listControllerPathTemplates;
38
+ exports.matchControllerTemplate = matchControllerTemplate;
36
39
  exports.dtoRequired = dtoRequired;
37
40
  /**
38
41
  * Resolve Required / Optional from Nest controllers + class-validator DTO metadata.
@@ -46,6 +49,7 @@ const storage_1 = require("class-transformer/cjs/storage");
46
49
  const class_validator_1 = require("class-validator");
47
50
  const ts = __importStar(require("typescript"));
48
51
  const config_1 = require("../config");
52
+ const path_util_1 = require("../path.util");
49
53
  function controllerRoot() {
50
54
  return (0, config_1.getConfig)().controllersRoot;
51
55
  }
@@ -274,9 +278,68 @@ function getRoutes() {
274
278
  });
275
279
  return routeCache;
276
280
  }
281
+ function controllerRouteCount() {
282
+ return getRoutes().length;
283
+ }
284
+ /** Unique Nest controller path templates (may omit URI version prefix). */
285
+ function listControllerPathTemplates() {
286
+ const seen = new Set();
287
+ for (const route of getRoutes()) {
288
+ seen.add(route.pathTemplate);
289
+ if (!/^\/v\d+/i.test(route.pathTemplate)) {
290
+ seen.add(`/v1${route.pathTemplate.startsWith('/') ? route.pathTemplate : `/${route.pathTemplate}`}`);
291
+ }
292
+ }
293
+ return [...seen].sort((a, b) => a.localeCompare(b));
294
+ }
295
+ function scoreTemplate(template) {
296
+ const parts = template.split('/').filter(Boolean);
297
+ const params = parts.filter((part) => /^\{.+\}$/.test(part)).length;
298
+ return parts.length * 10 - params;
299
+ }
300
+ function ensureVersionPrefix(template, actual) {
301
+ if (/^\/v\d+/i.test(template) || !/^\/v\d+/i.test(actual))
302
+ return template;
303
+ const version = actual.match(/^\/(v\d+)/i)?.[1] ?? 'v1';
304
+ return `/${version}${template.startsWith('/') ? template : `/${template}`}`;
305
+ }
306
+ /**
307
+ * Map a concrete request path onto a Nest controller OpenAPI template.
308
+ * Prefers the most specific declared route (longest path, fewest params).
309
+ */
310
+ function matchControllerTemplate(pathname, method) {
311
+ const routes = getRoutes();
312
+ if (!routes.length)
313
+ return null;
314
+ const actual = (pathname.split('?')[0] || '/').replace(/\/+$/, '') || '/';
315
+ const stripped = actual.replace(/^\/v\d+(?=\/|$)/i, '') || '/';
316
+ const methodKey = method?.toLowerCase();
317
+ let best = null;
318
+ for (const route of routes) {
319
+ if (methodKey && route.method !== 'all' && route.method !== methodKey)
320
+ continue;
321
+ const base = route.pathTemplate;
322
+ const versioned = ensureVersionPrefix(base, actual);
323
+ const candidates = [...new Set([base, versioned])];
324
+ for (const template of candidates) {
325
+ const ok = (0, path_util_1.pathMatchesTemplate)(template, actual) ||
326
+ (0, path_util_1.pathMatchesTemplate)(base, stripped) ||
327
+ (0, path_util_1.pathMatchesTemplate)(template, stripped);
328
+ if (!ok)
329
+ continue;
330
+ const resolved = (0, path_util_1.pathMatchesTemplate)(template, actual) ? template : ensureVersionPrefix(base, actual);
331
+ const score = scoreTemplate(resolved);
332
+ if (!best || score > best.score)
333
+ best = { template: resolved, score };
334
+ }
335
+ }
336
+ return best?.template ?? null;
337
+ }
277
338
  function findRoute(method, pathTemplate) {
278
339
  const keyMethod = method.toLowerCase();
279
- return getRoutes().find((route) => route.method === keyMethod && route.pathTemplate === pathTemplate);
340
+ const routes = getRoutes();
341
+ return (routes.find((route) => route.method === keyMethod && route.pathTemplate === pathTemplate) ||
342
+ routes.find((route) => route.method === keyMethod && ensureVersionPrefix(route.pathTemplate, pathTemplate) === pathTemplate));
280
343
  }
281
344
  function isOptionalMetas(metas) {
282
345
  return metas.some((meta) => meta.type === 'conditionalValidation' || meta.name === 'isOptional');
@@ -1,6 +1,14 @@
1
1
  export declare function toOpenApiTemplate(path: string): string;
2
2
  export declare function templateFromTestName(test?: string): string | null;
3
3
  export declare function pathMatchesTemplate(template: string, actual: string): boolean;
4
- export declare function templatize(pathname: string, test?: string): string | null;
4
+ export declare function isDynamicSegment(segment: string, previous?: string): boolean;
5
+ export declare function heuristicTemplatize(pathname: string): string;
6
+ /**
7
+ * Map a concrete (or already-templated) path onto an OpenAPI template.
8
+ * Returns null when the hit should not be recorded (unknown vs Nest controllers).
9
+ */
10
+ export declare function templatize(pathname: string, test?: string, method?: string): string | null;
5
11
  export declare function pathParamNames(pathTemplate: string): string[];
6
12
  export declare function extractPathParams(pathTemplate: string, actualPath: string): Record<string, string>;
13
+ /** Fill `{param}` slots so a stored template can be re-matched / re-heuristic'd. */
14
+ export declare function materializePath(pathTemplate: string, pathParams?: Record<string, string>): string;
package/dist/path.util.js CHANGED
@@ -3,13 +3,48 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.toOpenApiTemplate = toOpenApiTemplate;
4
4
  exports.templateFromTestName = templateFromTestName;
5
5
  exports.pathMatchesTemplate = pathMatchesTemplate;
6
+ exports.isDynamicSegment = isDynamicSegment;
7
+ exports.heuristicTemplatize = heuristicTemplatize;
6
8
  exports.templatize = templatize;
7
9
  exports.pathParamNames = pathParamNames;
8
10
  exports.extractPathParams = extractPathParams;
11
+ exports.materializePath = materializePath;
9
12
  const config_1 = require("./config");
10
13
  const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
11
- const NUMERIC_ID_RE = /^\d{5,}$/;
14
+ const NUMERIC_ID_RE = /^-?\d+(\.\d+)?$/;
12
15
  const TOKENISH_RE = /^[A-Za-z0-9_-]{16,}$/;
16
+ const BOOLISH_RE = /^(true|false|null|undefined)$/i;
17
+ const ENCODED_RE = /%[0-9A-Fa-f]{2}/;
18
+ const LITERAL_PARAM_RE = /^\{[^}]+\}$/;
19
+ /** Path segments that are real route actions/resources, not id-like test values. */
20
+ const STATIC_SEGMENTS = new Set([
21
+ 'lock',
22
+ 'unlock',
23
+ 'pay',
24
+ 'complete',
25
+ 'cancel',
26
+ 'confirm',
27
+ 'status',
28
+ 'start',
29
+ 'stop',
30
+ 'retry',
31
+ 'approve',
32
+ 'reject',
33
+ 'search',
34
+ 'export',
35
+ 'import',
36
+ 'me',
37
+ 'admin',
38
+ 'device',
39
+ 'devices',
40
+ 'basket',
41
+ 'baskets',
42
+ 'user',
43
+ 'users',
44
+ 'health',
45
+ 'ready',
46
+ 'live',
47
+ ]);
13
48
  function toOpenApiTemplate(path) {
14
49
  return path.replace(/:([A-Za-z_][A-Za-z0-9_]*)/g, '{$1}');
15
50
  }
@@ -29,12 +64,43 @@ function pathMatchesTemplate(template, actual) {
29
64
  return false;
30
65
  return templateParts.every((part, index) => /^\{.+\}$/.test(part) || part === actualParts[index]);
31
66
  }
67
+ function safeDecode(segment) {
68
+ try {
69
+ return decodeURIComponent(segment);
70
+ }
71
+ catch {
72
+ return segment;
73
+ }
74
+ }
75
+ function looksLikeCollection(segment) {
76
+ if (!segment || /^v\d+$/i.test(segment) || /^\{.+\}$/.test(segment))
77
+ return false;
78
+ const lower = segment.toLowerCase();
79
+ if (STATIC_SEGMENTS.has(lower) && !lower.endsWith('s'))
80
+ return false;
81
+ return /s$/i.test(segment) || /list|items|records/i.test(segment);
82
+ }
83
+ function looksLikeStaticSegment(segment) {
84
+ return STATIC_SEGMENTS.has(safeDecode(segment).toLowerCase());
85
+ }
32
86
  function isDynamicSegment(segment, previous) {
33
- if (UUID_RE.test(segment))
87
+ const decoded = safeDecode(segment);
88
+ if (UUID_RE.test(decoded))
89
+ return true;
90
+ if (NUMERIC_ID_RE.test(decoded))
91
+ return true;
92
+ if (BOOLISH_RE.test(decoded))
93
+ return true;
94
+ if (LITERAL_PARAM_RE.test(decoded))
34
95
  return true;
35
- if (NUMERIC_ID_RE.test(segment))
96
+ if (ENCODED_RE.test(segment))
36
97
  return true;
37
- if (TOKENISH_RE.test(segment) && previous && !/^v\d+$/i.test(previous))
98
+ if (/^(\[\]|\{\}|\[.*\]|\{.*\})$/.test(decoded.replace(/\s/g, '')))
99
+ return true;
100
+ if (TOKENISH_RE.test(decoded) && previous && !/^v\d+$/i.test(previous))
101
+ return true;
102
+ // After a collection, only known actions/resources stay literal — test junk becomes {id}
103
+ if (previous && looksLikeCollection(previous) && !looksLikeStaticSegment(decoded))
38
104
  return true;
39
105
  return false;
40
106
  }
@@ -79,16 +145,43 @@ function heuristicTemplatize(pathname) {
79
145
  });
80
146
  return `/${templated.join('/')}`;
81
147
  }
82
- function templatize(pathname, test) {
148
+ function matchAgainstControllers(pathname, method) {
149
+ try {
150
+ // Lazy require avoids circular init with dto-fields → path.util
151
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
152
+ const dto = require('./fields/dto-fields');
153
+ const matched = dto.matchControllerTemplate(pathname, method);
154
+ if (matched)
155
+ return { matched };
156
+ if (dto.controllerRouteCount() > 0)
157
+ return { skip: true };
158
+ }
159
+ catch {
160
+ // controllers unavailable
161
+ }
162
+ return { none: true };
163
+ }
164
+ /**
165
+ * Map a concrete (or already-templated) path onto an OpenAPI template.
166
+ * Returns null when the hit should not be recorded (unknown vs Nest controllers).
167
+ */
168
+ function templatize(pathname, test, method) {
83
169
  const trimmed = (pathname.split('?')[0] || '/').replace(/\/+$/, '') || '/';
84
170
  if (trimmed === '/')
85
171
  return null;
86
172
  const custom = (0, config_1.getConfig)().templatize?.(trimmed, test);
87
173
  if (custom)
88
174
  return custom;
175
+ if (custom === null)
176
+ return null;
89
177
  const declared = templateFromTestName(test);
90
178
  if (declared && pathMatchesTemplate(declared, trimmed))
91
179
  return declared;
180
+ const controller = matchAgainstControllers(trimmed, method);
181
+ if ('matched' in controller)
182
+ return controller.matched;
183
+ if ('skip' in controller)
184
+ return null;
92
185
  return heuristicTemplatize(trimmed);
93
186
  }
94
187
  function pathParamNames(pathTemplate) {
@@ -106,3 +199,10 @@ function extractPathParams(pathTemplate, actualPath) {
106
199
  }
107
200
  return params;
108
201
  }
202
+ /** Fill `{param}` slots so a stored template can be re-matched / re-heuristic'd. */
203
+ function materializePath(pathTemplate, pathParams) {
204
+ return pathTemplate.replace(/\{([^}]+)\}/g, (_, name) => {
205
+ const value = pathParams?.[name];
206
+ return value != null && value !== '' ? encodeURIComponent(value) : name;
207
+ });
208
+ }
@@ -77,7 +77,7 @@ function recordFromSuperagent(request, res) {
77
77
  const rawUrl = request.url || '';
78
78
  const url = new URL(rawUrl, 'http://localhost');
79
79
  const test = currentTestName();
80
- const pathTemplate = (0, path_util_1.templatize)(url.pathname, test);
80
+ const pathTemplate = (0, path_util_1.templatize)(url.pathname, test, (request.method || 'GET').toLowerCase());
81
81
  if (!pathTemplate)
82
82
  return;
83
83
  const query = Object.fromEntries(url.searchParams.entries());
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@t0.labs/daxta",
3
- "version": "0.4.1",
3
+ "version": "0.4.3",
4
4
  "description": "DAxTA \u2014 docs from Nest integration traffic + DTO field CLI / Try-it",
5
5
  "license": "MIT",
6
6
  "repository": {