@t0.labs/daxta 0.4.13 → 0.4.15

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
@@ -128,12 +128,12 @@ Company-wide choices (saved in `daxta.config.ts`):
128
128
 
129
129
  | Option | Meaning |
130
130
  | --- | --- |
131
- | `treeLayout` | `role-resource` (`v1 › admin › baskets`) or `resource-role` (`v1 › baskets › admin`) — sidebar **and** OpenAPI export path keys |
131
+ | `treeLayout` | `role-resource` (`v1 › admin › baskets`) or `resource-role` (`v1 › baskets › admin`) — sidebar **and** Postman export folders |
132
132
  | `treeSkipParams` | Don’t nest folders under `{id}` (recommended `true`) |
133
133
  | `envPresets` | Multi-base Try-it presets (`local` / `staging` / `production` + optional variables) |
134
134
  | `exampleLabelStyle` | OpenAPI example labels: `status-title-case` / `status-case` / `full` |
135
135
 
136
- 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`).
136
+ OpenAPI path keys in the generated spec still follow the sidebar tree. Real URLs stay on `x-daxta-url-path` when the layout differs (e.g. `/v1/admin/baskets` → tree `/v1/baskets/admin`).
137
137
 
138
138
  ### Try-it env / headers (persisted)
139
139
 
@@ -156,14 +156,7 @@ envPresets: {
156
156
 
157
157
  Sidebar: expand the chevron on an endpoint to list recorded examples underneath; click one to open it in the workbench.
158
158
 
159
- Export: the download button opens a picker (All / None / Success only) so the OpenAPI JSON only includes the selected examples.
160
-
161
- For Postman-friendly fills, export can bake the **active Try-it env + header group** into the OpenAPI (`servers` + header `example`s). Two modes:
162
-
163
- - **Resolved values** — literals in the OpenAPI (import with parameter generation = Example)
164
- - **Postman `{{variables}}`** — placeholders in OpenAPI + a companion `.postman_environment.json`
165
-
166
- Also download **Postman Collection** (default on): example names stay as `201 — should create…` instead of generic `Created` / `Bad Request` (Postman’s OpenAPI importer names examples from status description).
159
+ Export: download is **Postman Collection** (nested folders like the sidebar) plus, by default, the active Try-it **environment + header group** as a `.postman_environment.json`. Pick All / None / Success only for which examples to include. Import the collection, then the environment, and select that env in Postman.
167
160
 
168
161
  Example label (`status-title-case`):
169
162
 
@@ -173,6 +166,29 @@ Example label (`status-title-case`):
173
166
 
174
167
  Then `daxta build` to refresh `/docs` and export.
175
168
 
169
+ ## Test titles (docs / Postman names)
170
+
171
+ Docs and the collection use a **human title**, not the raw path. Put it in `TEST_TITLE` (or the describe string):
172
+
173
+ ```ts
174
+ static TEST_TITLE = () => `Create Mock Tbs /v1/admin/mock-tbs [POST] (integration)`;
175
+ describe(`${TEST_TITLE()} POSITIVE CASES`, () => { /* … */ });
176
+ ```
177
+
178
+ Format: `{Title} {path} [{METHOD}] (integration)`
179
+
180
+ - Verb comes from the method (`GET` collection → Find All, `GET …/{id}` → Find One, `POST` → Create, …) plus kebab resource (`mock-tbs` → Mock Tbs). Action segments (`validate`, `approve`, …) become the verb.
181
+ - Skip the title and docs fall back to the path.
182
+ - `it()` example names: `{outcome} when {condition}` — e.g. `creates mock tbs when payload is valid`. No path, no `[POST]`, no status (status comes from the recorded hit).
183
+ - `daxta titles` lists file:line for both rules; pick a suggestion, type custom, or skip.
184
+ - **Before tests:** Jest `globalSetup` always scans (plugin). `daxta test` scans too, then starts Jest. `daxta titles --check --strict` or `DAXTA_TITLE_CHECK=strict` fails CI.
185
+
186
+ ```bash
187
+ daxta titles # interactive
188
+ daxta titles --check # report only
189
+ ```
190
+
191
+
176
192
 
177
193
 
178
194
  ## API
@@ -642,28 +642,6 @@
642
642
  color: var(--stone);
643
643
  font-family: var(--mono);
644
644
  }
645
- .export-mode {
646
- display: flex;
647
- flex-direction: column;
648
- gap: 6px;
649
- margin-left: 22px;
650
- }
651
- .export-mode label {
652
- display: flex;
653
- align-items: flex-start;
654
- gap: 8px;
655
- font-size: 12px;
656
- color: var(--charcoal);
657
- cursor: pointer;
658
- line-height: 1.35;
659
- }
660
- .export-mode.disabled { opacity: 0.45; pointer-events: none; }
661
- .export-tip {
662
- margin: 0 0 0 22px;
663
- font-size: 11px;
664
- color: var(--stone);
665
- line-height: 1.4;
666
- }
667
645
  .export-toolbar {
668
646
  display: flex;
669
647
  flex-wrap: wrap;
@@ -1097,7 +1075,7 @@
1097
1075
  <div class="search-panel" id="search-panel" role="listbox"></div>
1098
1076
  </div>
1099
1077
  <div class="nav-tools">
1100
- <button class="btn icon" id="export-openapi" type="button" data-tip="Export OpenAPI" aria-label="Export OpenAPI">
1078
+ <button class="btn icon" id="export-openapi" type="button" data-tip="Export Postman" aria-label="Export Postman">
1101
1079
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
1102
1080
  </button>
1103
1081
  <div class="env-wrap" id="env-wrap">
@@ -1110,30 +1088,15 @@
1110
1088
  <div class="export-backdrop" id="export-backdrop" role="dialog" aria-modal="true" aria-labelledby="export-title">
1111
1089
  <div class="export-modal" id="export-modal">
1112
1090
  <div class="export-head">
1113
- <h2 id="export-title">Export OpenAPI</h2>
1114
- <p>Choose examples to include. Optionally bake Try-it env/headers so Postman can auto-fill on import.</p>
1091
+ <h2 id="export-title">Export Postman</h2>
1092
+ <p>Pick examples, then download a Collection with the docs folder tree. Env + headers come from the active Try-it preset.</p>
1115
1093
  </div>
1116
1094
  <div class="export-options">
1117
1095
  <label class="export-check">
1118
1096
  <input type="checkbox" id="export-include-tryit" checked />
1119
- <span>Include active Try-it env + header group</span>
1097
+ <span>Include env + headers <span style="color:var(--stone)">(Collection uses <code>{{baseUrl}}</code> / <code>{{vars}}</code> + environment file)</span></span>
1120
1098
  </label>
1121
1099
  <div class="export-tryit-meta" id="export-tryit-meta">—</div>
1122
- <div class="export-mode" id="export-mode-wrap">
1123
- <label>
1124
- <input type="radio" name="export-fill" value="resolved" checked />
1125
- <span>Resolved values in OpenAPI <span style="color:var(--stone)">(headers/server filled literally)</span></span>
1126
- </label>
1127
- <label>
1128
- <input type="radio" name="export-fill" value="variables" />
1129
- <span>Postman <code>{{variables}}</code> + download environment file</span>
1130
- </label>
1131
- </div>
1132
- <p class="export-tip">Postman names saved examples from OpenAPI <em>response description</em> (“Created”), so also download a Collection with the real scenario titles. Import → advanced → parameter generation = <strong>Example</strong>.</p>
1133
- <label class="export-check">
1134
- <input type="checkbox" id="export-postman-collection" checked />
1135
- <span>Also download Postman Collection <span style="color:var(--stone)">(named examples)</span></span>
1136
- </label>
1137
1100
  </div>
1138
1101
  <div class="export-toolbar">
1139
1102
  <button type="button" class="btn sm" id="export-all">All</button>
@@ -2139,64 +2102,6 @@
2139
2102
  return groups[store.activeGroup] || groups[Object.keys(groups)[0]] || [];
2140
2103
  };
2141
2104
 
2142
- const applyTryItFill = (exported, fillMode) => {
2143
- const vars = varMap();
2144
- const rows = headerRowsForExport();
2145
- const finalServer =
2146
- fillMode === "variables" ? "{{baseUrl}}" : String(interpolate(vars.baseUrl || defaultBaseUrl, vars)).replace(/\/$/, "") || defaultBaseUrl;
2147
-
2148
- exported.servers = [{ url: finalServer }];
2149
-
2150
- const paths = exported.paths || {};
2151
- for (const pathItem of Object.values(paths)) {
2152
- if (!pathItem || typeof pathItem !== "object") continue;
2153
- for (const method of HTTP_EXPORT) {
2154
- if (!pathItem[method] || typeof pathItem[method] !== "object") continue;
2155
- const operation = { ...pathItem[method] };
2156
- const params = Array.isArray(operation.parameters) ? operation.parameters.map((p) => ({ ...p })) : [];
2157
-
2158
- for (const row of rows) {
2159
- if (!row.key) continue;
2160
- const lower = String(row.key).toLowerCase();
2161
- if (lower === "host" || lower === "content-length") continue;
2162
- const exampleValue =
2163
- fillMode === "resolved"
2164
- ? String(interpolate(row.value || "", vars))
2165
- : String(row.value ?? "");
2166
- const existing = params.findIndex(
2167
- (param) => param && param.in === "header" && String(param.name).toLowerCase() === lower,
2168
- );
2169
- if (existing >= 0) {
2170
- const prev = params[existing];
2171
- params[existing] = {
2172
- ...prev,
2173
- required: prev.required !== false,
2174
- example: exampleValue,
2175
- schema: {
2176
- ...(prev.schema && typeof prev.schema === "object" ? prev.schema : {}),
2177
- type: "string",
2178
- example: exampleValue,
2179
- },
2180
- };
2181
- } else {
2182
- params.push({
2183
- name: row.key,
2184
- in: "header",
2185
- required: true,
2186
- schema: { type: "string", example: exampleValue },
2187
- example: exampleValue,
2188
- });
2189
- }
2190
- }
2191
-
2192
- operation.parameters = params;
2193
- pathItem[method] = operation;
2194
- }
2195
- }
2196
-
2197
- return exported;
2198
- };
2199
-
2200
2105
  const buildPostmanEnvironment = () => {
2201
2106
  const env = activeEnvConfig();
2202
2107
  const values = (env.variables || [])
@@ -2209,6 +2114,15 @@
2209
2114
  }));
2210
2115
  // Ensure header template vars referenced as {{x}} appear even if missing from variables list.
2211
2116
  const known = new Set(values.map((row) => row.key));
2117
+ if (!known.has("baseUrl")) {
2118
+ known.add("baseUrl");
2119
+ values.unshift({
2120
+ key: "baseUrl",
2121
+ value: String(presetBaseUrl(store.activeEnv) || defaultBaseUrl || ""),
2122
+ type: "default",
2123
+ enabled: true,
2124
+ });
2125
+ }
2212
2126
  for (const row of headerRowsForExport()) {
2213
2127
  const text = String(row.value || "");
2214
2128
  const matches = text.matchAll(/\{\{\s*([a-zA-Z0-9_]+)\s*\}\}/g);
@@ -2286,12 +2200,30 @@
2286
2200
  return [...folders, ...requests];
2287
2201
  };
2288
2202
 
2203
+ const collectionRequestHeaders = (operation, includeTryIt) => {
2204
+ const byLower = new Map();
2205
+ const add = (key, value) => {
2206
+ if (!key) return;
2207
+ const lower = String(key).toLowerCase();
2208
+ if (lower === "host" || lower === "content-length") return;
2209
+ byLower.set(lower, { key, value: value != null ? String(value) : "", type: "text" });
2210
+ };
2211
+ for (const param of operation.parameters || []) {
2212
+ if (param && param.in === "header" && param.name) add(param.name, param.example != null ? param.example : "");
2213
+ }
2214
+ if (includeTryIt) {
2215
+ for (const row of headerRowsForExport()) add(row.key, row.value ?? "");
2216
+ }
2217
+ return [...byLower.values()];
2218
+ };
2219
+
2289
2220
  /**
2290
- * Postman Collection v2.1 — example `name` = scenario title (not "Created" / "Bad Request").
2291
- * Folders follow the docs tree (v1 → admin → product), not a single joined tag.
2221
+ * Postman Collection v2.1 — nested folders + named examples.
2222
+ * When includeTryIt, requests use {{baseUrl}} and the active header group; env file is downloaded separately.
2292
2223
  */
2293
- const buildPostmanCollection = (openapi) => {
2294
- const serverUrl = (openapi.servers && openapi.servers[0] && openapi.servers[0].url) || "{{baseUrl}}";
2224
+ const buildPostmanCollection = (openapi, includeTryIt) => {
2225
+ const specServer = (openapi.servers && openapi.servers[0] && openapi.servers[0].url) || "{{baseUrl}}";
2226
+ const serverUrl = includeTryIt ? "{{baseUrl}}" : specServer;
2295
2227
  const root = [];
2296
2228
 
2297
2229
  for (const [urlPath, pathItem] of Object.entries(openapi.paths || {})) {
@@ -2300,13 +2232,7 @@
2300
2232
  const operation = pathItem[method];
2301
2233
  if (!operation || typeof operation !== "object") continue;
2302
2234
  const requestPath = operation["x-daxta-url-path"] || urlPath;
2303
-
2304
- const headerParams = (operation.parameters || []).filter((param) => param && param.in === "header" && param.name);
2305
- const requestHeaders = headerParams.map((param) => ({
2306
- key: param.name,
2307
- value: param.example != null ? String(param.example) : "",
2308
- type: "text",
2309
- }));
2235
+ const requestHeaders = collectionRequestHeaders(operation, includeTryIt);
2310
2236
 
2311
2237
  const reqExamples = operation.requestBody?.content?.["application/json"]?.examples || {};
2312
2238
  const firstReq = Object.values(reqExamples)[0];
@@ -2395,10 +2321,7 @@
2395
2321
 
2396
2322
  const syncExportTryItUi = () => {
2397
2323
  const meta = document.getElementById("export-tryit-meta");
2398
- const modeWrap = document.getElementById("export-mode-wrap");
2399
- const include = document.getElementById("export-include-tryit");
2400
2324
  if (meta) meta.textContent = store.activeEnv + " · " + store.activeGroup;
2401
- if (modeWrap) modeWrap.classList.toggle("disabled", !(include && include.checked));
2402
2325
  };
2403
2326
 
2404
2327
  const openExportModal = () => {
@@ -2457,35 +2380,19 @@
2457
2380
  String(workspace || title || "openapi")
2458
2381
  .toLowerCase()
2459
2382
  .replace(/[^a-z0-9]+/g, "-")
2460
- .replace(/^-|-$/g, "") || "openapi";
2383
+ .replace(/^-|-$/g, "") || "daxta";
2461
2384
 
2462
2385
  const runExportDownload = () => {
2463
2386
  const selectedByOpId = collectSelectedExamples();
2464
- let exported = toExportSpec(spec, selectedByOpId);
2387
+ const exported = toExportSpec(spec, selectedByOpId);
2465
2388
  const includeTryIt = Boolean(document.getElementById("export-include-tryit")?.checked);
2466
- const wantCollection = Boolean(document.getElementById("export-postman-collection")?.checked);
2467
- const fillMode =
2468
- document.querySelector('input[name="export-fill"]:checked')?.value === "variables" ? "variables" : "resolved";
2469
2389
  const base = exportSafeName();
2470
2390
 
2391
+ downloadJsonFile(base + ".postman_collection.json", buildPostmanCollection(exported, includeTryIt));
2471
2392
  if (includeTryIt) {
2472
- exported = applyTryItFill(exported, fillMode);
2473
- }
2474
-
2475
- downloadJsonFile(base + ".openapi.json", exported);
2476
-
2477
- let delay = 120;
2478
- if (wantCollection) {
2479
- setTimeout(() => {
2480
- downloadJsonFile(base + ".postman_collection.json", buildPostmanCollection(exported));
2481
- }, delay);
2482
- delay += 120;
2483
- }
2484
-
2485
- if (includeTryIt && fillMode === "variables") {
2486
2393
  setTimeout(() => {
2487
2394
  downloadJsonFile(base + ".postman_environment.json", buildPostmanEnvironment());
2488
- }, delay);
2395
+ }, 120);
2489
2396
  }
2490
2397
  };
2491
2398
 
@@ -2498,7 +2405,6 @@
2498
2405
  if (event.target.id === "export-backdrop") closeExportModal();
2499
2406
  });
2500
2407
  document.getElementById("export-modal").addEventListener("click", (event) => event.stopPropagation());
2501
- document.getElementById("export-include-tryit").addEventListener("change", syncExportTryItUi);
2502
2408
  document.getElementById("export-all").addEventListener("click", () => {
2503
2409
  document.querySelectorAll("#export-body input[type=checkbox]").forEach((input) => {
2504
2410
  input.checked = true;
@@ -1,4 +1,6 @@
1
1
  import { type TreeLayout } from '../config';
2
+ export { parseOperationLabel, suggestOperationTitles, formatTestTitle } from './test-title';
3
+ export { isValidItCase, suggestItCases, parseCaseSection, type CaseSection } from './it-case';
2
4
  export type { TreeLayout };
3
5
  export type FieldDoc = {
4
6
  name: string;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.STATUS_TEXT = void 0;
3
+ exports.STATUS_TEXT = exports.parseCaseSection = exports.suggestItCases = exports.isValidItCase = exports.formatTestTitle = exports.suggestOperationTitles = exports.parseOperationLabel = void 0;
4
4
  exports.declaredMethods = declaredMethods;
5
5
  exports.pathSegments = pathSegments;
6
6
  exports.treePathSegments = treePathSegments;
@@ -14,6 +14,15 @@ exports.caseName = caseName;
14
14
  exports.exampleLabel = exampleLabel;
15
15
  exports.operationSummary = operationSummary;
16
16
  const config_1 = require("../config");
17
+ const test_title_1 = require("./test-title");
18
+ var test_title_2 = require("./test-title");
19
+ Object.defineProperty(exports, "parseOperationLabel", { enumerable: true, get: function () { return test_title_2.parseOperationLabel; } });
20
+ Object.defineProperty(exports, "suggestOperationTitles", { enumerable: true, get: function () { return test_title_2.suggestOperationTitles; } });
21
+ Object.defineProperty(exports, "formatTestTitle", { enumerable: true, get: function () { return test_title_2.formatTestTitle; } });
22
+ var it_case_1 = require("./it-case");
23
+ Object.defineProperty(exports, "isValidItCase", { enumerable: true, get: function () { return it_case_1.isValidItCase; } });
24
+ Object.defineProperty(exports, "suggestItCases", { enumerable: true, get: function () { return it_case_1.suggestItCases; } });
25
+ Object.defineProperty(exports, "parseCaseSection", { enumerable: true, get: function () { return it_case_1.parseCaseSection; } });
17
26
  exports.STATUS_TEXT = {
18
27
  '200': 'OK',
19
28
  '201': 'Created',
@@ -138,6 +147,9 @@ function caseSectionLabel(test) {
138
147
  function apiTitle(test) {
139
148
  if (!test)
140
149
  return undefined;
150
+ const fromLabel = (0, test_title_1.parseOperationLabel)(test)?.title;
151
+ if (fromLabel)
152
+ return fromLabel;
141
153
  const patterns = [
142
154
  /^(.+?\bAPI)\s*[-–—]\s*(?:GET|POST|PUT|PATCH|DELETE)\b/i,
143
155
  /\]\s*(?:\([^)]*\)\s*)?(.+?\bAPI)\s+(?:POSITIVE|SEMANTIC|INVALID|OMITTED)\b/i,
@@ -0,0 +1,7 @@
1
+ export type CaseSection = 'positive' | 'semantic' | 'invalid' | 'omitted' | 'auth';
2
+ export declare function parseCaseSection(raw?: string): CaseSection | undefined;
3
+ export declare function isValidItCase(name?: string): boolean;
4
+ /**
5
+ * Deterministic it() suggestions: `{outcome} when {condition}`.
6
+ */
7
+ export declare function suggestItCases(section: CaseSection | undefined, method?: string, pathTemplate?: string): string[];
@@ -0,0 +1,96 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.parseCaseSection = parseCaseSection;
4
+ exports.isValidItCase = isValidItCase;
5
+ exports.suggestItCases = suggestItCases;
6
+ const test_title_1 = require("./test-title");
7
+ const CASE_START = /^(returns|creates|updates|deletes|lists|rejects|conflicts)\b/i;
8
+ function parseCaseSection(raw) {
9
+ if (!raw)
10
+ return undefined;
11
+ if (/SEMANTIC ERROR CASES\s*-\s*AUTH/i.test(raw))
12
+ return 'auth';
13
+ if (/POSITIVE CASES/i.test(raw))
14
+ return 'positive';
15
+ if (/SEMANTIC ERROR CASES/i.test(raw))
16
+ return 'semantic';
17
+ if (/INVALID CASES/i.test(raw))
18
+ return 'invalid';
19
+ if (/OMITTED/i.test(raw))
20
+ return 'omitted';
21
+ return undefined;
22
+ }
23
+ function isValidItCase(name) {
24
+ const value = name?.trim() ?? '';
25
+ if (value.length < 12 || value.length > 100)
26
+ return false;
27
+ if (value.startsWith('/'))
28
+ return false;
29
+ if (/\[(GET|POST|PUT|PATCH|DELETE|UPDATE|UPSERT)\]/i.test(value))
30
+ return false;
31
+ if (/(POSITIVE CASES|SEMANTIC ERROR CASES|INVALID CASES|OMITTED)/i.test(value))
32
+ return false;
33
+ if (!CASE_START.test(value))
34
+ return false;
35
+ if (!/\bwhen\b/i.test(value))
36
+ return false;
37
+ return true;
38
+ }
39
+ function resourcePhrase(pathTemplate) {
40
+ if (!pathTemplate)
41
+ return 'resource';
42
+ const named = pathTemplate.split('/').filter((part) => part && !part.startsWith('{') && !/^v\d+$/i.test(part));
43
+ const last = named[named.length - 1] || 'resource';
44
+ const prev = named[named.length - 2];
45
+ const action = /^(validate|approve|reject|sync|search|export|import|lock|unlock)$/i.test(last);
46
+ return (0, test_title_1.titleCaseToken)(action && prev ? prev : last).toLowerCase();
47
+ }
48
+ /**
49
+ * Deterministic it() suggestions: `{outcome} when {condition}`.
50
+ */
51
+ function suggestItCases(section, method, pathTemplate) {
52
+ const res = resourcePhrase(pathTemplate);
53
+ const m = (method || 'get').toLowerCase();
54
+ const hasParam = Boolean(pathTemplate?.split('/').some((part) => part.startsWith('{')));
55
+ const out = [];
56
+ const add = (value) => {
57
+ const next = value.replace(/\s+/g, ' ').trim();
58
+ if (next && !out.includes(next))
59
+ out.push(next);
60
+ };
61
+ if (section === 'auth') {
62
+ add('rejects when unauthorized');
63
+ add('rejects when authorization is missing');
64
+ return out;
65
+ }
66
+ if (section === 'invalid') {
67
+ add('rejects when payload is invalid');
68
+ add(`rejects when ${res} payload is invalid`);
69
+ return out;
70
+ }
71
+ if (section === 'omitted') {
72
+ add('rejects when a required field is omitted');
73
+ add(`rejects when ${res} field is omitted`);
74
+ return out;
75
+ }
76
+ if (section === 'semantic') {
77
+ add(`rejects when ${res} already exists`);
78
+ add(`rejects when ${res} is not found`);
79
+ return out;
80
+ }
81
+ // positive / unknown
82
+ if (m === 'post')
83
+ add(`creates ${res} when payload is valid`);
84
+ else if (m === 'delete')
85
+ add(`deletes ${res} when it exists`);
86
+ else if (m === 'put' || m === 'patch' || m === 'update')
87
+ add(`updates ${res} when payload is valid`);
88
+ else if (m === 'get' && hasParam)
89
+ add(`returns ${res} when found by id`);
90
+ else if (m === 'get')
91
+ add(`returns ${res} list when query is valid`);
92
+ else
93
+ add(`returns ${res} when request is valid`);
94
+ add(`returns ${res} when payload is valid`);
95
+ return out.slice(0, 3);
96
+ }
@@ -0,0 +1,19 @@
1
+ export type ParsedOperationLabel = {
2
+ title?: string;
3
+ path: string;
4
+ method: string;
5
+ integration: boolean;
6
+ };
7
+ export declare function titleCaseToken(value: string): string;
8
+ export declare function isHumanOperationTitle(title: string | undefined): boolean;
9
+ /**
10
+ * Pull path / method / optional human title from a TEST_TITLE or Jest name.
11
+ * Section suffixes (POSITIVE CASES …) are ignored.
12
+ */
13
+ export declare function parseOperationLabel(raw?: string): ParsedOperationLabel | undefined;
14
+ export declare function formatTestTitle(title: string, pathTemplate: string, method: string): string;
15
+ /**
16
+ * Deterministic title suggestions from HTTP method + path (no AI).
17
+ * POST /v1/admin/mock-tbs → ["Create Mock Tbs", "Create Admin Mock Tbs"]
18
+ */
19
+ export declare function suggestOperationTitles(method: string, pathTemplate: string): string[];
@@ -0,0 +1,138 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.titleCaseToken = titleCaseToken;
4
+ exports.isHumanOperationTitle = isHumanOperationTitle;
5
+ exports.parseOperationLabel = parseOperationLabel;
6
+ exports.formatTestTitle = formatTestTitle;
7
+ exports.suggestOperationTitles = suggestOperationTitles;
8
+ const METHODS = 'GET|POST|PUT|PATCH|DELETE|UPDATE|UPSERT';
9
+ const PATH_ONLY_RE = new RegExp(`^(?<path>\\/\\S+)\\s+\\[(?<method>${METHODS})\\](?:\\s+\\(integration\\))?\\s*$`, 'i');
10
+ const WITH_TITLE_RE = new RegExp(`^(?<title>.+?)\\s+(?<path>\\/\\S+)\\s+\\[(?<method>${METHODS})\\](?:\\s+\\(integration\\))?\\s*$`, 'i');
11
+ const ROLE_WORDS = new Set([
12
+ 'admin',
13
+ 'user',
14
+ 'users',
15
+ 'public',
16
+ 'internal',
17
+ 'partner',
18
+ 'staff',
19
+ 'customer',
20
+ 'vendor',
21
+ 'merchant',
22
+ 'operator',
23
+ 'system',
24
+ 'superadmin',
25
+ ]);
26
+ const ACTION_WORDS = new Set([
27
+ 'validate',
28
+ 'approve',
29
+ 'reject',
30
+ 'sync',
31
+ 'search',
32
+ 'export',
33
+ 'import',
34
+ 'login',
35
+ 'logout',
36
+ 'preview',
37
+ 'lock',
38
+ 'unlock',
39
+ 'publish',
40
+ 'archive',
41
+ 'restore',
42
+ 'verify',
43
+ 'confirm',
44
+ 'activate',
45
+ 'deactivate',
46
+ ]);
47
+ function titleCaseToken(value) {
48
+ return value
49
+ .replace(/[{}]/g, '')
50
+ .split(/[-_]/g)
51
+ .filter(Boolean)
52
+ .map((part) => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase())
53
+ .join(' ');
54
+ }
55
+ function isHumanOperationTitle(title) {
56
+ const value = title?.trim() ?? '';
57
+ if (value.length < 2 || value.length > 80)
58
+ return false;
59
+ if (value.startsWith('/'))
60
+ return false;
61
+ if (!/[a-zA-Z]/.test(value))
62
+ return false;
63
+ return true;
64
+ }
65
+ /**
66
+ * Pull path / method / optional human title from a TEST_TITLE or Jest name.
67
+ * Section suffixes (POSITIVE CASES …) are ignored.
68
+ */
69
+ function parseOperationLabel(raw) {
70
+ if (!raw)
71
+ return undefined;
72
+ const cut = raw
73
+ .replace(/\s+(POSITIVE CASES|SEMANTIC ERROR CASES(?:\s*-\s*AUTH)?|INVALID CASES|OMITTED(?: FIELD)? CASES)\b[\s\S]*$/i, '')
74
+ .trim();
75
+ const integration = /\(integration\)/i.test(cut);
76
+ const pathOnly = cut.match(PATH_ONLY_RE);
77
+ if (pathOnly?.groups?.path && pathOnly.groups.method) {
78
+ return { path: pathOnly.groups.path, method: pathOnly.groups.method.toUpperCase(), integration };
79
+ }
80
+ const withTitle = cut.match(WITH_TITLE_RE);
81
+ if (!withTitle?.groups?.path || !withTitle.groups.method)
82
+ return undefined;
83
+ const title = withTitle.groups.title?.trim();
84
+ return {
85
+ title: isHumanOperationTitle(title) ? title : undefined,
86
+ path: withTitle.groups.path,
87
+ method: withTitle.groups.method.toUpperCase(),
88
+ integration,
89
+ };
90
+ }
91
+ function formatTestTitle(title, pathTemplate, method) {
92
+ const clean = title.trim().replace(/\s+/g, ' ');
93
+ return `${clean} ${pathTemplate} [${method.toUpperCase()}] (integration)`;
94
+ }
95
+ function verbFor(method, pathTemplate, actionLabel) {
96
+ if (actionLabel)
97
+ return actionLabel;
98
+ const hasParam = pathTemplate.split('/').some((part) => part.startsWith('{'));
99
+ const m = method.toLowerCase();
100
+ if (m === 'get')
101
+ return hasParam ? 'Find One' : 'Find All';
102
+ if (m === 'post')
103
+ return 'Create';
104
+ if (m === 'delete')
105
+ return 'Delete';
106
+ if (m === 'put' || m === 'patch' || m === 'update')
107
+ return 'Update';
108
+ if (m === 'upsert')
109
+ return 'Upsert';
110
+ return titleCaseToken(m);
111
+ }
112
+ /**
113
+ * Deterministic title suggestions from HTTP method + path (no AI).
114
+ * POST /v1/admin/mock-tbs → ["Create Mock Tbs", "Create Admin Mock Tbs"]
115
+ */
116
+ function suggestOperationTitles(method, pathTemplate) {
117
+ const parts = pathTemplate.split('/').filter(Boolean);
118
+ const named = parts.filter((part) => !part.startsWith('{') && !/^v\d+$/i.test(part));
119
+ const last = named[named.length - 1] || 'resource';
120
+ const prev = named[named.length - 2];
121
+ const lastIsAction = ACTION_WORDS.has(last.toLowerCase());
122
+ const resource = titleCaseToken(lastIsAction && prev ? prev : last);
123
+ const actionLabel = lastIsAction ? titleCaseToken(last) : null;
124
+ const role = named.find((part) => ROLE_WORDS.has(part.toLowerCase()));
125
+ const verb = verbFor(method, pathTemplate, actionLabel);
126
+ const out = [];
127
+ const add = (value) => {
128
+ const next = value.replace(/\s+/g, ' ').trim();
129
+ if (next && !out.includes(next))
130
+ out.push(next);
131
+ };
132
+ add(`${verb} ${resource}`);
133
+ if (role)
134
+ add(`${verb} ${titleCaseToken(role)} ${resource}`);
135
+ if (actionLabel && verb !== actionLabel)
136
+ add(`${actionLabel} ${resource}`);
137
+ return out.slice(0, 3);
138
+ }
package/dist/cli/main.js CHANGED
@@ -9,6 +9,7 @@ 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 titles_1 = require("./titles");
12
13
  const uninstall_1 = require("./uninstall");
13
14
  function usage() {
14
15
  console.log(`DAxTA CLI (@t0.labs/daxta)
