@t0.labs/daxta 0.3.2 → 0.3.4

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
@@ -10,49 +10,35 @@ pnpm dlx @t0.labs/daxta install
10
10
  npx @t0.labs/daxta install
11
11
  ```
12
12
 
13
- Adds the package as a devDependency **and** wires the project (config, scripts, `apiDocs(app)` into `main.ts`).
14
-
15
- Flags: `--yes`, `--main src/main.ts`, `--skip-main`, `--dry-run`, `--skip-dep`, `--fast` (skip step delays)
16
-
13
+ Install attaches DAxTA as a **Jest plugin** (setup + reporter) on your existing jest config.
14
+ Your `test:integration` (or whatever you pick) stays the entrypoint — DAxTA does **not** wrap the process.
17
15
 
18
16
  ```ts
19
17
  import { apiDocs } from '@t0.labs/daxta';
20
-
21
- const app = await NestFactory.create(AppModule);
22
- apiDocs(app);
18
+ apiDocs(app); // needs DAXTA_DOCS
23
19
  ```
24
20
 
25
21
  ## Required env
26
22
 
27
- `apiDocs(app)` **throws** if `DAXTA_DOCS` is missing:
28
-
29
23
  ```bash
30
- DAXTA_DOCS=true # enable /docs
31
- DAXTA_DOCS=false # disable (must be set explicitly)
24
+ DAXTA_DOCS=true # enable /docs on the app port
25
+ DAXTA_DOCS=false # disable (must be set)
32
26
  ```
33
27
 
34
- ## Runtime CLI
28
+ ## Usage
35
29
 
36
30
  ```bash
37
- daxta test # run tests → build (docs on app /docs)
38
- daxta test --serve # also open standalone viewer
39
- daxta test --script test:integration
40
- daxta serve # standalone only
41
- daxta build
42
- daxta fields
43
- daxta call
31
+ pnpm run test:integration # your script — Docs ready prints when Jest finishes
32
+ daxta migrate # force upgrade after package bump
33
+ daxta serve # standalone viewer (optional)
44
34
  ```
45
35
 
46
- `daxta test` uses your wired script (`testScript` / `testCommand` in config). Recording is injected at runtime — no extra `daxta:*` scripts.
47
-
48
- On package upgrade, the next `daxta` command auto-migrates old config/scripts (`daxtaVersion` in `daxta.config.ts`).
49
-
50
36
  ## API
51
37
 
52
38
  ```ts
53
39
  import { apiDocs, apiDocsHandler, serveApiDocs } from '@t0.labs/daxta';
54
40
 
