@t0.labs/daxta 0.2.0 → 0.2.2

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
@@ -2,39 +2,54 @@
2
2
 
3
3
  DAxTA — NestJS integration-test traffic → API docs, DTO required/optional, terminal Try-it, and app `/docs`.
4
4
 
5
- ## Install (zero manual wiring)
5
+ ## Install
6
6
 
7
7
  ```bash
8
8
  npm i -D @t0.labs/daxta
9
9
  npx daxta install
10
10
  ```
11
11
 
12
- `daxta install` writes `daxta.config.ts`, scripts, Jest hooks, and Nest `/docs` via `NODE_OPTIONS=--require @t0.labs/daxta/register`.
12
+ `daxta install`:
13
13
 
14
- ## Features
14
+ - writes `daxta.config.ts` + `daxta/out`
15
+ - strips any `NODE_OPTIONS=--require @t0.labs/daxta/register` from start scripts
16
+ - finds `main.ts`, asks **Y / n / other path**, injects:
15
17
 
16
- - Record supertest/superagent hits → OpenAPI + standalone HTML viewer
17
- - Required/Optional from `class-validator` DTO metadata
18
- - `/docs` on the app port (`mountDaxtaDocs` / auto-register)
19
- - Base URL inferred from serving path (`…/onboarding/docs` → `…/onboarding`)
20
- - Header groups auto-selected from operation `security`; env vars seeded from recorded traffic
21
- - CLI: `install`, `build`, `serve`, `fields`, `call`
18
+ ```ts
19
+ import { apiDocs } from '@t0.labs/daxta';
20
+ // ...
21
+ const app = await NestFactory.create(AppModule);
22
+ apiDocs(app);
23
+ ```
24
+
25
+ Flags: `--yes`, `--main src/main.ts`, `--skip-main`, `--dry-run`, `--skip-dep`
22
26
 
23
- ## CLI
27
+ ## Required env
28
+
29
+ `apiDocs(app)` **throws** if `DAXTA_DOCS` is missing:
24
30
 
25
31
  ```bash
26
- daxta install
27
- daxta build
32
+ DAXTA_DOCS=true # enable /docs
33
+ DAXTA_DOCS=false # disable (must be set explicitly)
34
+ ```
35
+
36
+ ## Runtime CLI
37
+
38
+ ```bash
39
+ daxta test
40
+ daxta test --config test/setup/jest.integration.json
28
41
  daxta serve
42
+ daxta build
29
43
  daxta fields
30
44
  daxta call
31
45
  ```
32
46
 
33
- ## Nest / Express
34
-
35
- Handled by install + register. Manual:
47
+ ## API
36
48
 
37
49
  ```ts
38
- import { mountDaxtaDocs } from '@t0.labs/daxta';
39
- mountDaxtaDocs(app, { enabled: process.env.NODE_ENV !== 'production' });
50
+ import { apiDocs, apiDocsHandler, serveApiDocs } from '@t0.labs/daxta';
51
+
52
+ apiDocs(app); // app /docs (needs DAXTA_DOCS)
53
+ app.use(apiDocsHandler()); // raw handler
54
+ serveApiDocs({ port: 5199 }); // standalone viewer
40
55
  ```
@@ -833,6 +833,35 @@
833
833
  { key: "content-type", value: "application/json" },
834
834
  ];
835
835
  }
