@t0.labs/daxta 0.4.4 → 0.4.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,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
@@ -1,4 +1,8 @@
1
- export type TreeLayout = 'resource-first' | 'url-order';
1
+ /** role→resource (URL order) vs resource→role (swap after version) */
2
+ export type TreeLayout = 'role-resource' | 'resource-role';
3
+ /** @deprecated use role-resource / resource-role */
4
+ export type LegacyTreeLayout = 'url-order' | 'resource-first';
5
+ export type ExampleLabelStyle = 'status-case' | 'status-title-case' | 'full';
2
6
  export type SpecInfo = {
3
7
  title?: string;
4
8
  version?: string;
@@ -9,18 +13,37 @@ export type DaxtaConfig = {
9
13
  baseUrl?: string;
10
14
  controllersRoot?: string;
11
15
  outDir?: string;
12
- treeLayout?: TreeLayout;
16
+ /**
17
+ * Sidebar / tag folder order after version:
18
+ * - role-resource → v1 › admin › baskets (URL order, recommended)
19
+ * - resource-role → v1 › baskets › admin
20
+ */
21
+ treeLayout?: TreeLayout | LegacyTreeLayout;
22
+ /**
23
+ * Do not create sidebar folders for `{param}` segments (and anything after).
24
+ * Ops like POST …/{id}/lock sit under the parent resource. Default true.
25
+ */
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;
13
33
  treePathOverrides?: Record<string, string[]>;
34
+ /**
35
+ * OpenAPI example + scenario labels:
36
+ * - status-case → `200 — returns basket when found`
37
+ * - status-title-case → `200 — Admin Find One Basket By Id API — returns…`
38
+ * - full → `200 — Admin Find… API - GET /v1/admin/baskets/{id} POSITIVE CASES returns…`
39
+ */
40
+ exampleLabelStyle?: ExampleLabelStyle;
14
41
  port?: number;
15
42
  fieldsFile?: string;
16
43
  docsPath?: string;
17
- /** package.json script name wired to DAxTA (e.g. test:integration) */
18
44
  testScript?: string;
19
- /** Original test command before wrap (e.g. jest --config …) */
20
45
  testCommand?: string;
21
- /** Last auto-migrated @t0.labs/daxta version */
22
46
  daxtaVersion?: string;
23
- /** Optional explicit Jest JSON config path */
24
47
  jestConfig?: string;
25
48
  templatize?: (pathname: string, test?: string) => string | null | undefined;
26
49
  operationTag?: (pathTemplate: string, method: string) => string | undefined;
@@ -31,8 +54,9 @@ export type DaxtaConfig = {
31
54
  includeHit?: (method: string, pathTemplate: string, test?: string) => boolean;
32
55
  treePathSegments?: (pathTemplate: string) => string[] | undefined;
33
56
  };
34
- export type ResolvedDaxtaConfig = Required<Pick<DaxtaConfig, 'workspace' | 'baseUrl' | 'controllersRoot' | 'outDir' | 'treeLayout' | 'treePathOverrides' | 'port' | 'fieldsFile' | 'docsPath'>> & DaxtaConfig;
57
+ export type ResolvedDaxtaConfig = Required<Pick<DaxtaConfig, 'workspace' | 'baseUrl' | 'controllersRoot' | 'outDir' | 'treeLayout' | 'treePathOverrides' | 'treeSkipParams' | 'exampleLabelStyle' | 'port' | 'fieldsFile' | 'docsPath'>> & DaxtaConfig;
35
58
  export declare function defineConfig(config: DaxtaConfig): DaxtaConfig;
59
+ export declare function normalizeTreeLayout(layout: TreeLayout | LegacyTreeLayout | undefined): TreeLayout;
36
60
  export declare function resolveConfig(cwd?: string, overrides?: DaxtaConfig): ResolvedDaxtaConfig;
37
61
  export declare function getConfig(forceReload?: boolean): ResolvedDaxtaConfig;
38
62
  export declare function setConfig(config: ResolvedDaxtaConfig): void;
package/dist/config.js CHANGED
@@ -34,6 +34,7 @@ var __importStar = (this && this.__importStar) || (function () {
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.defineConfig = defineConfig;
37
+ exports.normalizeTreeLayout = normalizeTreeLayout;
37
38
  exports.resolveConfig = resolveConfig;
38
39
  exports.getConfig = getConfig;
39
40
  exports.setConfig = setConfig;
@@ -45,8 +46,11 @@ const DEFAULTS = {
45
46
  baseUrl: 'http://localhost:3000',
46
47
  controllersRoot: 'src',
47
48
  outDir: 'daxta/out',
48
- treeLayout: 'resource-first',
49
+ treeLayout: 'role-resource',
50
+ treeSkipParams: true,
51
+ treeMaxDepth: null,
49
52
  treePathOverrides: {},
53
+ exampleLabelStyle: 'status-title-case',
50
54
  port: 5199,
51
55
  fieldsFile: 'daxta.fields.json',
52
56
  docsPath: '/docs',
@@ -55,6 +59,13 @@ let cached = null;
55
59
  function defineConfig(config) {
56
60
  return config;
57
61
  }
62
+ function normalizeTreeLayout(layout) {
63
+ if (layout === 'resource-first' || layout === 'resource-role')
64
+ return 'resource-role';
65
+ if (layout === 'url-order' || layout === 'role-resource')
66
+ return 'role-resource';
67
+ return 'role-resource';
68
+ }
58
69
  function loadConfigFile(cwd) {
59
70
  const candidates = ['daxta.config.ts', 'daxta.config.js', 'daxta.config.mjs', 'daxta.config.cjs'];
60
71
  for (const name of candidates) {
@@ -86,6 +97,11 @@ function resolveConfig(cwd = process.cwd(), overrides) {
86
97
  ...(overrides?.treePathOverrides ?? {}),
87
98
  },
88
99
  };
100
+ merged.treeLayout = normalizeTreeLayout(merged.treeLayout);
101
+ if (merged.treeSkipParams == null)
102
+ merged.treeSkipParams = DEFAULTS.treeSkipParams;
103
+ if (merged.exampleLabelStyle == null)
104
+ merged.exampleLabelStyle = DEFAULTS.exampleLabelStyle;
89
105
  merged.controllersRoot = path.isAbsolute(merged.controllersRoot)
90
106
  ? merged.controllersRoot
91
107
  : path.join(cwd, merged.controllersRoot);
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export { defineConfig, getConfig, resolveConfig, type DaxtaConfig, type TreeLayout, type SpecInfo } from './config';
1
+ export { defineConfig, getConfig, resolveConfig, normalizeTreeLayout, type DaxtaConfig, type TreeLayout, type ExampleLabelStyle, type SpecInfo } from './config';
2
2
  export { buildDaxtaSpec, buildOpenApi, loadHits, type BuildResult, type Scenario } from './build/build-spec';
3
3
  export { rebuildFromDisk, flushAndRebuild, clearPartialMarker, touchPartialMarker } from './build/incremental';
4
4
  export { install, flush, clearWorkerHits, getHits, type RecordedHit } from './recorder';
package/dist/index.js CHANGED
@@ -1,10 +1,11 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.installDaxta = exports.executeCall = exports.runFileCall = exports.runInteractiveCall = exports.getSpecJsonPath = exports.getOutDir = exports.getHtmlPath = exports.getDocsBasePath = exports.serveApiDocs = exports.apiDocsHandler = exports.apiDocs = exports.readFieldsFile = exports.writeFieldsFile = exports.buildFieldsFile = exports.dtoRequired = exports.getHits = exports.clearWorkerHits = exports.flush = exports.install = exports.touchPartialMarker = exports.clearPartialMarker = exports.flushAndRebuild = exports.rebuildFromDisk = exports.loadHits = exports.buildOpenApi = exports.buildDaxtaSpec = exports.resolveConfig = exports.getConfig = exports.defineConfig = void 0;
3
+ exports.installDaxta = exports.executeCall = exports.runFileCall = exports.runInteractiveCall = exports.getSpecJsonPath = exports.getOutDir = exports.getHtmlPath = exports.getDocsBasePath = exports.serveApiDocs = exports.apiDocsHandler = exports.apiDocs = exports.readFieldsFile = exports.writeFieldsFile = exports.buildFieldsFile = exports.dtoRequired = exports.getHits = exports.clearWorkerHits = exports.flush = exports.install = exports.touchPartialMarker = exports.clearPartialMarker = exports.flushAndRebuild = exports.rebuildFromDisk = exports.loadHits = exports.buildOpenApi = exports.buildDaxtaSpec = exports.normalizeTreeLayout = exports.resolveConfig = exports.getConfig = exports.defineConfig = void 0;
4
4
  var config_1 = require("./config");
5
5
  Object.defineProperty(exports, "defineConfig", { enumerable: true, get: function () { return config_1.defineConfig; } });
6
6
  Object.defineProperty(exports, "getConfig", { enumerable: true, get: function () { return config_1.getConfig; } });
7
7
  Object.defineProperty(exports, "resolveConfig", { enumerable: true, get: function () { return config_1.resolveConfig; } });
8
+ Object.defineProperty(exports, "normalizeTreeLayout", { enumerable: true, get: function () { return config_1.normalizeTreeLayout; } });
8
9
  var build_spec_1 = require("./build/build-spec");
9
10
  Object.defineProperty(exports, "buildDaxtaSpec", { enumerable: true, get: function () { return build_spec_1.buildDaxtaSpec; } });
10
11
  Object.defineProperty(exports, "buildOpenApi", { enumerable: true, get: function () { return build_spec_1.buildOpenApi; } });
@@ -1,2 +1,7 @@
1
1
  export declare function stripViewerExtensions(value: unknown): unknown;
2
+ /**
3
+ * Export OpenAPI with real URL paths (correct for clients) and tags/folders
4
+ * matching the docs sidebar (`x-tree-segments`).
5
+ */
6
+ export declare function toTreeOrderedOpenApi(raw: Record<string, unknown>): Record<string, unknown>;
2
7
  export declare function readStrippedOpenApiJson(): string | null;
@@ -1,10 +1,12 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.stripViewerExtensions = stripViewerExtensions;
4
+ exports.toTreeOrderedOpenApi = toTreeOrderedOpenApi;
4
5
  exports.readStrippedOpenApiJson = readStrippedOpenApiJson;
5
6
  const fs_1 = require("fs");
6
7
  const paths_1 = require("./paths");
7
8
  const VIEWER_EXTENSION_KEYS = new Set(['x-viewer', 'x-docs', 'x-scenarios', 'x-tree-segments', 'x-workspace']);
9
+ const HTTP_METHODS = new Set(['get', 'post', 'put', 'patch', 'delete', 'options', 'head', 'trace']);
8
10
  function stripViewerExtensions(value) {
9
11
  if (Array.isArray(value))
10
12
  return value.map(stripViewerExtensions);
@@ -18,10 +20,61 @@ function stripViewerExtensions(value) {
18
20
  }
19
21
  return out;
20
22
  }
23
+ function treeSegmentsForOperation(urlPath, operation) {
24
+ const fromExt = operation['x-tree-segments'];
25
+ if (Array.isArray(fromExt) && fromExt.every((part) => typeof part === 'string')) {
26
+ return fromExt;
27
+ }
28
+ return urlPath.split('/').filter(Boolean);
29
+ }
30
+ /**
31
+ * Export OpenAPI with real URL paths (correct for clients) and tags/folders
32
+ * matching the docs sidebar (`x-tree-segments`).
33
+ */
34
+ function toTreeOrderedOpenApi(raw) {
35
+ const sourcePaths = (raw.paths ?? {});
36
+ const exportPaths = {};
37
+ const tagNames = new Set();
38
+ for (const [urlPath, pathItem] of Object.entries(sourcePaths)) {
39
+ if (!pathItem || typeof pathItem !== 'object')
40
+ continue;
41
+ const exportPathItem = {};
42
+ for (const [key, value] of Object.entries(pathItem)) {
43
+ if (!HTTP_METHODS.has(key) || !value || typeof value !== 'object') {
44
+ if (!HTTP_METHODS.has(key))
45
+ exportPathItem[key] = stripViewerExtensions(value);
46
+ continue;
47
+ }
48
+ const operation = value;
49
+ const segments = treeSegmentsForOperation(urlPath, operation);
50
+ const cleaned = stripViewerExtensions(operation);
51
+ const tagParts = segments.filter((part) => !part.startsWith('{'));
52
+ const tag = tagParts.length ? tagParts.join(' / ') : 'API';
53
+ cleaned.tags = [tag];
54
+ tagNames.add(tag);
55
+ exportPathItem[key] = cleaned;
56
+ }
57
+ exportPaths[urlPath] = exportPathItem;
58
+ }
59
+ const orderedPaths = {};
60
+ for (const key of Object.keys(exportPaths).sort((a, b) => a.localeCompare(b))) {
61
+ orderedPaths[key] = exportPaths[key];
62
+ }
63
+ const info = stripViewerExtensions(raw.info ?? { title: 'API', version: '0.0.0' });
64
+ const tags = [...tagNames].sort((a, b) => a.localeCompare(b)).map((name) => ({ name }));
65
+ return {
66
+ openapi: raw.openapi || '3.0.3',
67
+ info,
68
+ ...(raw.servers ? { servers: stripViewerExtensions(raw.servers) } : {}),
69
+ tags,
70
+ paths: orderedPaths,
71
+ ...(raw.components ? { components: stripViewerExtensions(raw.components) } : {}),
72
+ };
73
+ }
21
74
  function readStrippedOpenApiJson() {
22
75
  const specPath = (0, paths_1.getSpecJsonPath)();
23
76
  if (!(0, fs_1.existsSync)(specPath))
24
77
  return null;
25
78
  const raw = JSON.parse((0, fs_1.readFileSync)(specPath, 'utf8'));
26
- return `${JSON.stringify(stripViewerExtensions(raw), null, 2)}\n`;
79
+ return `${JSON.stringify(toTreeOrderedOpenApi(raw), null, 2)}\n`;
27
80
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@t0.labs/daxta",
3
- "version": "0.4.4",
3
+ "version": "0.4.6",
4
4
  "description": "DAxTA \u2014 docs from Nest integration traffic + DTO field CLI / Try-it",
5
5
  "license": "MIT",
6
6
  "repository": {