@t0.labs/daxta 0.2.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,195 @@
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.runDaxtaTest = runDaxtaTest;
37
+ const fs_1 = require("fs");
38
+ const path = __importStar(require("path"));
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
+ const recorder_1 = require("../recorder");
43
+ function walk(dir, match, out = [], depth = 0) {
44
+ if (depth > 6 || !(0, fs_1.existsSync)(dir))
45
+ return out;
46
+ for (const name of (0, fs_1.readdirSync)(dir)) {
47
+ if (name === 'node_modules' || name === 'dist' || name === '.git' || name === 'coverage')
48
+ continue;
49
+ const full = path.join(dir, name);
50
+ let st;
51
+ try {
52
+ st = (0, fs_1.statSync)(full);
53
+ }
54
+ catch {
55
+ continue;
56
+ }
57
+ if (st.isDirectory())
58
+ walk(full, match, out, depth + 1);
59
+ else if (match(name))
60
+ out.push(full);
61
+ }
62
+ return out;
63
+ }
64
+ function preferIntegrationConfig(files) {
65
+ const ranked = [...files].sort((a, b) => {
66
+ const score = (f) => {
67
+ const n = f.toLowerCase();
68
+ if (n.includes('integration'))
69
+ return 0;
70
+ if (n.includes('e2e'))
71
+ return 1;
72
+ return 2;
73
+ };
74
+ return score(a) - score(b);
75
+ });
76
+ return ranked[0];
77
+ }
78
+ function parseTestArgs(argv) {
79
+ const passthrough = [];
80
+ let configFromFlag;
81
+ for (let i = 0; i < argv.length; i += 1) {
82
+ const token = argv[i];
83
+ if (token === '--') {
84
+ passthrough.push(...argv.slice(i + 1));
85
+ break;
86
+ }
87
+ if (token === '--config' || token === '-c') {
88
+ configFromFlag = argv[++i];
89
+ continue;
90
+ }
91
+ if (token.startsWith('--config=')) {
92
+ configFromFlag = token.slice('--config='.length);
93
+ continue;
94
+ }
95
+ passthrough.push(token);
96
+ }
97
+ return { configFromFlag, passthrough };
98
+ }
99
+ function loadJestJson(filePath) {
100
+ return JSON.parse((0, fs_1.readFileSync)(filePath, 'utf8'));
101
+ }
102
+ function mergeDaxtaHooks(base) {
103
+ const setup = Array.isArray(base.setupFilesAfterEnv) ? [...base.setupFilesAfterEnv] : [];
104
+ if (!setup.includes('@t0.labs/daxta/setup'))
105
+ setup.unshift('@t0.labs/daxta/setup');
106
+ const reporters = Array.isArray(base.reporters) ? [...base.reporters] : ['default'];
107
+ const hasReporter = reporters.some((entry) => {
108
+ if (entry === '@t0.labs/daxta/jest-reporter')
109
+ return true;
110
+ if (Array.isArray(entry) && entry[0] === '@t0.labs/daxta/jest-reporter')
111
+ return true;
112
+ return false;
113
+ });
114
+ if (!hasReporter)
115
+ reporters.push('@t0.labs/daxta/jest-reporter');
116
+ return {
117
+ ...base,
118
+ setupFilesAfterEnv: setup,
119
+ reporters,
120
+ };
121
+ }
122
+ function resolveJestBin(cwd) {
123
+ const local = path.join(cwd, 'node_modules', '.bin', process.platform === 'win32' ? 'jest.cmd' : 'jest');
124
+ if ((0, fs_1.existsSync)(local))
125
+ return local;
126
+ return 'jest';
127
+ }
128
+ /**
129
+ * Run Jest with DAxTA recording injected via a temp config — no project file edits.
130
+ */
131
+ function runDaxtaTest(options = {}) {
132
+ const cwd = options.cwd ?? process.cwd();
133
+ const { configFromFlag, passthrough } = parseTestArgs(options.argv ?? []);
134
+ let baseConfigPath = configFromFlag
135
+ ? path.isAbsolute(configFromFlag)
136
+ ? configFromFlag
137
+ : path.join(cwd, configFromFlag)
138
+ : undefined;
139
+ if (!baseConfigPath) {
140
+ const found = walk(cwd, (name) => name.startsWith('jest.') && name.endsWith('.json'));
141
+ baseConfigPath = preferIntegrationConfig(found);
142
+ }
143
+ if (!baseConfigPath || !(0, fs_1.existsSync)(baseConfigPath)) {
144
+ throw new Error('No Jest JSON config found. Pass one: daxta test --config test/setup/jest.integration.json');
145
+ }
146
+ let base;
147
+ try {
148
+ base = loadJestJson(baseConfigPath);
149
+ }
150
+ catch {
151
+ throw new Error(`Jest config must be JSON for dynamic merge: ${baseConfigPath}`);
152
+ }
153
+ const merged = mergeDaxtaHooks(base);
154
+ // Paths in jest config are relative to the config file directory
155
+ const configDir = path.dirname(baseConfigPath);
156
+ const tmpDir = path.join(cwd, 'daxta', 'out');
157
+ (0, fs_1.mkdirSync)(tmpDir, { recursive: true });
158
+ const tmpConfig = path.join(tmpDir, 'jest.daxta.runtime.json');
159
+ // Rewrite relative paths that jest resolves from config location — keep same dir as base
160
+ // by writing next to base via a name that won't be committed (under daxta/out) and setting root.
161
+ // Jest resolves <rootDir> from config's rootDir or cwd of config file.
162
+ // Put runtime config beside original so relative globalSetup paths still work:
163
+ const siblingTmp = path.join(configDir, '.jest.daxta.runtime.json');
164
+ (0, fs_1.writeFileSync)(siblingTmp, `${JSON.stringify(merged, null, 2)}\n`);
165
+ // also keep a copy under out for debugging
166
+ (0, fs_1.writeFileSync)(tmpConfig, `${JSON.stringify({ ...merged, _extends: path.relative(tmpDir, baseConfigPath) }, null, 2)}\n`);
167
+ (0, recorder_1.clearWorkerHits)();
168
+ const jestBin = resolveJestBin(cwd);
169
+ const result = (0, child_process_1.spawnSync)(jestBin, ['--config', siblingTmp, ...passthrough], {
170
+ cwd,
171
+ stdio: 'inherit',
172
+ shell: process.platform === 'win32',
173
+ env: process.env,
174
+ });
175
+ try {
176
+ const build = (0, build_spec_1.buildDaxtaSpec)({ silent: true });
177
+ if (!build.skipped) {
178
+ console.log(`DAxTA ${build.changed ? 'updated' : 'ready'}: ${build.hits} hits, ${build.operations} operations`);
179
+ }
180
+ (0, incremental_1.clearPartialMarker)();
181
+ }
182
+ catch (error) {
183
+ console.error('DAxTA build failed:', error instanceof Error ? error.message : error);
184
+ }
185
+ try {
186
+ (0, fs_1.unlinkSync)(siblingTmp);
187
+ }
188
+ catch {
189
+ // ignore
190
+ }
191
+ if (result.status && result.status !== 0)
192
+ process.exit(result.status);
193
+ if (result.error)
194
+ throw result.error;
195
+ }
package/dist/index.d.ts CHANGED
@@ -4,7 +4,7 @@ export { rebuildFromDisk, flushAndRebuild, clearPartialMarker, touchPartialMarke
4
4
  export { install, flush, clearWorkerHits, getHits, type RecordedHit } from './recorder';
5
5
  export { dtoRequired, type FieldLocation } from './fields/dto-fields';
6
6
  export { buildFieldsFile, writeFieldsFile, readFieldsFile, type FieldsFile } from './fields/export-fields';
7
- export { startDaxtaDocsServer, startServe, createDaxtaDocsMiddleware, mountDaxtaDocs, getDocsBasePath, getHtmlPath, getOutDir, getSpecJsonPath, type DaxtaDocsMiddleware, type DaxtaDocsMiddlewareOptions, } from './serve';
7
+ export { docs, docsHandler, serveDocs, getDocsBasePath, getHtmlPath, getOutDir, getSpecJsonPath, type DocsHandler, type DocsOptions, } from './serve';
8
8
  export { runInteractiveCall, runFileCall, executeCall, type CallValues } from './call';
9
9
  export type { FieldDoc, 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.mountDaxtaDocs = exports.createDaxtaDocsMiddleware = exports.startServe = exports.startDaxtaDocsServer = exports.readFieldsFile = exports.writeFieldsFile = exports.buildFieldsFile = exports.dtoRequired = exports.getHits = exports.clearWorkerHits = exports.flush = exports.install = exports.touchPartialMarker = exports.clearPartialMarker = exports.flushAndRebuild = exports.rebuildFromDisk = exports.loadHits = exports.buildOpenApi = exports.buildDaxtaSpec = exports.resolveConfig = exports.getConfig = exports.defineConfig = void 0;
3
+ exports.installDaxta = exports.executeCall = exports.runFileCall = exports.runInteractiveCall = exports.getSpecJsonPath = exports.getOutDir = exports.getHtmlPath = exports.getDocsBasePath = exports.serveDocs = exports.docsHandler = exports.docs = exports.readFieldsFile = exports.writeFieldsFile = exports.buildFieldsFile = exports.dtoRequired = exports.getHits = exports.clearWorkerHits = exports.flush = exports.install = exports.touchPartialMarker = exports.clearPartialMarker = exports.flushAndRebuild = exports.rebuildFromDisk = exports.loadHits = exports.buildOpenApi = exports.buildDaxtaSpec = exports.resolveConfig = exports.getConfig = exports.defineConfig = void 0;
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; } });
@@ -26,10 +26,9 @@ Object.defineProperty(exports, "buildFieldsFile", { enumerable: true, get: funct
26
26
  Object.defineProperty(exports, "writeFieldsFile", { enumerable: true, get: function () { return export_fields_1.writeFieldsFile; } });
27
27
  Object.defineProperty(exports, "readFieldsFile", { enumerable: true, get: function () { return export_fields_1.readFieldsFile; } });
28
28
  var serve_1 = require("./serve");
29
- Object.defineProperty(exports, "startDaxtaDocsServer", { enumerable: true, get: function () { return serve_1.startDaxtaDocsServer; } });
30
- Object.defineProperty(exports, "startServe", { enumerable: true, get: function () { return serve_1.startServe; } });
31
- Object.defineProperty(exports, "createDaxtaDocsMiddleware", { enumerable: true, get: function () { return serve_1.createDaxtaDocsMiddleware; } });
32
- Object.defineProperty(exports, "mountDaxtaDocs", { enumerable: true, get: function () { return serve_1.mountDaxtaDocs; } });
29
+ Object.defineProperty(exports, "docs", { enumerable: true, get: function () { return serve_1.docs; } });
30
+ Object.defineProperty(exports, "docsHandler", { enumerable: true, get: function () { return serve_1.docsHandler; } });
31
+ Object.defineProperty(exports, "serveDocs", { enumerable: true, get: function () { return serve_1.serveDocs; } });
33
32
  Object.defineProperty(exports, "getDocsBasePath", { enumerable: true, get: function () { return serve_1.getDocsBasePath; } });
34
33
  Object.defineProperty(exports, "getHtmlPath", { enumerable: true, get: function () { return serve_1.getHtmlPath; } });
35
34
  Object.defineProperty(exports, "getOutDir", { enumerable: true, get: function () { return serve_1.getOutDir; } });
package/dist/register.js CHANGED
@@ -2,7 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  /**
4
4
  * Side-effect entry: `node -r @t0.labs/daxta/register`
5
- * Auto-mounts DAxTA `/docs` on NestFactory.create (non-production).
5
+ * Prefer injecting `docs(app)` into main.ts via `daxta install`.
6
6
  */
7
7
  const middleware_1 = require("./serve/middleware");
8
8
  function patchNestFactory() {
@@ -16,7 +16,7 @@ function patchNestFactory() {
16
16
  const originalCreate = nestFactory.create.bind(nestFactory);
17
17
  nestFactory.create = async (...args) => {
18
18
  const app = await originalCreate(...args);
19
- (0, middleware_1.mountDaxtaDocs)(app, { enabled: process.env.NODE_ENV !== 'production' });
19
+ (0, middleware_1.docs)(app);
20
20
  return app;
21
21
  };
22
22
  }
@@ -1,9 +1,7 @@
1
1
  import * as http from 'http';
2
- export { createDaxtaDocsMiddleware, mountDaxtaDocs, type DaxtaDocsMiddleware, type DaxtaDocsMiddlewareOptions, } from './middleware';
2
+ export { docs, docsHandler, type DocsHandler, type DocsOptions } from './middleware';
3
3
  export { getDocsBasePath, getHtmlPath, getOutDir, getSpecJsonPath } from './paths';
4
- /** Standalone docs HTTP server (CLI: `daxta serve`). Prefer `mountDaxtaDocs` on the app port. */
5
- export declare function startDaxtaDocsServer(options?: {
4
+ /** Standalone docs HTTP server (CLI: `daxta serve`). Prefer `docs(app)` on the app port. */
5
+ export declare function serveDocs(options?: {
6
6
  port?: number;
7
7
  }): http.Server<typeof http.IncomingMessage, typeof http.ServerResponse>;
8
- /** @deprecated Use `startDaxtaDocsServer` */
9
- export declare const startServe: typeof startDaxtaDocsServer;
@@ -33,8 +33,8 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.startServe = exports.getSpecJsonPath = exports.getOutDir = exports.getHtmlPath = exports.getDocsBasePath = exports.mountDaxtaDocs = exports.createDaxtaDocsMiddleware = void 0;
37
- exports.startDaxtaDocsServer = startDaxtaDocsServer;
36
+ exports.getSpecJsonPath = exports.getOutDir = exports.getHtmlPath = exports.getDocsBasePath = exports.docsHandler = exports.docs = void 0;
37
+ exports.serveDocs = serveDocs;
38
38
  const fs_1 = require("fs");
39
39
  const http = __importStar(require("http"));
40
40
  const url_1 = require("url");
@@ -43,8 +43,8 @@ const paths_1 = require("./paths");
43
43
  const proxy_1 = require("./proxy");
44
44
  const spec_utils_1 = require("./spec-utils");
45
45
  var middleware_1 = require("./middleware");
46
- Object.defineProperty(exports, "createDaxtaDocsMiddleware", { enumerable: true, get: function () { return middleware_1.createDaxtaDocsMiddleware; } });
47
- Object.defineProperty(exports, "mountDaxtaDocs", { enumerable: true, get: function () { return middleware_1.mountDaxtaDocs; } });
46
+ Object.defineProperty(exports, "docs", { enumerable: true, get: function () { return middleware_1.docs; } });
47
+ Object.defineProperty(exports, "docsHandler", { enumerable: true, get: function () { return middleware_1.docsHandler; } });
48
48
  var paths_2 = require("./paths");
49
49
  Object.defineProperty(exports, "getDocsBasePath", { enumerable: true, get: function () { return paths_2.getDocsBasePath; } });
50
50
  Object.defineProperty(exports, "getHtmlPath", { enumerable: true, get: function () { return paths_2.getHtmlPath; } });
@@ -54,8 +54,8 @@ function send(res, status, body, headers = {}) {
54
54
  res.writeHead(status, headers);
55
55
  res.end(body);
56
56
  }
57
- /** Standalone docs HTTP server (CLI: `daxta serve`). Prefer `mountDaxtaDocs` on the app port. */
58
- function startDaxtaDocsServer(options = {}) {
57
+ /** Standalone docs HTTP server (CLI: `daxta serve`). Prefer `docs(app)` on the app port. */
58
+ function serveDocs(options = {}) {
59
59
  const config = (0, config_1.getConfig)();
60
60
  const port = options.port ?? Number(process.env.DAXTA_DOCS_PORT || process.env.OPENAPI_DOCS_PORT || config.port);
61
61
  const htmlPath = (0, paths_1.getHtmlPath)();
@@ -122,5 +122,3 @@ function startDaxtaDocsServer(options = {}) {
122
122
  });
123
123
  return server;
124
124
  }
125
- /** @deprecated Use `startDaxtaDocsServer` */
126
- exports.startServe = startDaxtaDocsServer;
@@ -1,4 +1,4 @@
1
- export type DaxtaDocsMiddlewareOptions = {
1
+ export type DocsOptions = {
2
2
  /** URL prefix for the viewer. Default from config (`docsPath`) or `/docs`. */
3
3
  basePath?: string;
4
4
  };
@@ -20,19 +20,21 @@ type LooseResponse = {
20
20
  end: (body?: string | Buffer) => void;
21
21
  writeHead?: (code: number, headers?: Record<string, string>) => void;
22
22
  };
23
- export type DaxtaDocsMiddleware = (req: LooseRequest, res: LooseResponse, next: (error?: unknown) => void) => void | Promise<void>;
23
+ export type DocsHandler = (req: LooseRequest, res: LooseResponse, next: (error?: unknown) => void) => void | Promise<void>;
24
24
  /**
25
- * Express / Nest compatible middleware that serves the DAxTA viewer under `/docs`
25
+ * Express / Nest handler that serves the DAxTA viewer under `/docs`
26
26
  * (or `basePath`) and the Try-it proxy at `/__proxy`.
27
27
  */
28
- export declare function createDaxtaDocsMiddleware(options?: DaxtaDocsMiddlewareOptions): DaxtaDocsMiddleware;
28
+ export declare function docsHandler(options?: DocsOptions): DocsHandler;
29
29
  /**
30
- * Mount DAxTA docs on a Nest / Express app (`app.use(...)`).
31
- * Pass `{ enabled: false }` to no-op (e.g. production).
30
+ * Enable DAxTA `/docs` on a Nest / Express app (`app.use(...)`).
31
+ *
32
+ * Requires `DAXTA_DOCS` in the environment:
33
+ * - missing / empty → throws (app must set it explicitly)
34
+ * - `true` | `1` | `yes` | `on` → serve `/docs`
35
+ * - `false` | `0` | `no` | `off` → no-op
32
36
  */
33
- export declare function mountDaxtaDocs(app: {
37
+ export declare function docs(app: {
34
38
  use: (...handlers: unknown[]) => unknown;
35
- }, options?: DaxtaDocsMiddlewareOptions & {
36
- enabled?: boolean;
37
- }): void;
39
+ }, options?: DocsOptions): void;
38
40
  export {};
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.createDaxtaDocsMiddleware = createDaxtaDocsMiddleware;
4
- exports.mountDaxtaDocs = mountDaxtaDocs;
3
+ exports.docsHandler = docsHandler;
4
+ exports.docs = docs;
5
5
  const fs_1 = require("fs");
6
6
  const paths_1 = require("./paths");
7
7
  const proxy_1 = require("./proxy");
@@ -57,10 +57,10 @@ function bodyToBuffer(body) {
57
57
  return Buffer.from(JSON.stringify(body));
58
58
  }
59
59
  /**
60
- * Express / Nest compatible middleware that serves the DAxTA viewer under `/docs`
60
+ * Express / Nest handler that serves the DAxTA viewer under `/docs`
61
61
  * (or `basePath`) and the Try-it proxy at `/__proxy`.
62
62
  */
63
- function createDaxtaDocsMiddleware(options = {}) {
63
+ function docsHandler(options = {}) {
64
64
  const basePath = (options.basePath ?? (0, paths_1.getDocsBasePath)()).replace(/\/$/, '') || '/docs';
65
65
  return async (req, res, next) => {
66
66
  const method = (req.method || 'GET').toUpperCase();
@@ -121,11 +121,25 @@ function createDaxtaDocsMiddleware(options = {}) {
121
121
  };
122
122
  }
123
123
  /**
124
- * Mount DAxTA docs on a Nest / Express app (`app.use(...)`).
125
- * Pass `{ enabled: false }` to no-op (e.g. production).
124
+ * Enable DAxTA `/docs` on a Nest / Express app (`app.use(...)`).
125
+ *
126
+ * Requires `DAXTA_DOCS` in the environment:
127
+ * - missing / empty → throws (app must set it explicitly)
128
+ * - `true` | `1` | `yes` | `on` → serve `/docs`
129
+ * - `false` | `0` | `no` | `off` → no-op
126
130
  */
127
- function mountDaxtaDocs(app, options = {}) {
128
- if (options.enabled === false)
131
+ function docs(app, options = {}) {
132
+ const raw = process.env.DAXTA_DOCS;
133
+ if (raw == null || String(raw).trim() === '') {
134
+ throw new Error('DAxTA: DAXTA_DOCS is not set. Set DAXTA_DOCS=true to enable /docs, or DAXTA_DOCS=false to disable.');
135
+ }
136
+ const normalized = String(raw).trim().toLowerCase();
137
+ const enabled = ['1', 'true', 'yes', 'on'].includes(normalized);
138
+ const disabled = ['0', 'false', 'no', 'off'].includes(normalized);
139
+ if (!enabled && !disabled) {
140
+ throw new Error(`DAxTA: invalid DAXTA_DOCS="${raw}". Use true/false (or 1/0).`);
141
+ }
142
+ if (!enabled)
129
143
  return;
130
- app.use(createDaxtaDocsMiddleware(options));
144
+ app.use(docsHandler(options));
131
145
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@t0.labs/daxta",
3
- "version": "0.2.0",
3
+ "version": "0.2.1",
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",