836
+ // Pre-build merged groups for operations that need multiple schemes together.
837
+ const seenCombos = new Set();
838
+ for (const pathItem of Object.values(spec.paths || {})) {
839
+ for (const op of Object.values(pathItem || {})) {
840
+ if (!op || typeof op !== "object") continue;
841
+ const ids = [];
842
+ for (const requirement of op.security || []) {
843
+ if (!requirement || typeof requirement !== "object") continue;
844
+ for (const id of Object.keys(requirement)) {
845
+ if (headerGroups[id]) ids.push(id);
846
+ }
847
+ }
848
+ const unique = [...new Set(ids)];
849
+ if (unique.length < 2) continue;
850
+ const comboKey = unique.slice().sort().join("+");
851
+ if (seenCombos.has(comboKey)) continue;
852
+ seenCombos.add(comboKey);
853
+ const byKey = {};
854
+ for (const id of unique) {
855
+ for (const row of headerGroups[id] || []) {
856
+ if (!row.key) continue;
857
+ byKey[row.key] = { key: row.key, value: row.value };
858
+ }
859
+ }
860
+ if (!byKey["content-type"]) byKey["content-type"] = { key: "content-type", value: "application/json" };
861
+ headerGroups[comboKey] = Object.values(byKey);
862
+ }
863
+ }
864
+
836
865
  const groupNames = Object.keys(headerGroups);
837
866
  if (!groupNames.length) headerGroups.default = [{ key: "content-type", value: "application/json" }];
