@t0.labs/daxta 0.4.14 → 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
@@ -166,6 +166,29 @@ Example label (`status-title-case`):
166
166
 
167
167
  Then `daxta build` to refresh `/docs` and export.
168
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
+
169
192
 
170
193
 
171
194
  ## API
@@ -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.14",
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": {