55
- apiDocs(app); // app /docs (needs DAXTA_DOCS)
56
- app.use(apiDocsHandler()); // raw handler
57
- serveApiDocs({ port: 5199 }); // standalone viewer
41
+ apiDocs(app);
42
+ app.use(apiDocsHandler());
43
+ serveApiDocs({ port: 5199 });
58
44
  ```
@@ -134,6 +134,22 @@ function slug(value, index) {
134
134
  .slice(0, 72);
135
135
  return base || `example-${index + 1}`;
136
136
  }
137
+ function valueFingerprint(value) {
138
+ try {
139
+ return JSON.stringify(value) ?? 'undefined';
140
+ }
141
+ catch {
142
+ return Object.prototype.toString.call(value);
143
+ }
144
+ }
145
+ /** Stable shared key so request + response examples from the same hit stay paired. */
146
+ function exampleKeyForHit(hit, index) {
147
+ const base = slug(exampleLabel(hit), index);
148
+ return `${base}-${index}`;
149
+ }
150
+ function putExample(store, key, summary, value) {
151
+ store[key] = { summary, value };
152
+ }
137
153
  function isPrimaryHit(hit) {
138
154
  if (!hit.test)
139
155
  return false;
@@ -144,15 +160,6 @@ function isPrimaryHit(hit) {
144
160
  return true;
145
161
  return methods.includes(hit.method);
146
162
  }
147
- function addUniqueExample(store, name, value) {
148
- const serialized = JSON.stringify(value);
149
- if (Object.values(store).some((example) => JSON.stringify(example.value) === serialized))
150
- return;
151
- let key = slug(name, Object.keys(store).length);
152
- if (store[key])
153
- key = `${key}-${Object.keys(store).length}`;
154
- store[key] = { summary: name, value };
155
- }
156
163
  function pathParamsFromHit(hit) {
157
164
  if (hit.pathParams && Object.keys(hit.pathParams).length)
158
165
  return hit.pathParams;
@@ -350,7 +357,16 @@ function sortScenarios(scenarios) {
350
357
  function dedupeScenarios(scenarios) {
351
358
  const seen = new Set();
352
359
  return scenarios.filter((scenario) => {
353
- const key = JSON.stringify([scenario.group, scenario.name, scenario.status, scenario.reqBody, scenario.query, scenario.pathParams]);
360
+ // Include resBody so a new response keeps its matching request as its own scenario.
361
+ const key = JSON.stringify([
362
+ scenario.group,
363
+ scenario.name,
364
+ scenario.status,
365
+ scenario.reqBody,
366
+ scenario.resBody,
367
+ scenario.query,
368
+ scenario.pathParams,
369
+ ]);
354
370
  if (seen.has(key))
355
371
  return false;
356
372
  seen.add(key);
@@ -440,14 +456,16 @@ function buildSpec(hits) {
440
456
  const parameters = buildParameters(pathTemplate, opHits);
441
457
  if (parameters.length)
442
458
  operation.parameters = parameters;
443
- for (const hit of opHits) {
459
+ for (let index = 0; index < opHits.length; index += 1) {
460
+ const hit = opHits[index];
444
461
  const label = exampleLabel(hit);
462
+ const exampleKey = exampleKeyForHit(hit, index);
445
463
  if (hit.reqBody !== undefined) {
446
464
  operation.requestBody ??= { required: method === 'post' || method === 'put', content: { 'application/json': { schema: inferSchema(hit.reqBody), examples: {} } } };
447
465
  const media = operation.requestBody.content['application/json'];
448
466
  media.schema = mergeSchema(media.schema, inferSchema(hit.reqBody));
449
467
  media.examples ??= {};
450
- addUniqueExample(media.examples, label, hit.reqBody);
468
+ putExample(media.examples, exampleKey, label, hit.reqBody);
451
469
  }
452
470
  const status = String(hit.status);
453
471
  operation.responses[status] ??= {
@@ -458,7 +476,7 @@ function buildSpec(hits) {
458
476
  const responseMedia = operation.responses[status].content['application/json'];
459
477
  responseMedia.schema = mergeSchema(responseMedia.schema, inferSchema(hit.resBody));
460
478
  responseMedia.examples ??= {};
461
- addUniqueExample(responseMedia.examples, label, hit.resBody);
479
+ putExample(responseMedia.examples, exampleKey, label, hit.resBody);
462
480
  }
463
481
  }
464
482
  operation['x-scenarios'] = sortScenarios(dedupeScenarios(opHits.map(toScenario)));
@@ -517,13 +535,16 @@ function scenarioSignature(scenario) {
517
535
  pathParamKeys: sortedKeys(scenario.pathParams),
518
536
  reqSchema: signatureSchema(scenario.reqBody),
519
537
  resSchema: signatureSchema(scenario.resBody),
538
+ // Value fingerprints so body content changes invalidate the cached operation.
539
+ reqValue: valueFingerprint(scenario.reqBody),
540
+ resValue: valueFingerprint(scenario.resBody),
520
541
  });
521
542
  }
522
- function exampleSummaries(operation) {
523
- const summaries = [];
543
+ function exampleFingerprints(operation) {
544
+ const fingerprints = [];
524
545
  const collect = (examples) => {
525
- for (const example of Object.values(examples ?? {})) {
526
- summaries.push(String(example?.summary ?? ''));
546
+ for (const [key, example] of Object.entries(examples ?? {})) {
547
+ fingerprints.push(`${key}:${example?.summary ?? ''}:${valueFingerprint(example?.value)}`);
527
548
  }
528
549
  };
529
550
  const requestBody = operation.requestBody;
@@ -532,7 +553,7 @@ function exampleSummaries(operation) {
532
553
  for (const response of Object.values(responses)) {
533
554
  collect(response?.content?.['application/json']?.examples);
534
555
  }
535
- return summaries.sort((left, right) => left.localeCompare(right));
556
+ return fingerprints.sort((left, right) => left.localeCompare(right));
536
557
  }
537
558
  function operationSignature(operation) {
538
559
  const scenarios = (operation['x-scenarios'] ?? []).map(scenarioSignature).sort((left, right) => left.localeCompare(right));
@@ -548,7 +569,7 @@ function operationSignature(operation) {
548
569
  security: operation.security,
549
570
  docs: operation['x-docs'],
550
571
  responseStatuses: Object.keys(operation.responses ?? {}).sort(),
551
- examples: exampleSummaries(operation),
572
+ examples: exampleFingerprints(operation),
552
573
  scenarios,
553
574
  });
554
575
  }
@@ -565,6 +586,8 @@ function hitSignature(hit) {
565
586
  pathParamKeys: sortedKeys(hit.pathParams),
566
587
  reqSchema: signatureSchema(hit.reqBody),
567
588
  resSchema: signatureSchema(hit.resBody),
589
+ reqValue: valueFingerprint(hit.reqBody),
590
+ resValue: valueFingerprint(hit.resBody),
568
591
  });
569
592
  }
570
593
  function hitsStructureSame(existing, fresh) {
@@ -18,16 +18,15 @@ export declare function resolveTestScript(options: {
18
18
  yes?: boolean;
19
19
  flag?: string;
20
20
  }): Promise<string | null>;
21
- /** Persist which script is wired + the original jest command (before wrap). */
21
+ /** Persist test wiring + optional jestConfig path */
22
22
  export declare function upsertTestWiringInConfig(cwd: string, wiring: {
23
23
  testScript: string;
24
24
  testCommand: string;
25
+ jestConfig?: string;
25
26
  }, dryRun?: boolean): string;
26
- /** @deprecated use upsertTestWiringInConfig */
27
- export declare function upsertTestScriptInConfig(cwd: string, testScript: string, dryRun?: boolean): string;
28
27
  /**
29
- * Point the user's script at `daxta test --yes` without adding new script keys.
30
- * Returns the original command that must be stored in config as `testCommand`.
28
+ * @deprecated wrapping scripts made DAxTA the parent process — do not use.
29
+ * Kept for migrate unwrap only.
31
30
  */
32
31
  export declare function wrapUserTestScript(scripts: Record<string, string>, scriptName: string): {
33
32
  original: string;
@@ -38,7 +38,6 @@ exports.listTestScripts = listTestScripts;
38
38
  exports.extractJestConfigFromCommand = extractJestConfigFromCommand;
39
39
  exports.resolveTestScript = resolveTestScript;
40
40
  exports.upsertTestWiringInConfig = upsertTestWiringInConfig;
41
- exports.upsertTestScriptInConfig = upsertTestScriptInConfig;
42
41
  exports.wrapUserTestScript = wrapUserTestScript;
43
42
  const readline_1 = require("readline");
44
43
  const fs_1 = require("fs");
@@ -127,7 +126,7 @@ async function resolveTestScript(options) {
127
126
  const cmd = isDaxtaWrappedScript(choice.command) ? '(already wired → daxta test)' : choice.command.slice(0, 56);
128
127
  console.log(` ${mark} ${label} ${ui_1.c.dim(cmd)}`);
129
128
  });
130
- const answer = await prompt(` ${ui_1.c.yellow('?')} Wire ${ui_1.c.cyan(def.name)} with DAxTA recording?\n` +
129
+ const answer = await prompt(` ${ui_1.c.yellow('?')} Attach DAxTA plugin to ${ui_1.c.cyan(def.name)}?\n` +
131
130
  ` ${ui_1.c.dim('Y')} yes · ${ui_1.c.dim('n')} skip · or type another script name\n ${ui_1.c.cyan('›')} `);
132
131
  if (!answer || /^y(es)?$/i.test(answer))
133
132
  return def.name;
@@ -160,17 +159,19 @@ function upsertConfigFields(cwd, fields, dryRun = false) {
160
159
  (0, fs_1.writeFileSync)(configPath, text);
161
160
  return notes.join(', ');
162
161
  }
163
- /** Persist which script is wired + the original jest command (before wrap). */
162
+ /** Persist test wiring + optional jestConfig path */
164
163
  function upsertTestWiringInConfig(cwd, wiring, dryRun = false) {
165
- return upsertConfigFields(cwd, wiring, dryRun);
166
- }
167
- /** @deprecated use upsertTestWiringInConfig */
168
- function upsertTestScriptInConfig(cwd, testScript, dryRun = false) {
169
- return upsertConfigFields(cwd, { testScript }, dryRun);
164
+ const fields = {
165
+ testScript: wiring.testScript,
166
+ testCommand: wiring.testCommand,
167
+ };
168
+ if (wiring.jestConfig)
169
+ fields.jestConfig = wiring.jestConfig;
170
+ return upsertConfigFields(cwd, fields, dryRun);
170
171
  }
171
172
  /**
172
- * Point the user's script at `daxta test --yes` without adding new script keys.
173
- * Returns the original command that must be stored in config as `testCommand`.
173
+ * @deprecated wrapping scripts made DAxTA the parent process — do not use.
174
+ * Kept for migrate unwrap only.
174
175
  */
175
176
  function wrapUserTestScript(scripts, scriptName) {
176
177
  const current = scripts[scriptName];
@@ -39,6 +39,7 @@ const path = __importStar(require("path"));
39
39
  const child_process_1 = require("child_process");
40
40
  const inject_main_1 = require("./inject-main");
41
41
  const discover_test_1 = require("./discover-test");
42
+ const jest_hooks_1 = require("./jest-hooks");
42
43
  const ui_1 = require("./ui");
43
44
  function readJson(filePath) {
44
45
  return JSON.parse((0, fs_1.readFileSync)(filePath, 'utf8'));
@@ -239,44 +240,68 @@ async function installDaxta(options = {}) {
239
240
  }
240
241
  }
241
242
  console.log('');
242
- console.log(` ${ui_1.c.yellow(ui_1.c.bold('?'))} ${ui_1.c.bold('Test script')} ${ui_1.c.dim('— wire your existing script')}`);
243
+ console.log(` ${ui_1.c.yellow(ui_1.c.bold('?'))} ${ui_1.c.bold('Test script')} ${ui_1.c.dim('— Jest plugin, your script stays the parent')}`);
243
244
  const testScript = await (0, discover_test_1.resolveTestScript)({
244
245
  cwd,
245
246
  scripts: pkg.scripts,
246
247
  yes: options.yes,
247
248
  });
248
249
  if (testScript && pkg.scripts?.[testScript]) {
249
- await (0, ui_1.step)(`Wire ${testScript}`, () => {
250
- const current = pkg.scripts[testScript];
251
- if ((0, discover_test_1.isDaxtaWrappedScript)(current)) {
252
- return {
253
- summary: 'already wired',
254
- details: [`${testScript} → daxta test --yes`],
255
- };
250
+ await (0, ui_1.step)(`Attach to ${testScript}`, () => {
251
+ const details = [];
252
+ let command = pkg.scripts[testScript];
253
+ // Load existing testCommand from config if script was wrapped previously
254
+ const configPath = path.join(cwd, 'daxta.config.ts');
255
+ let savedCommand;
256
+ if ((0, fs_1.existsSync)(configPath)) {
257
+ const cfg = (0, fs_1.readFileSync)(configPath, 'utf8');
258
+ const m = cfg.match(/testCommand\s*:\s*['"`]([^'"`]+)['"`]/);
259
+ savedCommand = m?.[1];
260
+ }
261
+ if ((0, discover_test_1.isDaxtaWrappedScript)(command) && savedCommand && !(0, discover_test_1.isDaxtaWrappedScript)(savedCommand)) {
262
+ if ((0, jest_hooks_1.unwrapDaxtaTestScript)(pkg.scripts, testScript, savedCommand)) {
263
+ command = savedCommand;
264
+ details.push(`unwrapped ${testScript} → original jest command`);
265
+ if (!dryRun)
266
+ writeJson(pkgPath, pkg);
267
+ }
268
+ }
269
+ if ((0, discover_test_1.isDaxtaWrappedScript)(command)) {
270
+ throw new Error(`${testScript} is still "daxta test …" and testCommand is missing. Set testCommand in daxta.config.ts then re-run install.`);
271
+ }
272
+ const jestPath = (0, jest_hooks_1.resolveJestConfigPath)(cwd, { scriptCommand: command });
273
+ if (!jestPath) {
274
+ throw new Error(`No --config in "${testScript}". Add jestConfig: '…' to daxta.config.ts`);
256
275
  }
257
- const { original } = (0, discover_test_1.wrapUserTestScript)(pkg.scripts, testScript);
258
- if (!dryRun)
259
- writeJson(pkgPath, pkg);
260
- const note = (0, discover_test_1.upsertTestWiringInConfig)(cwd, { testScript, testCommand: original }, dryRun);
276
+ const hookNotes = (0, jest_hooks_1.injectJestHooks)(jestPath, dryRun);
277
+ details.push(...hookNotes);
278
+ details.push(`plugin on ${path.relative(cwd, jestPath)}`);
279
+ const note = (0, discover_test_1.upsertTestWiringInConfig)(cwd, {
280
+ testScript,
281
+ testCommand: command,
282
+ jestConfig: path.relative(cwd, jestPath),
283
+ }, dryRun);
284
+ details.push(note);
261
285
  return {
262
- summary: `${testScript} → daxta test --yes`,
263
- details: [`kept original as testCommand`, note],
286
+ summary: 'hooks in Jest config',
287
+ details,
264
288
  };
265
289
  }, { paceMs });