838
867
  return {
@@ -930,7 +959,7 @@
930
959
 
931
960
  const resolvedHeaders = () => resolvedHeadersFromGroup(store.activeGroup);
932
961
 
933
- /** OpenAPI security requirement scheme ids for an operation (AND). */
962
+ /** OpenAPI security scheme ids for an operation (union across requirements). */
934
963
  const securitySchemeIds = (op) => {
935
964
  const requirements = (op && op.security) || spec.security || [];
936
965
  if (!Array.isArray(requirements) || !requirements.length) return [];
@@ -942,44 +971,54 @@
942
971
  return [...new Set(ids)];
943
972
  };
944
973
 
945
- const headerGroupLabelForOp = (op) => {
974
+ /** Stable group name for this op: single scheme, or merged combo (userId+merchantId). */
975
+ const requiredGroupName = (op) => {
946
976
  const ids = securitySchemeIds(op);
947
- if (!ids.length) return store.activeGroup || "default";
948
- return ids.join(" + ");
977
+ if (!ids.length) return null;
978
+ if (ids.length === 1) return ids[0];
979
+ return ids.slice().sort().join("+");
949
980
  };
950
981
 
951
- const headersBadgeForOp = (op) => store.activeEnv + " · " + headerGroupLabelForOp(op);
952
-
953
- /** Merge header rows from every security scheme this operation needs. */
954
- const resolvedHeadersForOp = (op) => {
982
+ /** Fixed hint next to Headers — what this API needs to work. */
983
+ const requiredAuthHint = (op) => {
955
984
  const ids = securitySchemeIds(op);
956
- if (!ids.length) return resolvedHeaders();
985
+ if (!ids.length) return "";
986
+ return "Required: " + ids.join(" + ");
987
+ };
988
+
989
+ /** Ensure merged combo group exists in the active env (lazy for older localStorage). */
990
+ const ensureRequiredHeaderGroup = (op) => {
991
+ const name = requiredGroupName(op);
992
+ if (!name) return null;
957
993
  const env = activeEnvConfig();
958
- const groups = env.headerGroups || {};
959
- const vars = varMap();
960
- const merged = {};
994
+ const groups = env.headerGroups || (env.headerGroups = {});
995
+ if (groups[name]) return name;
996
+ const ids = securitySchemeIds(op);
997
+ const byKey = {};
961
998
  for (const id of ids) {
962
- const rows = groups[id] || [];
963
- for (const row of rows) {
999
+ for (const row of groups[id] || []) {
964
1000
  if (!row.key) continue;
965
- merged[row.key] = String(interpolate(row.value || "", vars));
1001
+ byKey[row.key] = { key: row.key, value: row.value };
966
1002
  }
967
1003
  }
968
- if (!Object.keys(merged).length) return resolvedHeaders();
969
- return merged;
1004
+ if (!Object.keys(byKey).length) return null;
1005
+ if (!byKey["content-type"]) byKey["content-type"] = { key: "content-type", value: "application/json" };
1006
+ groups[name] = Object.values(byKey);
1007
+ return name;
970
1008
  };
971
1009
 
1010
+ /**
1011
+ * On operation select: switch to the required (possibly merged) group once.
1012
+ * User can still change the group from the top env panel afterward; Send follows that.
1013
+ */
972
1014
  const syncHeaderGroupForOp = (op) => {
973
- const ids = securitySchemeIds(op);
974
- const groups = (activeEnvConfig().headerGroups) || {};
975
- if (ids.length === 1 && groups[ids[0]]) {
976
- if (store.activeGroup !== ids[0]) {
977
- store.activeGroup = ids[0];
978
- persistStore();
979
- syncEnvTrigger();
980
- if (document.getElementById("env-wrap")?.classList.contains("open")) renderEnvPop();
981
- }
982
- }
1015
+ const name = ensureRequiredHeaderGroup(op);
1016
+ if (!name) return;
1017
+ if (store.activeGroup === name) return;
1018
+ store.activeGroup = name;
1019
+ persistStore();
1020
+ syncEnvTrigger();
1021
+ if (document.getElementById("env-wrap")?.classList.contains("open")) renderEnvPop();
983
1022
  };
984
1023
 
985
1024
  const currentBaseUrl = () => String(interpolate(varMap().baseUrl || defaultBaseUrl, varMap()) || defaultBaseUrl).replace(/\/$/, "");
@@ -1320,7 +1359,7 @@
1320
1359
  };
1321
1360
 
1322
1361
  const toCurl = (item, scenario) => {
1323
- const headers = resolvedHeadersForOp(item.op);
1362
+ const headers = resolvedHeaders();
1324
1363
  const body = scenario.reqBody !== undefined ? interpolate(scenario.reqBody, varMap()) : undefined;
1325
1364
  const lines = ["curl -X " + item.method.toUpperCase() + " '" + resolvedUrl(item, scenario).replace(/'/g, "'\\''") + "'"];
1326
1365
  for (const [name, value] of Object.entries(headers)) {
@@ -1345,7 +1384,7 @@
1345
1384
 
1346
1385
  const sendRequest = async (item, scenario) => {
1347
1386
  const target = resolvedUrl(item, scenario);
1348
- const headers = { ...resolvedHeadersForOp(item.op) };
1387
+ const headers = { ...resolvedHeaders() };
1349
1388
  const body = scenario.reqBody !== undefined ? interpolate(scenario.reqBody, varMap()) : undefined;
1350
1389
  if (body !== undefined && !headers["content-type"] && !headers["Content-Type"]) {
1351
1390
  headers["content-type"] = "application/json";
@@ -1634,8 +1673,8 @@
1634
1673
  if (scenarioIndex >= item.scenarios.length) scenarioIndex = 0;
1635
1674
  const scenario = item.scenarios[scenarioIndex] || { status: 0, pathParams: {}, query: {}, headers: {}, name: "" };
1636
1675
  const fields = item.docs.fields || [];
1637
- syncHeaderGroupForOp(item.op);
1638
- const injectedHeaders = resolvedHeadersForOp(item.op);
1676
+ ensureRequiredHeaderGroup(item.op);
1677
+ const injectedHeaders = resolvedHeaders();
1639
1678
  const recordedOk = scenario.status >= 200 && scenario.status < 300;
1640
1679
  const statusText = STATUS[scenario.status] || item.op.responses?.[String(scenario.status)]?.description || "";
1641
1680
  const emptyResponse = scenario.resBody === undefined || scenario.status === 204;
@@ -1650,7 +1689,7 @@
1650
1689
  const responseTitle = showingLive ? "Live response" : "Recorded response";
1651
1690
  const headersHtml = Object.keys(injectedHeaders).length
1652
1691
  ? Object.entries(injectedHeaders).map(([name, value]) => kv(name, value)).join("")
1653
- : `<div class="meta-empty">No headers for this operation auth group - set values in the env panel.</div>`;
1692
+ : `<div class="meta-empty">No headers in the active group - pick the required group in the env panel.</div>`;
1654
1693
  const pathParamsHtml = Object.entries(scenario.pathParams || {})
1655
1694
  .map(([name, value]) => kv(name, value))
1656
1695
  .join("");
@@ -1684,7 +1723,7 @@
1684
1723
  </div>
1685
1724
  </div>
1686
1725
  <div class="card-body">
1687
- ${metaBlock("Headers", headersHtml, headersBadgeForOp(item.op), { always: true })}
1726
+ ${metaBlock("Headers", headersHtml, requiredAuthHint(item.op), { always: true })}
1688
1727
  ${metaBlock("Path", pathParamsHtml)}
1689
1728
  ${metaBlock("Query", queryHtml)}
1690
1729
  ${metaBlock("Body", bodyHtml, "", { always: true })}
@@ -0,0 +1,15 @@
1
+ /** Prefer Nest entrypoints: src/main.ts, main.ts, then other *main*.ts */
2
+ export declare function findMainCandidates(cwd: string): string[];
3
+ /**
4
+ * Ask: use detected main, or type another path / n to skip.
5
+ */
6
+ export declare function resolveMainPath(cwd: string, candidates: string[]): Promise<string | null>;
7
+ export declare function injectApiDocs(filePath: string, dryRun?: boolean): string;
8
+ export type InjectMainOptions = {
9
+ cwd?: string;
10
+ dryRun?: boolean;
11
+ /** Skip prompt; use first candidate or this relative/absolute path */
12
+ mainPath?: string;
13
+ yes?: boolean;
14
+ };
15
+ export declare function promptAndInjectMain(options?: InjectMainOptions): Promise<string | null>;
@@ -0,0 +1,214 @@
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.findMainCandidates = findMainCandidates;
37
+ exports.resolveMainPath = resolveMainPath;
38
+ exports.injectApiDocs = injectApiDocs;
39
+ exports.promptAndInjectMain = promptAndInjectMain;
40
+ const readline_1 = require("readline");
41
+ const fs_1 = require("fs");
42
+ const path = __importStar(require("path"));
43
+ const IMPORT_LINE = `import { apiDocs } from '@t0.labs/daxta';`;
44
+ const MARKER = 'apiDocs(';
45
+ function walk(dir, match, out = [], depth = 0) {
46
+ if (depth > 5 || !(0, fs_1.existsSync)(dir))
47
+ return out;
48
+ for (const name of (0, fs_1.readdirSync)(dir)) {
49
+ if (name === 'node_modules' || name === 'dist' || name === '.git' || name === 'coverage')
50
+ continue;
51
+ const full = path.join(dir, name);
52
+ let st;
53
+ try {
54
+ st = (0, fs_1.statSync)(full);
55
+ }
56
+ catch {
57
+ continue;
58
+ }
59
+ if (st.isDirectory())
60
+ walk(full, match, out, depth + 1);
61
+ else if (match(name))
62
+ out.push(full);
63
+ }
64
+ return out;
65
+ }
66
+ /** Prefer Nest entrypoints: src/main.ts, main.ts, then other *main*.ts */
67
+ function findMainCandidates(cwd) {
68
+ const preferred = ['src/main.ts', 'src/main.js', 'main.ts', 'main.js']
69
+ .map((rel) => path.join(cwd, rel))
70
+ .filter((p) => (0, fs_1.existsSync)(p));
71
+ const scanned = walk(cwd, (name) => /^(main|bootstrap)\.(ts|js|mts|cts)$/i.test(name));
72
+ const seen = new Set(preferred);
73
+ for (const file of scanned) {
74
+ if (!seen.has(file)) {
75
+ seen.add(file);
76
+ preferred.push(file);
77
+ }
78
+ }
79
+ return preferred;
80
+ }
81
+ function prompt(question) {
82
+ const rl = (0, readline_1.createInterface)({ input: process.stdin, output: process.stdout });
83
+ return new Promise((resolve) => {
84
+ rl.question(question, (answer) => {
85
+ rl.close();
86
+ resolve(answer.trim());
87
+ });
88
+ });
89
+ }
90
+ /**
91
+ * Ask: use detected main, or type another path / n to skip.
92
+ */
93
+ async function resolveMainPath(cwd, candidates) {
94
+ const def = candidates[0];
95
+ if (!def) {
96
+ const typed = await prompt('No main.ts found. Enter path (or n to skip): ');
97
+ if (!typed || /^n(o)?$/i.test(typed))
98
+ return null;
99
+ const full = path.isAbsolute(typed) ? typed : path.join(cwd, typed);
100
+ if (!(0, fs_1.existsSync)(full))
101
+ throw new Error(`File not found: ${full}`);
102
+ return full;
103
+ }
104
+ const rel = path.relative(cwd, def);
105
+ const others = candidates.length > 1
106
+ ? `\n other candidates: ${candidates
107
+ .slice(1, 4)
108
+ .map((c) => path.relative(cwd, c))
109
+ .join(', ')}${candidates.length > 4 ? ', …' : ''}`
110
+ : '';
111
+ const answer = await prompt(`Inject apiDocs(app) into ${rel}? [Y/n / or type another path]${others}\n> `);
112
+ if (!answer || /^y(es)?$/i.test(answer))
113
+ return def;
114
+ if (/^n(o)?$/i.test(answer))
115
+ return null;
116
+ const full = path.isAbsolute(answer) ? answer : path.join(cwd, answer);
117
+ if (!(0, fs_1.existsSync)(full))
118
+ throw new Error(`File not found: ${full}`);
119
+ return full;
120
+ }
121
+ function ensureImport(source) {
122
+ if (source.includes("from '@t0.labs/daxta'") || source.includes('from "@t0.labs/daxta"')) {
123
+ if (/import\s*\{[^}]*\bapiDocs\b/.test(source))
124
+ return source;
125
+ return source.replace(/import\s*\{([^}]*)\}\s*from\s*['"]@t0\.labs\/daxta['"]\s*;?/, (full, names) => {
126
+ let next = names;
127
+ next = next.replace(/\b(mountDaxtaDocs|docs)\b\s*,?\s*/g, '');
128
+ if (/\bapiDocs\b/.test(next)) {
129
+ return `import { ${next.trim().replace(/,$/, '')} } from '@t0.labs/daxta';`;
130
+ }
131
+ const trimmed = next.trim().replace(/,$/, '');
132
+ return trimmed
133
+ ? `import { ${trimmed}, apiDocs } from '@t0.labs/daxta';`
134
+ : `import { apiDocs } from '@t0.labs/daxta';`;
135
+ });
136
+ }
137
+ const lastImport = [...source.matchAll(/^import\s.+;?\s*$/gm)].pop();
138
+ if (lastImport && lastImport.index != null) {
139
+ const insertAt = lastImport.index + lastImport[0].length;
140
+ const after = source.slice(insertAt);
141
+ const pad = after.startsWith('\n\n') ? '\n' : after.startsWith('\n') ? '\n' : '\n';
142
+ return `${source.slice(0, insertAt)}${pad}${IMPORT_LINE}${source.slice(insertAt)}`;
143
+ }
144
+ return `${IMPORT_LINE}\n\n${source}`;
145
+ }
146
+ function ensureApiDocsCall(source) {
147
+ if (source.includes(MARKER) || source.includes('mountDaxtaDocs(') || /\bdocs\s*\(/.test(source)) {
148
+ return source
149
+ .replace(/\bmountDaxtaDocs\s*\(/g, 'apiDocs(')
150
+ .replace(/\bdocs\s*\(/g, 'apiDocs(');
151
+ }
152
+ const constMatch = source.match(/(const|let|var)\s+(\w+)\s*=\s*await\s+NestFactory\.create\b[\s\S]*?;/);
153
+ if (constMatch && constMatch.index != null) {
154
+ const varName = constMatch[2];
155
+ const insertAt = constMatch.index + constMatch[0].length;
156
+ const indent = guessIndent(source, insertAt);
157
+ const hook = `\n${indent}apiDocs(${varName});`;
158
+ return `${source.slice(0, insertAt)}${hook}${source.slice(insertAt)}`;
159
+ }
160
+ const assignMatch = source.match(/(\w+)\s*=\s*await\s+NestFactory\.create\b[\s\S]*?;/);
161
+ if (assignMatch && assignMatch.index != null) {
162
+ const varName = assignMatch[1];
163
+ const insertAt = assignMatch.index + assignMatch[0].length;
164
+ const indent = guessIndent(source, insertAt);
165
+ const hook = `\n${indent}apiDocs(${varName});`;
166
+ return `${source.slice(0, insertAt)}${hook}${source.slice(insertAt)}`;
167
+ }
168
+ throw new Error('Could not find `await NestFactory.create(...)` to inject apiDocs(app). Add it manually near bootstrap.');
169
+ }
170
+ function guessIndent(source, index) {
171
+ const lineStart = source.lastIndexOf('\n', index - 1) + 1;
172
+ const line = source.slice(lineStart, index);
173
+ const m = line.match(/^\s*/);
174
+ return m?.[0] ?? ' ';
175
+ }
176
+ function injectApiDocs(filePath, dryRun = false) {
177
+ const before = (0, fs_1.readFileSync)(filePath, 'utf8');
178
+ if (before.includes(MARKER) && /import\s*\{[^}]*\bapiDocs\b/.test(before)) {
179
+ return `already has apiDocs() in ${filePath}`;
180
+ }
181
+ let next = ensureImport(before);
182
+ next = ensureApiDocsCall(next);
183
+ if (next === before)
184
+ return `no changes for ${filePath}`;
185
+ if (!dryRun)
186
+ (0, fs_1.writeFileSync)(filePath, next);
187
+ return `injected apiDocs() into ${path.relative(process.cwd(), filePath)}`;
188
+ }
189
+ async function promptAndInjectMain(options = {}) {
190
+ const cwd = options.cwd ?? process.cwd();
191
+ const candidates = findMainCandidates(cwd);
192
+ let target;
193
+ if (options.mainPath) {
194
+ target = path.isAbsolute(options.mainPath) ? options.mainPath : path.join(cwd, options.mainPath);
195
+ if (!(0, fs_1.existsSync)(target))
196
+ throw new Error(`File not found: ${target}`);
197
+ }
198
+ else if (options.yes) {
199
+ target = candidates[0] ?? null;
200
+ if (!target)
201
+ throw new Error('No main.ts found; pass --main <path>');
202
+ }
203
+ else if (!process.stdin.isTTY) {
204
+ target = candidates[0] ?? null;
205
+ if (!target)
206
+ return 'skip main inject (no TTY / no main.ts)';
207
+ }
208
+ else {
209
+ target = await resolveMainPath(cwd, candidates);
210
+ }
211
+ if (!target)
212
+ return 'skipped main.ts inject';
213
+ return injectApiDocs(target, options.dryRun);
214
+ }
@@ -2,5 +2,12 @@ export type InstallOptions = {
2
2
  cwd?: string;
3
3
  skipDep?: boolean;
4
4
  dryRun?: boolean;
5
+ yes?: boolean;
6
+ mainPath?: string;
7
+ skipMain?: boolean;
5
8
  };
6
- export declare function installDaxta(options?: InstallOptions): void;
9
+ /**
10
+ * Bootstrap: config, outDir, scripts, strip NODE_OPTIONS hacks,
11
+ * prompt to inject `apiDocs(app)` into main.ts.
12
+ */
13
+ export declare function installDaxta(options?: InstallOptions): Promise<void>;