@@ -18,7 +19,8 @@ Usage:
18
19
  daxta init (alias of install)
19
20
  daxta uninstall [--yes] [--dry-run] [--keep-dep] [--fast]
20
21
  daxta migrate [--yes] (force upgrade + sidebar prompts)
21
- daxta test [--script <name>] [--config <jest.json>] [--serve] [--port <n>] [--yes]
22
+ daxta titles [--check] [--strict]
23
+ daxta test [--script <name>] [--config <jest.json>] [--serve] [--port <n>] [--yes] [--strict]
22
24
  daxta build
23
25
  daxta serve [--port <n>]
24
26
  daxta tree [PATH] [--layout resource-first|url-order]
@@ -34,6 +36,7 @@ Remove completely:
34
36
  pnpm dlx @t0.labs/daxta uninstall
35
37
  npx @t0.labs/daxta uninstall
36
38
 
39
+ daxta titles = check TEST_TITLE + it() format before tests; suggests names from method/path/section
37
40
  daxta test = forwards to your package script (Jest stays parent; DAxTA is a plugin)
38
41
  daxta tree = choose how paths appear in the /docs sidebar
39
42
  `);
@@ -110,6 +113,16 @@ async function main() {
110
113
  (0, migrate_1.reportMigration)((0, migrate_1.migrateProject)(process.cwd(), { force: true }));
111
114
  return;
112
115
  }
116
+ if (command === 'titles' || command === 'title') {
117
+ const code = await (0, titles_1.runTitleCheck)({
118
+ checkOnly: Boolean(flags.check),
119
+ yes: Boolean(flags.yes),
120
+ strict: Boolean(flags.strict),
121
+ });
122
+ if (code)
123
+ process.exitCode = code;
124
+ return;
125
+ }
113
126
  if (command === 'test') {
114
127
  const argv = rest[0] === '--' ? rest.slice(1) : rest;
115
128
  await (0, test_1.runDaxtaTest)({ argv });
package/dist/cli/test.js CHANGED
@@ -39,6 +39,7 @@ const path = __importStar(require("path"));
39
39
  const child_process_1 = require("child_process");
40
40
  const config_1 = require("../config");
41
41
  const discover_test_1 = require("./discover-test");
42
+ const titles_1 = require("./titles");
42
43
  const ui_1 = require("./ui");
43
44
  function readPkg(cwd) {
44
45
  return JSON.parse((0, fs_1.readFileSync)(path.join(cwd, 'package.json'), 'utf8'));
@@ -62,11 +63,14 @@ async function runDaxtaTest(options = {}) {
62
63
  const config = (0, config_1.getConfig)(true);
63
64
  const passthrough = [];
64
65
  let yes = false;
66
+ let strict = false;
65
67
  let scriptFlag;
66
68
  for (let i = 0; i < (options.argv ?? []).length; i += 1) {
67
69
  const token = (options.argv ?? [])[i];
68
70
  if (token === '--yes' || token === '-y')
69
71
  yes = true;
72
+ else if (token === '--strict')
73
+ strict = true;
70
74
  else if (token === '--script')
71
75
  scriptFlag = (options.argv ?? [])[++i];
72
76
  else if (token === '--')
@@ -91,6 +95,11 @@ async function runDaxtaTest(options = {}) {
91
95
  process.exitCode = 1;
92
96
  return;
93
97
  }
98
+ const titleExit = await (0, titles_1.runTitleCheck)({ cwd, checkOnly: true, yes: true, strict });
99
+ if (titleExit !== 0) {
100
+ process.exitCode = titleExit;
101
+ return;
102
+ }
94
103
  console.log(`${ui_1.c.dim('DAxTA')} forwarding to ${ui_1.c.cyan(`${pm} run ${scriptName}`)} ${ui_1.c.dim('(Jest stays parent)')}`);
95
104
  const args = pm === 'npm' ? ['run', scriptName, '--', ...passthrough] : ['run', scriptName, ...passthrough];
96
105
  const result = (0, child_process_1.spawnSync)(pm, args, {
@@ -0,0 +1,6 @@
1
+ export declare function runTitleCheck(options: {
2
+ cwd?: string;
3
+ checkOnly?: boolean;
4
+ yes?: boolean;
5
+ strict?: boolean;
6
+ }): Promise<number>;
@@ -0,0 +1,105 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.runTitleCheck = runTitleCheck;
4
+ const readline_1 = require("readline");
5
+ const test_title_1 = require("../catalog/test-title");
6
+ const it_case_1 = require("../catalog/it-case");
7
+ const scan_1 = require("../titles/scan");
8
+ const ui_1 = require("./ui");
9
+ function prompt(question) {
10
+ const rl = (0, readline_1.createInterface)({ input: process.stdin, output: process.stdout });
11
+ return new Promise((resolve) => {
12
+ rl.question(question, (answer) => {
13
+ rl.close();
14
+ resolve(answer.trim());
15
+ });
16
+ });
17
+ }
18
+ async function pickFromSuggestions(finding, extra, validate) {
19
+ const suggestions = finding.suggestions;
20
+ console.log('');
21
+ console.log(` ${ui_1.c.cyan(finding.file)}${ui_1.c.dim(`:${finding.line}:${finding.column}`)}`);
22
+ console.log(` ${ui_1.c.dim(finding.raw)}`);
23
+ if (extra)
24
+ console.log(` ${ui_1.c.dim(extra)}`);
25
+ suggestions.forEach((name, index) => {
26
+ const mark = index === 0 ? ui_1.c.dim(' (recommended)') : '';
27
+ console.log(` ${ui_1.c.cyan(String(index + 1))} ${name}${mark}`);
28
+ });
29
+ console.log(` ${ui_1.c.cyan('s')} skip`);
30
+ console.log(` ${ui_1.c.cyan('c')} custom`);
31
+ const answer = await prompt(` ${ui_1.c.cyan('›')} `);
32
+ if (!answer || answer.toLowerCase() === 's')
33
+ return 'skip';
34
+ if (answer.toLowerCase() === 'c') {
35
+ const custom = await prompt(` ${ui_1.c.dim('text')} ${ui_1.c.cyan('›')} `);
36
+ if (!validate(custom)) {
37
+ console.log(` ${ui_1.c.yellow('!')} does not match the format — skipped`);
38
+ return 'skip';
39
+ }
40
+ return custom;
41
+ }
42
+ const index = Number(answer);
43
+ if (Number.isInteger(index) && index >= 1 && index <= suggestions.length)
44
+ return suggestions[index - 1];
45
+ if (validate(answer))
46
+ return answer;
47
+ return 'skip';
48
+ }
49
+ async function runTitleCheck(options) {
50
+ const cwd = options.cwd ?? process.cwd();
51
+ const report = (0, scan_1.scanTestNaming)(cwd);
52
+ const total = report.titles.length + report.cases.length;
53
+ if (!total) {
54
+ if (!options.checkOnly) {
55
+ (0, ui_1.banner)('Test naming', 'titles + it() cases');
56
+ console.log(` ${ui_1.c.green('✔')} nothing to fix`);
57
+ console.log('');
58
+ }
59
+ return 0;
60
+ }
61
+ if (options.checkOnly || options.yes || !process.stdin.isTTY) {
62
+ (0, scan_1.printNamingFindings)(report, ui_1.c);
63
+ return options.strict ? 1 : 0;
64
+ }
65
+ (0, ui_1.banner)('Test naming', 'runs before Jest — docs / Postman labels');
66
+ console.log(` ${ui_1.c.dim('Title')} Create Mock Tbs /v1/admin/mock-tbs [POST] (integration)`);
67
+ console.log(` ${ui_1.c.dim('it()')} creates mock tbs when payload is valid`);
68
+ console.log(` ${ui_1.c.yellow(String(total))} to review — pick a suggestion, custom, or skip.`);
69
+ let written = 0;
70
+ let skipped = 0;
71
+ for (const finding of report.titles) {
72
+ const choice = await pickFromSuggestions(finding, `docs would show ${finding.path}`, test_title_1.isHumanOperationTitle);
73
+ if (!choice || choice === 'skip') {
74
+ skipped += 1;
75
+ continue;
76
+ }
77
+ if ((0, scan_1.applyTitle)(cwd, finding, choice)) {
78
+ console.log(` ${ui_1.c.green('✔')} ${choice}`);
79
+ written += 1;
80
+ }
81
+ else {
82
+ console.log(` ${ui_1.c.yellow('!')} could not rewrite that line — skipped`);
83
+ skipped += 1;
84
+ }
85
+ }
86
+ for (const finding of report.cases) {
87
+ const choice = await pickFromSuggestions(finding, finding.section ? `section ${finding.section}` : 'it() example name', it_case_1.isValidItCase);
88
+ if (!choice || choice === 'skip') {
89
+ skipped += 1;
90
+ continue;
91
+ }
92
+ if ((0, scan_1.applyItCase)(cwd, finding, choice)) {
93
+ console.log(` ${ui_1.c.green('✔')} ${choice}`);
94
+ written += 1;
95
+ }
96
+ else {
97
+ console.log(` ${ui_1.c.yellow('!')} could not rewrite that line — skipped`);
98
+ skipped += 1;
99
+ }
100
+ }
101
+ console.log('');
102
+ console.log(` ${ui_1.c.green('✔')} ${written} updated ${ui_1.c.dim(`${skipped} skipped`)}`);
103
+ console.log('');
104
+ return options.strict && skipped > 0 ? 1 : 0;
105
+ }
package/dist/index.d.ts CHANGED
@@ -6,5 +6,5 @@ export { dtoRequired, type FieldLocation } from './fields/dto-fields';
6
6
  export { buildFieldsFile, writeFieldsFile, readFieldsFile, type FieldsFile } from './fields/export-fields';
7
7
  export { apiDocs, apiDocsHandler, serveApiDocs, getDocsBasePath, getHtmlPath, getOutDir, getSpecJsonPath, type ApiDocsHandler, type ApiDocsOptions, } from './serve';
8
8
  export { runInteractiveCall, runFileCall, executeCall, type CallValues } from './call';
9
- export type { FieldDoc, OperationDoc } from './catalog';
9
+ export { apiTitle, parseOperationLabel, suggestOperationTitles, formatTestTitle, isValidItCase, suggestItCases, type FieldDoc, type OperationDoc, } from './catalog';
10
10
  export { installDaxta, type InstallOptions } from './cli/install';
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
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.normalizeTreeLayout = exports.resolveConfig = exports.getConfig = exports.defineConfig = void 0;
3
+ exports.installDaxta = exports.suggestItCases = exports.isValidItCase = exports.formatTestTitle = exports.suggestOperationTitles = exports.parseOperationLabel = exports.apiTitle = 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; } });
@@ -38,5 +38,12 @@ var call_1 = require("./call");
38
38
  Object.defineProperty(exports, "runInteractiveCall", { enumerable: true, get: function () { return call_1.runInteractiveCall; } });
39
39
  Object.defineProperty(exports, "runFileCall", { enumerable: true, get: function () { return call_1.runFileCall; } });
40
40
  Object.defineProperty(exports, "executeCall", { enumerable: true, get: function () { return call_1.executeCall; } });
41
+ var catalog_1 = require("./catalog");
42
+ Object.defineProperty(exports, "apiTitle", { enumerable: true, get: function () { return catalog_1.apiTitle; } });
43
+ Object.defineProperty(exports, "parseOperationLabel", { enumerable: true, get: function () { return catalog_1.parseOperationLabel; } });
44
+ Object.defineProperty(exports, "suggestOperationTitles", { enumerable: true, get: function () { return catalog_1.suggestOperationTitles; } });
45
+ Object.defineProperty(exports, "formatTestTitle", { enumerable: true, get: function () { return catalog_1.formatTestTitle; } });
46
+ Object.defineProperty(exports, "isValidItCase", { enumerable: true, get: function () { return catalog_1.isValidItCase; } });
47
+ Object.defineProperty(exports, "suggestItCases", { enumerable: true, get: function () { return catalog_1.suggestItCases; } });
41
48
  var install_1 = require("./cli/install");
42
49
  Object.defineProperty(exports, "installDaxta", { enumerable: true, get: function () { return install_1.installDaxta; } });
@@ -2,6 +2,25 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.default = daxtaGlobalSetup;
4
4
  const recorder_1 = require("../recorder");
5
+ const scan_1 = require("../titles/scan");
6
+ const ui_1 = require("../cli/ui");
5
7
  async function daxtaGlobalSetup() {
6
8
  (0, recorder_1.clearWorkerHits)();
9
+ try {
10
+ const strict = process.env.DAXTA_TITLE_CHECK === 'strict';
11
+ const off = process.env.DAXTA_TITLE_CHECK === 'off';
12
+ if (off)
13
+ return;
14
+ const report = (0, scan_1.scanTestNaming)(process.cwd());
15
+ if (!report.titles.length && !report.cases.length)
16
+ return;
17
+ (0, scan_1.printNamingFindings)(report, ui_1.c);
18
+ if (strict) {
19
+ throw new Error('DAxTA: test naming off format. Run `daxta titles` or set DAXTA_TITLE_CHECK=off.');
20
+ }
21
+ }
22
+ catch (error) {
23
+ if (process.env.DAXTA_TITLE_CHECK === 'strict')
24
+ throw error;
25
+ }
7
26
  }
@@ -0,0 +1,43 @@
1
+ import { type CaseSection } from '../catalog/it-case';
2
+ export type TitleFinding = {
3
+ file: string;
4
+ line: number;
5
+ column: number;
6
+ raw: string;
7
+ quote: string;
8
+ path: string;
9
+ method: string;
10
+ suggestions: string[];
11
+ };
12
+ export declare function scanMissingTitles(cwd?: string): TitleFinding[];
13
+ export declare function applyTitle(cwd: string, finding: TitleFinding, title: string): boolean;
14
+ export declare function printTitleFindings(findings: TitleFinding[], paint: {
15
+ dim: (s: string) => string;
16
+ yellow: (s: string) => string;
17
+ cyan: (s: string) => string;
18
+ bold: (s: string) => string;
19
+ }): void;
20
+ export type ItFinding = {
21
+ file: string;
22
+ line: number;
23
+ column: number;
24
+ raw: string;
25
+ quote: string;
26
+ section?: CaseSection;
27
+ path?: string;
28
+ method?: string;
29
+ suggestions: string[];
30
+ };
31
+ export type NamingReport = {
32
+ titles: TitleFinding[];
33
+ cases: ItFinding[];
34
+ };
35
+ export declare function scanMissingItCases(cwd?: string): ItFinding[];
36
+ export declare function scanTestNaming(cwd?: string): NamingReport;
37
+ export declare function applyItCase(cwd: string, finding: ItFinding, name: string): boolean;
38
+ export declare function printNamingFindings(report: NamingReport, paint: {
39
+ dim: (s: string) => string;
40
+ yellow: (s: string) => string;
41
+ cyan: (s: string) => string;
42
+ bold: (s: string) => string;
43
+ }): void;
@@ -0,0 +1,288 @@
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.scanMissingTitles = scanMissingTitles;
37
+ exports.applyTitle = applyTitle;
38
+ exports.printTitleFindings = printTitleFindings;
39
+ exports.scanMissingItCases = scanMissingItCases;
40
+ exports.scanTestNaming = scanTestNaming;
41
+ exports.applyItCase = applyItCase;
42
+ exports.printNamingFindings = printNamingFindings;
43
+ const fs_1 = require("fs");
44
+ const path = __importStar(require("path"));
45
+ const test_title_1 = require("../catalog/test-title");
46
+ const it_case_1 = require("../catalog/it-case");
47
+ const SKIP_DIRS = new Set([
48
+ 'node_modules',
49
+ 'dist',
50
+ 'build',
51
+ 'coverage',
52
+ '.git',
53
+ '.next',
54
+ 'daxta',
55
+ 'out',
56
+ ]);
57
+ const TEST_FILE_RE = /\.(spec|test|e2e|int)\.(ts|js|mts|cts|tsx|jsx)$/i;
58
+ const TEST_DIR_RE = /(^|\/)(test|tests|e2e|integration)(\/|$)/i;
59
+ const SOURCE_RE = /\.(ts|js|mts|cts|tsx|jsx)$/i;
60
+ const STRING_RE = /(['"`])((?:\\.|(?!\1)[\s\S])*?)\1/g;
61
+ function shouldScanFile(rel) {
62
+ if (TEST_FILE_RE.test(rel))
63
+ return true;
64
+ return TEST_DIR_RE.test(rel.replace(/\\/g, '/')) && SOURCE_RE.test(rel);
65
+ }
66
+ function walk(dir, cwd, out) {
67
+ if (!(0, fs_1.existsSync)(dir))
68
+ return;
69
+ let entries = [];
70
+ try {
71
+ entries = (0, fs_1.readdirSync)(dir);
72
+ }
73
+ catch {
74
+ return;
75
+ }
76
+ for (const name of entries) {
77
+ if (name.startsWith('.') && name !== '.ts')
78
+ continue;
79
+ const full = path.join(dir, name);
80
+ let stat;
81
+ try {
82
+ stat = (0, fs_1.statSync)(full);
83
+ }
84
+ catch {
85
+ continue;
86
+ }
87
+ const rel = path.relative(cwd, full);
88
+ if (stat.isDirectory()) {
89
+ if (SKIP_DIRS.has(name))
90
+ continue;
91
+ walk(full, cwd, out);
92
+ continue;
93
+ }
94
+ if (stat.isFile() && shouldScanFile(rel))
95
+ out.push(full);
96
+ }
97
+ }
98
+ function listTestFiles(cwd) {
99
+ const roots = ['test', 'tests', 'e2e', 'src'];
100
+ const files = [];
101
+ for (const root of roots) {
102
+ const dir = path.join(cwd, root);
103
+ if ((0, fs_1.existsSync)(dir))
104
+ walk(dir, cwd, files);
105
+ }
106
+ return [...new Set(files)];
107
+ }
108
+ function scanMissingTitles(cwd = process.cwd()) {
109
+ const findings = [];
110
+ for (const file of listTestFiles(cwd)) {
111
+ let text = '';
112
+ try {
113
+ text = (0, fs_1.readFileSync)(file, 'utf8');
114
+ }
115
+ catch {
116
+ continue;
117
+ }
118
+ const rel = path.relative(cwd, file) || file;
119
+ const lines = text.split(/\n/);
120
+ lines.forEach((line, index) => {
121
+ STRING_RE.lastIndex = 0;
122
+ let match;
123
+ while ((match = STRING_RE.exec(line))) {
124
+ const quote = match[1];
125
+ const body = match[2];
126
+ const parsed = (0, test_title_1.parseOperationLabel)(body);
127
+ if (!parsed || parsed.title)
128
+ continue;
129
+ findings.push({
130
+ file: rel,
131
+ line: index + 1,
132
+ column: (match.index ?? 0) + 1,
133
+ raw: body,
134
+ quote,
135
+ path: parsed.path,
136
+ method: parsed.method,
137
+ suggestions: (0, test_title_1.suggestOperationTitles)(parsed.method, parsed.path),
138
+ });
139
+ }
140
+ });
141
+ }
142
+ return findings;
143
+ }
144
+ function applyTitle(cwd, finding, title) {
145
+ const abs = path.isAbsolute(finding.file) ? finding.file : path.join(cwd, finding.file);
146
+ if (!(0, fs_1.existsSync)(abs))
147
+ return false;
148
+ const text = (0, fs_1.readFileSync)(abs, 'utf8');
149
+ const lines = text.split(/\n/);
150
+ const line = lines[finding.line - 1];
151
+ if (!line)
152
+ return false;
153
+ const nextLabel = (0, test_title_1.formatTestTitle)(title, finding.path, finding.method);
154
+ const needle = `${finding.quote}${finding.raw}${finding.quote}`;
155
+ const replacement = `${finding.quote}${nextLabel}${finding.quote}`;
156
+ if (!line.includes(needle))
157
+ return false;
158
+ lines[finding.line - 1] = line.replace(needle, replacement);
159
+ (0, fs_1.writeFileSync)(abs, lines.join('\n'));
160
+ finding.raw = nextLabel;
161
+ return true;
162
+ }
163
+ function printTitleFindings(findings, paint) {
164
+ if (!findings.length)
165
+ return;
166
+ console.log('');
167
+ console.log(` ${paint.yellow('!')} ${paint.bold(`${findings.length} test title(s) missing a human name`)} ${paint.dim('(docs would show the path)')}`);
168
+ console.log(` ${paint.dim('Format:')} ${paint.cyan('Create Mock Tbs /v1/admin/mock-tbs [POST] (integration)')}`);
169
+ for (const item of findings) {
170
+ console.log('');
171
+ console.log(` ${paint.cyan(item.file)}${paint.dim(`:${item.line}:${item.column}`)}`);
172
+ console.log(` ${paint.dim(item.raw)}`);
173
+ if (item.suggestions.length) {
174
+ console.log(` ${paint.dim('suggest')} ${item.suggestions.map((name, i) => `${i + 1}:${name}`).join(' ')}`);
175
+ }
176
+ }
177
+ console.log('');
178
+ console.log(` ${paint.dim('Fix interactively:')} ${paint.cyan('daxta titles')}`);
179
+ console.log('');
180
+ }
181
+ function indexToLineCol(text, index) {
182
+ const until = text.slice(0, index);
183
+ const lines = until.split(/\n/);
184
+ return { line: lines.length, column: (lines[lines.length - 1]?.length ?? 0) + 1 };
185
+ }
186
+ const BLOCK_RE = /\b((?:describe|it|test)(?:\.(?:only|skip|todo))?)\s*\(\s*(['"`])((?:\\.|(?!\2)[\s\S])*?)\2/g;
187
+ function scanFileCases(rel, text) {
188
+ const labels = [];
189
+ STRING_RE.lastIndex = 0;
190
+ let strMatch;
191
+ while ((strMatch = STRING_RE.exec(text))) {
192
+ const parsed = (0, test_title_1.parseOperationLabel)(strMatch[2]);
193
+ if (!parsed)
194
+ continue;
195
+ labels.push({ index: strMatch.index, path: parsed.path, method: parsed.method });
196
+ }
197
+ const describes = [];
198
+ const findings = [];
199
+ BLOCK_RE.lastIndex = 0;
200
+ let block;
201
+ while ((block = BLOCK_RE.exec(text))) {
202
+ const kind = block[1].replace(/\.(?:only|skip|todo)$/, '');
203
+ const quote = block[2];
204
+ const body = block[3];
205
+ const index = block.index;
206
+ if (kind === 'describe') {
207
+ describes.push({ index, section: (0, it_case_1.parseCaseSection)(body) });
208
+ continue;
209
+ }
210
+ const section = [...describes].reverse().find((entry) => entry.index < index && entry.section)?.section;
211
+ if (!section)
212
+ continue;
213
+ if ((0, it_case_1.isValidItCase)(body))
214
+ continue;
215
+ const label = [...labels].reverse().find((entry) => entry.index < index);
216
+ const { line, column } = indexToLineCol(text, index);
217
+ findings.push({
218
+ file: rel,
219
+ line,
220
+ column,
221
+ raw: body,
222
+ quote,
223
+ section,
224
+ path: label?.path,
225
+ method: label?.method,
226
+ suggestions: (0, it_case_1.suggestItCases)(section, label?.method, label?.path),
227
+ });
228
+ }
229
+ return findings;
230
+ }
231
+ function scanMissingItCases(cwd = process.cwd()) {
232
+ const findings = [];
233
+ for (const file of listTestFiles(cwd)) {
234
+ let text = '';
235
+ try {
236
+ text = (0, fs_1.readFileSync)(file, 'utf8');
237
+ }
238
+ catch {
239
+ continue;
240
+ }
241
+ const rel = path.relative(cwd, file) || file;
242
+ findings.push(...scanFileCases(rel, text));
243
+ }
244
+ return findings;
245
+ }
246
+ function scanTestNaming(cwd = process.cwd()) {
247
+ return { titles: scanMissingTitles(cwd), cases: scanMissingItCases(cwd) };
248
+ }
249
+ function applyItCase(cwd, finding, name) {
250
+ const abs = path.isAbsolute(finding.file) ? finding.file : path.join(cwd, finding.file);
251
+ if (!(0, fs_1.existsSync)(abs))
252
+ return false;
253
+ const text = (0, fs_1.readFileSync)(abs, 'utf8');
254
+ const lines = text.split(/\n/);
255
+ const line = lines[finding.line - 1];
256
+ if (!line)
257
+ return false;
258
+ const needle = `${finding.quote}${finding.raw}${finding.quote}`;
259
+ const replacement = `${finding.quote}${name}${finding.quote}`;
260
+ if (!line.includes(needle))
261
+ return false;
262
+ lines[finding.line - 1] = line.replace(needle, replacement);
263
+ (0, fs_1.writeFileSync)(abs, lines.join('\n'));
264
+ finding.raw = name;
265
+ return true;
266
+ }
267
+ function printNamingFindings(report, paint) {
268
+ printTitleFindings(report.titles, paint);
269
+ if (!report.cases.length)
270
+ return;
271
+ if (report.titles.length) {
272
+ // spacer already from titles
273
+ }
274
+ console.log('');
275
+ console.log(` ${paint.yellow('!')} ${paint.bold(`${report.cases.length} it() case(s) off format`)} ${paint.dim('{outcome} when {condition}')}`);
276
+ console.log(` ${paint.dim('Format:')} ${paint.cyan('creates mock tbs when payload is valid')}`);
277
+ for (const item of report.cases) {
278
+ console.log('');
279
+ console.log(` ${paint.cyan(item.file)}${paint.dim(`:${item.line}:${item.column}`)}`);
280
+ console.log(` ${paint.dim(item.raw)}`);
281
+ if (item.suggestions.length) {
282
+ console.log(` ${paint.dim('suggest')} ${item.suggestions.map((name, i) => `${i + 1}:${name}`).join(' ')}`);
283
+ }
284
+ }
285
+ console.log('');
286
+ console.log(` ${paint.dim('Fix interactively:')} ${paint.cyan('daxta titles')}`);
287
+ console.log('');
288
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@t0.labs/daxta",
3
- "version": "0.4.13",
3
+ "version": "0.4.15",
4
4
  "description": "DAxTA \u2014 docs from Nest integration traffic + DTO field CLI / Try-it",
5
5
  "license": "MIT",
6
6
  "repository": {