266
290
  }
267
291
  else {
268
- await (0, ui_1.step)('Wire test script', () => 'skipped — run daxta test later to choose', { paceMs });
292
+ await (0, ui_1.step)('Attach test hooks', () => 'skipped', { paceMs });
269
293
  }
270
294
  (0, ui_1.box)('Done', [
271
295
  `${ui_1.c.green('✔')} DAxTA wired for ${ui_1.c.bold(project)}`,
272
- `${ui_1.c.dim('env')} ${ui_1.c.cyan('DAXTA_DOCS=true')} or ${ui_1.c.cyan('false')} ${ui_1.c.dim('(required — app throws if missing)')}`,
296
+ `${ui_1.c.dim('env')} ${ui_1.c.cyan('DAXTA_DOCS=true')} or ${ui_1.c.cyan('false')}`,
297
+ `${ui_1.c.dim('tests')} run your usual script — Docs ready prints when Jest finishes`,
273
298
  ]);
274
299
  const wired = testScript && pkg.scripts?.[testScript] ? testScript : null;
275
300
  (0, ui_1.nextSteps)([
276
301
  { cmd: 'echo "DAXTA_DOCS=true" >> .env', why: 'enable /docs on the app port' },
277
302
  {
278
- cmd: wired ? `${pm} run ${wired}` : 'daxta test',
279
- why: wired ? 'your script → record hits → build docs' : 'pick a test script and run',
303
+ cmd: wired ? `${pm} run ${wired}` : 'pnpm test',
304
+ why: 'unchanged entrypoint — DAxTA is a Jest plugin',
280
305
  },
281
306
  ]);
282
307
  }
@@ -0,0 +1,14 @@
1
+ type JestConfig = Record<string, unknown>;
2
+ export declare function loadJestJson(filePath: string): JestConfig;
3
+ export declare function resolveJestConfigPath(cwd: string, options: {
4
+ jestConfig?: string;
5
+ scriptCommand?: string;
6
+ }): string | null;
7
+ /**
8
+ * Inject DAxTA as a Jest plugin (setup + reporter). Does not wrap the test process.
9
+ * Leaves existing globalSetup / globalTeardown untouched.
10
+ */
11
+ export declare function injectJestHooks(jestConfigPath: string, dryRun?: boolean): string[];
12
+ /** Restore package.json script if it was wrapped as `daxta test --yes`. */
13
+ export declare function unwrapDaxtaTestScript(scripts: Record<string, string>, scriptName: string, originalCommand: string): boolean;
14
+ export {};
@@ -0,0 +1,104 @@
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.loadJestJson = loadJestJson;
37
+ exports.resolveJestConfigPath = resolveJestConfigPath;
38
+ exports.injectJestHooks = injectJestHooks;
39
+ exports.unwrapDaxtaTestScript = unwrapDaxtaTestScript;
40
+ const fs_1 = require("fs");
41
+ const path = __importStar(require("path"));
42
+ const discover_test_1 = require("./discover-test");
43
+ function loadJestJson(filePath) {
44
+ return JSON.parse((0, fs_1.readFileSync)(filePath, 'utf8'));
45
+ }
46
+ function resolveJestConfigPath(cwd, options) {
47
+ if (options.jestConfig) {
48
+ return path.isAbsolute(options.jestConfig) ? options.jestConfig : path.join(cwd, options.jestConfig);
49
+ }
50
+ if (options.scriptCommand) {
51
+ const fromScript = (0, discover_test_1.extractJestConfigFromCommand)(options.scriptCommand);
52
+ if (fromScript) {
53
+ return path.isAbsolute(fromScript) ? fromScript : path.join(cwd, fromScript);
54
+ }
55
+ }
56
+ return null;
57
+ }
58
+ /**
59
+ * Inject DAxTA as a Jest plugin (setup + reporter). Does not wrap the test process.
60
+ * Leaves existing globalSetup / globalTeardown untouched.
61
+ */
62
+ function injectJestHooks(jestConfigPath, dryRun = false) {
63
+ const notes = [];
64
+ if (!(0, fs_1.existsSync)(jestConfigPath))
65
+ throw new Error(`Jest config not found: ${jestConfigPath}`);
66
+ let data;
67
+ try {
68
+ data = loadJestJson(jestConfigPath);
69
+ }
70
+ catch {
71
+ throw new Error(`Jest config must be JSON to inject DAxTA hooks: ${jestConfigPath}`);
72
+ }
73
+ const setup = Array.isArray(data.setupFilesAfterEnv) ? [...data.setupFilesAfterEnv] : [];
74
+ if (!setup.includes('@t0.labs/daxta/setup')) {
75
+ setup.unshift('@t0.labs/daxta/setup');
76
+ data.setupFilesAfterEnv = setup;
77
+ notes.push('setupFilesAfterEnv += @t0.labs/daxta/setup');
78
+ }
79
+ const reporters = Array.isArray(data.reporters) ? [...data.reporters] : ['default'];
80
+ const hasReporter = reporters.some((entry) => {
81
+ if (entry === '@t0.labs/daxta/jest-reporter')
82
+ return true;
83
+ if (Array.isArray(entry) && entry[0] === '@t0.labs/daxta/jest-reporter')
84
+ return true;
85
+ return false;
86
+ });
87
+ if (!hasReporter) {
88
+ reporters.push('@t0.labs/daxta/jest-reporter');
89
+ data.reporters = reporters;
90
+ notes.push('reporters += @t0.labs/daxta/jest-reporter');
91
+ }
92
+ if (!dryRun && notes.length) {
93
+ (0, fs_1.writeFileSync)(jestConfigPath, `${JSON.stringify(data, null, 2)}\n`);
94
+ }
95
+ return notes;
96
+ }
97
+ /** Restore package.json script if it was wrapped as `daxta test --yes`. */
98
+ function unwrapDaxtaTestScript(scripts, scriptName, originalCommand) {
99
+ const current = scripts[scriptName];
100
+ if (!current || !/\bdaxta\s+test\b/.test(current))
101
+ return false;
102
+ scripts[scriptName] = originalCommand;
103
+ return true;
104
+ }
package/dist/cli/main.js CHANGED
@@ -14,6 +14,7 @@ function usage() {
14
14
  Usage:
15
15
  daxta install [--dry-run] [--skip-dep] [--skip-main] [--yes] [--main <path>] [--fast]
16
16
  daxta init (alias of install)
17
+ daxta migrate (force project upgrade)
17
18
  daxta test [--script <name>] [--config <jest.json>] [--serve] [--port <n>] [--yes]
18
19
  daxta build
19
20
  daxta serve [--port <n>]
@@ -25,10 +26,7 @@ One-shot setup:
25
26
  pnpm dlx @t0.labs/daxta install
26
27
  npx @t0.labs/daxta install
27
28
 
28
- daxta test = run tests → build docs (served on app via apiDocs(app) /docs)
29
- --serve = optional standalone viewer (no app)
30
-
31
- On upgrade, CLI auto-migrates old daxta.config / scripts / apiDocs wiring.
29
+ daxta test = forwards to your package script (Jest stays parent; DAxTA is a plugin)
32
30
  `);
33
31
  }
34
32
  function parseArgs(argv) {
@@ -67,14 +65,21 @@ async function main() {
67
65
  usage();
68
66
  return;
69
67
  }
70
- // Auto-upgrade project wiring when package version changes
71
- if (command !== 'install' && command !== 'init') {
72
- (0, migrate_1.reportMigration)((0, migrate_1.migrateProject)());
68
+ // Migrate only on package version bump (or daxta migrate --force)
69
+ if (command === 'migrate') {
70
+ const migration = (0, migrate_1.migrateProject)(process.cwd(), { force: true });
71
+ if (!migration.changed) {
72
+ console.log(`DAxTA already up to date (v${migration.toVersion})`);
73
+ }
74
+ else {
75
+ (0, migrate_1.reportMigration)({ ...migration, skipped: false });
76
+ }
77
+ return;
73
78
  }
79
+ (0, migrate_1.reportMigration)((0, migrate_1.migrateProject)());
74
80
  (0, config_1.resetConfig)();
75
81
  (0, config_1.getConfig)(true);
76
82
  if (command === 'install' || command === 'init') {
77
- (0, migrate_1.reportMigration)((0, migrate_1.migrateProject)());
78
83
  await (0, install_1.installDaxta)({
79
84
  dryRun: Boolean(flags['dry-run']),
80
85
  skipDep: Boolean(flags['skip-dep']),
@@ -83,8 +88,7 @@ async function main() {
83
88
  fast: Boolean(flags.fast),
84
89
  mainPath: typeof flags.main === 'string' ? flags.main : undefined,
85
90
  });
86
- // stamp version after install
87
- (0, migrate_1.reportMigration)((0, migrate_1.migrateProject)());
91
+ (0, migrate_1.reportMigration)((0, migrate_1.migrateProject)(process.cwd(), { force: true }));
88
92
  return;
89
93
  }
90
94
  if (command === 'test') {
@@ -4,10 +4,13 @@ export type MigrateResult = {
4
4
  fromVersion: string | null;
5
5
  toVersion: string;
6
6
  notes: string[];
7
+ skipped?: boolean;
7
8
  };
8
9
  /**
9
- * Idempotent project migration when `@t0.labs/daxta` is upgraded.
10
- * Safe to run on every CLI invocation.
10
+ * Migrate only when package version ≠ daxta.config `daxtaVersion`
11
+ * (or when `daxtaVersion` is missing). Otherwise no-op.
11
12
  */
12
- export declare function migrateProject(cwd?: string): MigrateResult;
13
+ export declare function migrateProject(cwd?: string, options?: {
14
+ force?: boolean;
15
+ }): MigrateResult;
13
16
  export declare function reportMigration(result: MigrateResult): void;
@@ -40,6 +40,7 @@ const fs_1 = require("fs");
40
40
  const path = __importStar(require("path"));
41
41
  const inject_main_1 = require("./inject-main");
42
42
  const discover_test_1 = require("./discover-test");
43
+ const jest_hooks_1 = require("./jest-hooks");
43
44
  const ui_1 = require("./ui");
44
45
  const CONFIG_NAMES = ['daxta.config.ts', 'daxta.config.js', 'daxta.config.mjs', 'daxta.config.cjs'];
45
46
  function readJson(filePath) {
@@ -120,22 +121,35 @@ function removeDaxtaAliases(scripts) {
120
121
  }
121
122
  function migrateTestWiring(cwd, configPath, configText, pkg) {
122
123
  const notes = [];
123
- const scripts = pkg.scripts ?? {};
124
+ const scripts = (pkg.scripts ??= {});
124
125
  const testScript = readStringField(configText, 'testScript');
125
126
  const testCommand = readStringField(configText, 'testCommand');
126
- if (!testScript || !scripts[testScript])
127
- return notes;
128
- const current = scripts[testScript];
129
- if (!(0, discover_test_1.isDaxtaWrappedScript)(current)) {
130
- const { original } = (0, discover_test_1.wrapUserTestScript)(scripts, testScript);
131
- upsertConfigField(configPath, 'testScript', testScript);
132
- upsertConfigField(configPath, 'testCommand', original);
133
- notes.push(`${testScript} → daxta test --yes`);
134
- notes.push(`testCommand ← ${original}`);
135
- return notes;
127
+ const jestConfigField = readStringField(configText, 'jestConfig');
128
+ if (testScript && scripts[testScript] && testCommand && !(0, discover_test_1.isDaxtaWrappedScript)(testCommand)) {
129
+ if ((0, jest_hooks_1.unwrapDaxtaTestScript)(scripts, testScript, testCommand)) {
130
+ notes.push(`unwrapped ${testScript} (DAxTA is no longer the parent)`);
131
+ }
136
132
  }
137
- if (!testCommand) {
138
- notes.push(`missing testCommand for ${testScript} — re-run daxta install to capture original jest cmd`);
133
+ const commandForJest = (testCommand && !(0, discover_test_1.isDaxtaWrappedScript)(testCommand) ? testCommand : undefined) ||
134
+ (testScript && scripts[testScript] && !(0, discover_test_1.isDaxtaWrappedScript)(scripts[testScript])
135
+ ? scripts[testScript]
136
+ : undefined);
137
+ const jestPath = (0, jest_hooks_1.resolveJestConfigPath)(cwd, {
138
+ jestConfig: jestConfigField ?? undefined,
139
+ scriptCommand: commandForJest,
140
+ });
141
+ if (jestPath) {
142
+ try {
143
+ const hooks = (0, jest_hooks_1.injectJestHooks)(jestPath, false);
144
+ notes.push(...hooks);
145
+ if (!jestConfigField) {
146
+ upsertConfigField(configPath, 'jestConfig', path.relative(cwd, jestPath));
147
+ notes.push(`jestConfig ← ${path.relative(cwd, jestPath)}`);
148
+ }
149
+ }
150
+ catch (error) {
151
+ notes.push(`jest hooks: ${error instanceof Error ? error.message : error}`);
152
+ }
139
153
  }
140
154
  return notes;
141
155
  }
@@ -149,12 +163,10 @@ function migrateMainApiDocs(cwd) {
149
163
  catch {
150
164
  continue;
151
165
  }
152
- if (!before.includes('mountDaxtaDocs') && !(/(?<![\w.])docs\s*\(/.test(before) && before.includes('@t0.labs/daxta'))) {
166
+ const hasLegacy = before.includes('mountDaxtaDocs') ||
167
+ (before.includes('@t0.labs/daxta') && /\bdocs\s*\(/.test(before) && !before.includes('apiDocs('));
168
+ if (!hasLegacy)
153
169
  continue;
154
- }
155
- if (before.includes('apiDocs(') && /import\s*\{[^}]*\bapiDocs\b/.test(before) && !before.includes('mountDaxtaDocs')) {
156
- continue;
157
- }
158
170
  try {
159
171
  const note = (0, inject_main_1.injectApiDocs)(file, false);
160
172
  if (!note.startsWith('already'))
@@ -179,59 +191,48 @@ function migrateConfigDefaults(configPath, configText) {
179
191
  return notes;
180
192
  }
181
193
  /**
182
- * Idempotent project migration when `@t0.labs/daxta` is upgraded.
183
- * Safe to run on every CLI invocation.
194
+ * Migrate only when package version ≠ daxta.config `daxtaVersion`
195
+ * (or when `daxtaVersion` is missing). Otherwise no-op.
184
196
  */
185
- function migrateProject(cwd = process.cwd()) {
197
+ function migrateProject(cwd = process.cwd(), options = {}) {
186
198
  const toVersion = packageVersion();
187
199
  const notes = [];
188
200
  const configPath = findConfigPath(cwd);
189
201
  if (!configPath) {
190
- return { changed: false, fromVersion: null, toVersion, notes: [] };
202
+ return { changed: false, fromVersion: null, toVersion, notes: [], skipped: true };
191
203
  }
192
204
  let configText = (0, fs_1.readFileSync)(configPath, 'utf8');
193
205
  const fromVersion = readConfigVersion(configText);
194
- const versionBump = fromVersion !== toVersion;
206
+ if (!options.force && fromVersion === toVersion) {
207
+ return { changed: false, fromVersion, toVersion, notes: [], skipped: true };
208
+ }
195
209
  const pkgPath = path.join(cwd, 'package.json');
196
- let pkgDirty = false;
197
210
  if ((0, fs_1.existsSync)(pkgPath)) {
198
211
  const pkg = readJson(pkgPath);
199
212
  pkg.scripts ??= {};
213
+ const before = JSON.stringify(pkg.scripts);
200
214
  const stripped = stripRegisterNodeOptions(pkg.scripts);
201
215
  const removed = removeDaxtaAliases(pkg.scripts);
202
- if (stripped.length) {
216
+ if (stripped.length)
203
217
  notes.push(`stripped register from: ${stripped.join(', ')}`);
204
- pkgDirty = true;
205
- }
206
- if (removed.length) {
218
+ if (removed.length)
207
219
  notes.push(`removed aliases: ${removed.join(', ')}`);
208
- pkgDirty = true;
209
- }
210
- if (versionBump) {
211
- const beforeScripts = JSON.stringify(pkg.scripts);
212
- const wiringNotes = migrateTestWiring(cwd, configPath, configText, pkg);
213
- notes.push(...wiringNotes);
214
- if (JSON.stringify(pkg.scripts) !== beforeScripts)
215
- pkgDirty = true;
216
- }
217
- if (pkgDirty)
220
+ notes.push(...migrateTestWiring(cwd, configPath, configText, pkg));
221
+ if (JSON.stringify(pkg.scripts) !== before)
218
222
  writeJson(pkgPath, pkg);
219
223
  }
220
- if (versionBump) {
221
- configText = (0, fs_1.readFileSync)(configPath, 'utf8');
222
- notes.push(...migrateConfigDefaults(configPath, configText));
223
- notes.push(...migrateMainApiDocs(cwd));
224
- }
225
- if (upsertConfigField(configPath, 'daxtaVersion', toVersion)) {
226
- if (fromVersion && fromVersion !== toVersion)
227
- notes.push(`daxtaVersion ${fromVersion} → ${toVersion}`);
228
- else if (!fromVersion)
229
- notes.push(`daxtaVersion set to ${toVersion}`);
230
- }
224
+ configText = (0, fs_1.readFileSync)(configPath, 'utf8');
225
+ notes.push(...migrateConfigDefaults(configPath, configText));
226
+ notes.push(...migrateMainApiDocs(cwd));
227
+ upsertConfigField(configPath, 'daxtaVersion', toVersion);
228
+ if (fromVersion && fromVersion !== toVersion)
229
+ notes.push(`daxtaVersion ${fromVersion} → ${toVersion}`);
230
+ else if (!fromVersion)
231
+ notes.push(`daxtaVersion set to ${toVersion}`);
231
232
  return { changed: notes.length > 0, fromVersion, toVersion, notes };
232
233
  }
233
234
  function reportMigration(result) {
234
- if (!result.changed)
235
+ if (result.skipped || !result.changed)
235
236
  return;
236
237
  console.log('');
237
238
  console.log(` ${ui_1.c.magenta('↻')} ${ui_1.c.bold('DAxTA migrate')} ${ui_1.c.dim(result.fromVersion ? `${result.fromVersion} → ${result.toVersion}` : `→ ${result.toVersion}`)}`);
@@ -1,6 +1,6 @@
1
1
  /**
2
- * Run project tests with recording → build → print docs URL.
3
- * Quiet: jest output only, then Docs ready + Next.
2
+ * Thin convenience: runs the project's own test script via the package manager.
3
+ * Does NOT wrap Jest — DAxTA must already be attached as a Jest plugin (install/migrate).
4
4
  */
5
5
  export declare function runDaxtaTest(options?: {
6
6
  cwd?: string;
package/dist/cli/test.js CHANGED
@@ -37,258 +37,70 @@ exports.runDaxtaTest = runDaxtaTest;
37
37
  const fs_1 = require("fs");
38
38
  const path = __importStar(require("path"));
39
39
  const child_process_1 = require("child_process");
40
- const build_spec_1 = require("../build/build-spec");
41
- const incremental_1 = require("../build/incremental");
42
40
  const config_1 = require("../config");
43
- const recorder_1 = require("../recorder");
44
- const paths_1 = require("../serve/paths");
45
- const serve_1 = require("../serve");
46
41
  const discover_test_1 = require("./discover-test");
47
42
  const ui_1 = require("./ui");
48
- function walk(dir, match, out = [], depth = 0) {
49
- if (depth > 6 || !(0, fs_1.existsSync)(dir))
50
- return out;
51
- for (const name of (0, fs_1.readdirSync)(dir)) {
52
- if (name === 'node_modules' || name === 'dist' || name === '.git' || name === 'coverage')
53
- continue;
54
- const full = path.join(dir, name);
55
- let st;
56
- try {
57
- st = (0, fs_1.statSync)(full);
58
- }
59
- catch {
60
- continue;
61
- }
62
- if (st.isDirectory())
63
- walk(full, match, out, depth + 1);
64
- else if (match(name))
65
- out.push(full);
66
- }
67
- return out;
68
- }
69
- function preferIntegrationConfig(files) {
70
- const ranked = [...files].sort((a, b) => {
71
- const score = (f) => {
72
- const n = f.toLowerCase();
73
- if (n.includes('integration'))
74
- return 0;
75
- if (n.includes('e2e'))
76
- return 1;
77
- return 2;
78
- };
79
- return score(a) - score(b);
80
- });
81
- return ranked[0];
82
- }
83
- function parseTestArgs(argv) {
84
- const passthrough = [];
85
- let configFromFlag;
86
- let scriptFromFlag;
87
- let port;
88
- let standaloneServe = false;
89
- let yes = false;
90
- for (let i = 0; i < argv.length; i += 1) {
91
- const token = argv[i];
92
- if (token === '--') {
93
- passthrough.push(...argv.slice(i + 1));
94
- break;
95
- }
96
- if (token === '--config' || token === '-c') {
97
- configFromFlag = argv[++i];
98
- continue;
99
- }
100
- if (token.startsWith('--config=')) {
101
- configFromFlag = token.slice('--config='.length);
102
- continue;
103
- }
104
- if (token === '--script') {
105
- scriptFromFlag = argv[++i];
106
- continue;
107
- }
108
- if (token.startsWith('--script=')) {
109
- scriptFromFlag = token.slice('--script='.length);
110
- continue;
111
- }
112
- if (token === '--port') {
113
- port = Number(argv[++i]);
114
- continue;
115
- }
116
- if (token === '--serve') {
117
- standaloneServe = true;
118
- continue;
119
- }
120
- if (token === '--no-serve') {
121
- standaloneServe = false;
122
- continue;
123
- }
124
- if (token === '--yes' || token === '-y') {
125
- yes = true;
126
- continue;
127
- }
128
- passthrough.push(token);
129
- }
130
- return { configFromFlag, scriptFromFlag, passthrough, port, standaloneServe, yes };
131
- }
132
- function loadJestJson(filePath) {
133
- return JSON.parse((0, fs_1.readFileSync)(filePath, 'utf8'));
134
- }
135
- function mergeDaxtaHooks(base) {
136
- const setup = Array.isArray(base.setupFilesAfterEnv) ? [...base.setupFilesAfterEnv] : [];
137
- if (!setup.includes('@t0.labs/daxta/setup'))
138
- setup.unshift('@t0.labs/daxta/setup');
139
- const reporters = Array.isArray(base.reporters) ? [...base.reporters] : ['default'];
140
- const hasReporter = reporters.some((entry) => {
141
- if (entry === '@t0.labs/daxta/jest-reporter')
142
- return true;
143
- if (Array.isArray(entry) && entry[0] === '@t0.labs/daxta/jest-reporter')
144
- return true;
145
- return false;
146
- });
147
- if (!hasReporter)
148
- reporters.push('@t0.labs/daxta/jest-reporter');
149
- return {
150
- ...base,
151
- setupFilesAfterEnv: setup,
152
- reporters,
153
- };
154
- }
155
- function resolveJestBin(cwd) {
156
- const local = path.join(cwd, 'node_modules', '.bin', process.platform === 'win32' ? 'jest.cmd' : 'jest');
157
- if ((0, fs_1.existsSync)(local))
158
- return local;
159
- return 'jest';
160
- }
161
43
  function readPkg(cwd) {
162
44
  return JSON.parse((0, fs_1.readFileSync)(path.join(cwd, 'package.json'), 'utf8'));
163
45
  }
164
- function resolveBaseConfigPath(cwd, options) {
165
- if (options.configFromFlag) {
166
- return path.isAbsolute(options.configFromFlag)
167
- ? options.configFromFlag
168
- : path.join(cwd, options.configFromFlag);
169
- }
170
- if (options.jestConfig) {
171
- return path.isAbsolute(options.jestConfig) ? options.jestConfig : path.join(cwd, options.jestConfig);
172
- }
173
- if (options.scriptCommand) {
174
- const fromScript = (0, discover_test_1.extractJestConfigFromCommand)(options.scriptCommand);
175
- if (fromScript) {
176
- return path.isAbsolute(fromScript) ? fromScript : path.join(cwd, fromScript);
177
- }
178
- }
179
- const found = walk(cwd, (name) => name.startsWith('jest.') && name.endsWith('.json'));
180
- const preferred = preferIntegrationConfig(found);
181
- if (!preferred) {
182
- throw new Error('No Jest JSON config found. Pass --config test/setup/jest.integration.json');
183
- }
184
- return preferred;
185
- }
186
- function jestExtrasFromCommand(command) {
187
- if (!command)
188
- return [];
189
- const extra = [];
190
- const tokens = command.split(/\s+/).filter(Boolean);
191
- for (let i = 0; i < tokens.length; i += 1) {
192
- const t = tokens[i];
193
- if (t === 'jest' || t.endsWith('/jest') || t === 'cross-env')
194
- continue;
195
- if (t === 'daxta' || t === 'test' || t === '--yes' || t === '-y')
196
- continue;
197
- if (t.startsWith('NODE_OPTIONS=') || (t.includes('=') && !t.startsWith('-')))
198
- continue;
199
- if (t === '--config' || t === '-c') {
200
- i += 1;
201
- continue;
202
- }
203
- if (t.startsWith('--config='))
204
- continue;
205
- extra.push(t);
206
- }
207
- return extra;
46
+ function detectPackageManager(cwd, pkg) {
47
+ if ((0, fs_1.existsSync)(path.join(cwd, 'pnpm-lock.yaml')) || pkg.packageManager?.startsWith('pnpm'))
48
+ return 'pnpm';
49
+ if ((0, fs_1.existsSync)(path.join(cwd, 'yarn.lock')))
50
+ return 'yarn';
51
+ return 'npm';
208
52
  }
209
53
  /**
210
- * Run project tests with recording → build → print docs URL.
211
- * Quiet: jest output only, then Docs ready + Next.
54
+ * Thin convenience: runs the project's own test script via the package manager.
55
+ * Does NOT wrap Jest — DAxTA must already be attached as a Jest plugin (install/migrate).
212
56
  */
213
57
  async function runDaxtaTest(options = {}) {
214
58
  const cwd = options.cwd ?? process.cwd();
215
- const parsed = parseTestArgs(options.argv ?? []);
216
59
  const pkg = readPkg(cwd);
60
+ const pm = detectPackageManager(cwd, pkg);
217
61
  (0, config_1.resetConfig)();
218
- let config = (0, config_1.getConfig)(true);
62
+ const config = (0, config_1.getConfig)(true);
63
+ const passthrough = [];
64
+ let yes = false;
65
+ let scriptFlag;
66
+ for (let i = 0; i < (options.argv ?? []).length; i += 1) {
67
+ const token = (options.argv ?? [])[i];
68
+ if (token === '--yes' || token === '-y')
69
+ yes = true;
70
+ else if (token === '--script')
71
+ scriptFlag = (options.argv ?? [])[++i];
72
+ else if (token === '--')
73
+ passthrough.push(...(options.argv ?? []).slice(i + 1));
74
+ else
75
+ passthrough.push(token);
76
+ }
219
77
  const scriptName = await (0, discover_test_1.resolveTestScript)({
220
78
  cwd,
221
79
  scripts: pkg.scripts,
222
80
  configured: config.testScript,
223
- yes: parsed.yes,
224
- flag: parsed.scriptFromFlag,
81
+ yes,
82
+ flag: scriptFlag,
225
83
  });
226
- let scriptCommand = config.testCommand ||
227
- (scriptName && pkg.scripts?.[scriptName] && !(0, discover_test_1.isDaxtaWrappedScript)(pkg.scripts[scriptName])
228
- ? pkg.scripts[scriptName]
229
- : undefined);
230
- if (scriptName && (!config.testScript || !config.testCommand) && scriptCommand) {
231
- (0, discover_test_1.upsertTestWiringInConfig)(cwd, { testScript: scriptName, testCommand: scriptCommand });
232
- (0, config_1.resetConfig)();
233
- config = (0, config_1.getConfig)(true);
234
- scriptCommand = config.testCommand || scriptCommand;
235
- }
236
- const baseConfigPath = resolveBaseConfigPath(cwd, {
237
- configFromFlag: parsed.configFromFlag,
238
- jestConfig: config.jestConfig,
239
- scriptCommand: scriptCommand || config.testCommand,
240
- });
241
- let base;
242
- try {
243
- base = loadJestJson(baseConfigPath);
84
+ if (!scriptName || !pkg.scripts?.[scriptName]) {
85
+ console.log(`${ui_1.c.yellow('!')} No test script configured. Run ${ui_1.c.cyan('daxta install')} to attach the Jest plugin.`);
86
+ process.exitCode = 1;
87
+ return;
244
88
  }
245
- catch {
246
- throw new Error(`Jest config must be JSON for dynamic merge: ${baseConfigPath}`);
89
+ if ((0, discover_test_1.isDaxtaWrappedScript)(pkg.scripts[scriptName])) {
90
+ console.log(`${ui_1.c.yellow('!')} ${scriptName} still wraps ${ui_1.c.bold('daxta test')}. Run ${ui_1.c.cyan('daxta migrate')} to unwrap and attach as a Jest plugin.`);
91
+ process.exitCode = 1;
92
+ return;
247
93
  }
248
- const merged = mergeDaxtaHooks(base);
249
- const configDir = path.dirname(baseConfigPath);
250
- const tmpDir = path.join(cwd, 'daxta', 'out');
251
- (0, fs_1.mkdirSync)(tmpDir, { recursive: true });
252
- (0, fs_1.writeFileSync)(path.join(tmpDir, 'jest.daxta.runtime.json'), `${JSON.stringify({ ...merged, _source: path.relative(tmpDir, baseConfigPath) }, null, 2)}\n`);
253
- const siblingTmp = path.join(configDir, '.jest.daxta.runtime.json');
254
- (0, fs_1.writeFileSync)(siblingTmp, `${JSON.stringify(merged, null, 2)}\n`);
255
- (0, recorder_1.clearWorkerHits)();
256
- const jestBin = resolveJestBin(cwd);
257
- const result = (0, child_process_1.spawnSync)(jestBin, ['--config', siblingTmp, ...jestExtrasFromCommand(scriptCommand || config.testCommand), ...parsed.passthrough], {
94
+ console.log(`${ui_1.c.dim('DAxTA')} forwarding to ${ui_1.c.cyan(`${pm} run ${scriptName}`)} ${ui_1.c.dim('(Jest stays parent)')}`);
95
+ const args = pm === 'npm' ? ['run', scriptName, '--', ...passthrough] : ['run', scriptName, ...passthrough];
96
+ const result = (0, child_process_1.spawnSync)(pm, args, {
258
97
  cwd,
259
98
  stdio: 'inherit',
260
99
  shell: process.platform === 'win32',
261
- env: { ...process.env, DAXTA_QUIET: '1' },
100
+ env: process.env,
262
101
  });
263
- const testStatus = result.status ?? 1;
102
+ if (result.status && result.status !== 0)
103
+ process.exit(result.status);
264
104
  if (result.error)
265
105
  throw result.error;
266
- try {
267
- (0, fs_1.unlinkSync)(siblingTmp);
268
- }
269
- catch {
270
- // ignore
271
- }
272
- const build = (0, build_spec_1.buildDaxtaSpec)({ silent: true, html: true });
273
- (0, incremental_1.clearPartialMarker)();
274
- const buildSummary = build.skipped ? 'no hits yet' : `${build.hits} hits · ${build.operations} ops`;
275
- const docsBase = (0, paths_1.getDocsBasePath)();
276
- const appDocsUrl = `${config.baseUrl.replace(/\/$/, '')}${docsBase}`;
277
- if (parsed.standaloneServe) {
278
- const port = parsed.port ?? config.port;
279
- (0, ui_1.box)('Docs ready', [
280
- `${ui_1.c.green('✔')} ${ui_1.c.bold(`http://127.0.0.1:${port}${docsBase}`)} ${ui_1.c.dim(`(${buildSummary})`)}`,
281
- testStatus !== 0 ? `${ui_1.c.yellow('!')} tests exited ${testStatus}` : `${ui_1.c.dim('ctrl+c')} to stop`,
282
- ].filter(Boolean));
283
- (0, serve_1.serveApiDocs)({ port });
284
- return;
285
- }
286
- (0, ui_1.box)('Docs ready', [
287
- `${ui_1.c.green('✔')} ${ui_1.c.cyan(appDocsUrl)} ${ui_1.c.dim(`(${buildSummary})`)}`,
288
- `${ui_1.c.dim('DAXTA_DOCS=true')} required on app start`,
289
- testStatus !== 0 ? `${ui_1.c.yellow('!')} tests exited ${testStatus}` : '',
290
- ].filter(Boolean));
291
- (0, ui_1.nextSteps)([{ cmd: 'DAXTA_DOCS=true pnpm start:dev', why: `open ${appDocsUrl}` }]);
292
- if (testStatus !== 0)
293
- process.exit(testStatus);
294
106
  }
@@ -1,2 +1,5 @@
1
- /** Optional jest globalTeardown — silent; `daxta test` prints the final Docs ready. */
1
+ /**
2
+ * Optional jest globalTeardown — silent build only.
3
+ * Docs ready is printed by the Jest reporter so we don't own the test process.
4
+ */
2
5
  export default function daxtaGlobalTeardown(): Promise<void>;
@@ -3,10 +3,13 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.default = daxtaGlobalTeardown;
4
4
  const incremental_1 = require("../build/incremental");
5
5
  const build_spec_1 = require("../build/build-spec");
6
- /** Optional jest globalTeardown — silent; `daxta test` prints the final Docs ready. */
6
+ /**
7
+ * Optional jest globalTeardown — silent build only.
8
+ * Docs ready is printed by the Jest reporter so we don't own the test process.
9
+ */
7
10
  async function daxtaGlobalTeardown() {
8
11
  try {
9
- (0, build_spec_1.buildDaxtaSpec)({ silent: true });
12
+ (0, build_spec_1.buildDaxtaSpec)({ silent: true, html: true });
10
13
  (0, incremental_1.clearPartialMarker)();
11
14
  }
12
15
  catch {
@@ -1,3 +1,7 @@
1
+ /**
2
+ * Jest reporter plugin — records/rebuilds during the run, prints Docs ready at the end.
3
+ * Jest stays the process parent; DAxTA is only a plugin.
4
+ */
1
5
  declare class DaxtaJestReporter {
2
6
  private suitesDone;
3
7
  onTestResult(): void;
@@ -1,4 +1,36 @@
1
1
  "use strict";
2
+ const config_1 = require("../config");
3
+ const build_spec_1 = require("../build/build-spec");
4
+ const incremental_1 = require("../build/incremental");
5
+ const paths_1 = require("../serve/paths");
6
+ function printDocsReady(hits, operations) {
7
+ try {
8
+ (0, config_1.resetConfig)();
9
+ const config = (0, config_1.getConfig)(true);
10
+ const docsBase = (0, paths_1.getDocsBasePath)();
11
+ const url = `${config.baseUrl.replace(/\/$/, '')}${docsBase}`;
12
+ const cyan = (s) => `\x1b[36m${s}\x1b[0m`;
13
+ const green = (s) => `\x1b[32m${s}\x1b[0m`;
14
+ const dim = (s) => `\x1b[2m${s}\x1b[0m`;
15
+ const bold = (s) => `\x1b[1m${s}\x1b[0m`;
16
+ console.log('');
17
+ console.log(` ${bold('Docs ready')}`);
18
+ console.log(` ${dim('│')} ${green('✔')} ${cyan(url)} ${dim(`(${hits} hits · ${operations} ops)`)}`);
19
+ console.log(` ${dim('│')} ${dim('DAXTA_DOCS=true')} required on app start`);
20
+ console.log('');
21
+ console.log(` ${bold('Next')}`);
22
+ console.log(` ${cyan('$')} ${bold('DAXTA_DOCS=true pnpm start:dev')}`);
23
+ console.log(` ${dim(`open ${url}`)}`);
24
+ console.log('');
25
+ }
26
+ catch {
27
+ console.log(`\nDAxTA docs ready (${hits} hits · ${operations} ops)\n`);
28
+ }
29
+ }
30
+ /**
31
+ * Jest reporter plugin — records/rebuilds during the run, prints Docs ready at the end.
32
+ * Jest stays the process parent; DAxTA is only a plugin.
33
+ */
2
34
  class DaxtaJestReporter {
3
35
  constructor() {
4
36
  this.suitesDone = 0;
@@ -8,7 +40,20 @@ class DaxtaJestReporter {
8
40
  this.rebuild({ html: this.suitesDone % 5 === 0 });
9
41
  }
10
42
  onRunComplete() {
11
- this.rebuild({ html: true });
43
+ const result = this.rebuild({ html: true });
44
+ if (!result || result.skipped) {
45
+ try {
46
+ const build = (0, build_spec_1.buildDaxtaSpec)({ silent: true, html: true });
47
+ (0, incremental_1.clearPartialMarker)();
48
+ if (!build.skipped)
49
+ printDocsReady(build.hits, build.operations);
50
+ }
51
+ catch {
52
+ // ignore
53
+ }
54
+ return;
55
+ }
56
+ printDocsReady(result.hits ?? 0, result.operations ?? 0);
12
57
  }
13
58
  rebuild(options) {
14
59
  try {
@@ -16,11 +61,10 @@ class DaxtaJestReporter {
16
61
  require('reflect-metadata');
17
62
  // eslint-disable-next-line @typescript-eslint/no-var-requires
18
63
  const { rebuildFromDisk } = require('../build/incremental');
19
- rebuildFromDisk({ silent: true, force: true, html: options.html });
20
- // Keep jest output clean — final summary comes from `daxta test` (Docs ready).
64
+ return rebuildFromDisk({ silent: true, force: true, html: options.html });
21
65
  }
22
66
  catch {
23
- // incremental rebuild must never fail the test run
67
+ return null;
24
68
  }
25
69
  }
26
70
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@t0.labs/daxta",
3
- "version": "0.3.2",
3
+ "version": "0.3.4",
4
4
  "description": "DAxTA \u2014 docs from Nest integration traffic + DTO field CLI / Try-it",
5
5
  "license": "MIT",
6
6
  "main": "dist/index.js",