@dudousxd/nestjs-codegen 0.10.0 → 0.12.0

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/dist/index.cjs CHANGED
@@ -248,8 +248,8 @@ Run \`nestjs-codegen init\` to create a starter config.`
248
248
  }
249
249
 
250
250
  // src/generate.ts
251
- var import_promises11 = require("fs/promises");
252
- var import_node_path12 = require("path");
251
+ var import_promises12 = require("fs/promises");
252
+ var import_node_path13 = require("path");
253
253
 
254
254
  // src/discovery/pages.ts
255
255
  var import_promises2 = require("fs/promises");
@@ -863,7 +863,11 @@ function buildRequestModel(c) {
863
863
  urlExpr,
864
864
  optsExpr,
865
865
  responseType: `${TA}['response']`,
866
- queryKeyExpr: `[${flat}, input] as const`
866
+ // When no input is supplied the key omits the trailing element entirely
867
+ // (`[name]` rather than `[name, undefined]`) so the bare `.queryKey()` is a
868
+ // clean prefix that partial-matches every parametrized variant — making it
869
+ // directly usable for `invalidateQueries`.
870
+ queryKeyExpr: `(input === undefined ? [${flat}] as const : [${flat}, input] as const)`
867
871
  };
868
872
  }
869
873
  function renderFetcherRequest(req) {
@@ -2143,6 +2147,99 @@ function buildEmpty() {
2143
2147
  ].join("\n");
2144
2148
  }
2145
2149
 
2150
+ // src/generate-manifest.ts
2151
+ var import_node_crypto = require("crypto");
2152
+ var import_promises11 = require("fs/promises");
2153
+ var import_node_path12 = require("path");
2154
+ var import_fast_glob2 = __toESM(require("fast-glob"), 1);
2155
+ var MANIFEST_FILE = ".codegen-manifest.json";
2156
+ var LOCK_FILE = ".watcher.lock";
2157
+ function isManifestShape(value) {
2158
+ if (typeof value !== "object" || value === null) return false;
2159
+ const candidate = value;
2160
+ if (typeof candidate.version !== "string") return false;
2161
+ if (typeof candidate.hash !== "string") return false;
2162
+ if (!Array.isArray(candidate.files)) return false;
2163
+ return candidate.files.every((entry) => typeof entry === "string");
2164
+ }
2165
+ function serializeConfig(config) {
2166
+ try {
2167
+ return JSON.stringify(config, (_key, value) => {
2168
+ if (typeof value === "function") return `[fn:${value.name}]${value.toString()}`;
2169
+ return value;
2170
+ });
2171
+ } catch {
2172
+ return `unserializable:${config.codegen.outDir}:${config.contracts.glob}`;
2173
+ }
2174
+ }
2175
+ async function discoverInputFiles(config) {
2176
+ const globs = [config.contracts.glob, config.forms.watch];
2177
+ if (config.pages) globs.push(config.pages.glob);
2178
+ const cwd = config.codegen.cwd;
2179
+ const matched = await (0, import_fast_glob2.default)(globs, { cwd, absolute: true, onlyFiles: true });
2180
+ return [...new Set(matched)].sort();
2181
+ }
2182
+ async function computeInputsHash(config) {
2183
+ const hash = (0, import_node_crypto.createHash)("sha256");
2184
+ hash.update(`version:${VERSION}
2185
+ `);
2186
+ hash.update(`config:${serializeConfig(config)}
2187
+ `);
2188
+ const inputFiles = await discoverInputFiles(config);
2189
+ const cwd = config.codegen.cwd;
2190
+ for (const file of inputFiles) {
2191
+ const contents = await (0, import_promises11.readFile)(file, "utf8");
2192
+ hash.update(`file:${(0, import_node_path12.relative)(cwd, file)}
2193
+ `);
2194
+ hash.update(contents);
2195
+ hash.update("\n");
2196
+ }
2197
+ return hash.digest("hex");
2198
+ }
2199
+ async function readManifest(outDir) {
2200
+ try {
2201
+ const raw = await (0, import_promises11.readFile)((0, import_node_path12.join)(outDir, MANIFEST_FILE), "utf8");
2202
+ const parsed = JSON.parse(raw);
2203
+ if (!isManifestShape(parsed)) return null;
2204
+ return { version: parsed.version, hash: parsed.hash, files: parsed.files };
2205
+ } catch {
2206
+ return null;
2207
+ }
2208
+ }
2209
+ async function writeManifest(outDir, manifest) {
2210
+ await (0, import_promises11.writeFile)((0, import_node_path12.join)(outDir, MANIFEST_FILE), `${JSON.stringify(manifest, null, 2)}
2211
+ `, "utf8");
2212
+ }
2213
+ async function listOutputFiles(outDir) {
2214
+ const found = [];
2215
+ async function walk(dir) {
2216
+ const entries = await (0, import_promises11.readdir)(dir, { withFileTypes: true }).catch(() => []);
2217
+ for (const entry of entries) {
2218
+ const abs = (0, import_node_path12.join)(dir, entry.name);
2219
+ if (entry.isDirectory()) {
2220
+ await walk(abs);
2221
+ } else if (entry.isFile()) {
2222
+ const rel = (0, import_node_path12.relative)(outDir, abs);
2223
+ if (rel === MANIFEST_FILE || rel === LOCK_FILE) continue;
2224
+ found.push(rel);
2225
+ }
2226
+ }
2227
+ }
2228
+ await walk(outDir);
2229
+ return found.sort();
2230
+ }
2231
+ async function allOutputsExist(outDir, files) {
2232
+ const present = new Set(await listOutputFiles(outDir));
2233
+ return files.every((file) => present.has(file));
2234
+ }
2235
+ async function isManifestFresh(outDir, manifest, inputsHash) {
2236
+ if (manifest === null) return false;
2237
+ if (manifest.version !== VERSION) return false;
2238
+ if (manifest.hash !== inputsHash) return false;
2239
+ if (manifest.files.length === 0) return false;
2240
+ return allOutputsExist(outDir, manifest.files);
2241
+ }
2242
+
2146
2243
  // src/util/debug-log.ts
2147
2244
  var debugEnabled = false;
2148
2245
  function setCodegenDebug(enabled) {
@@ -2155,6 +2252,12 @@ function debugWarn(message) {
2155
2252
  // src/generate.ts
2156
2253
  async function generate(config, inputRoutes = []) {
2157
2254
  setCodegenDebug(config.debug);
2255
+ const inputsHash = await computeInputsHash(config);
2256
+ const manifest = await readManifest(config.codegen.outDir);
2257
+ if (await isManifestFresh(config.codegen.outDir, manifest, inputsHash)) {
2258
+ console.log(`[nestjs-codegen] ${config.codegen.outDir} up to date, skipped`);
2259
+ return;
2260
+ }
2158
2261
  const extensions = config.extensions ?? [];
2159
2262
  let routes = inputRoutes;
2160
2263
  const ctx = createExtensionContext(config, () => routes);
@@ -2211,21 +2314,27 @@ async function generate(config, inputRoutes = []) {
2211
2314
  if (extensions.length > 0) {
2212
2315
  const extraFiles = await collectEmittedFiles(extensions, ctx);
2213
2316
  for (const file of extraFiles) {
2214
- const dest = (0, import_node_path12.join)(config.codegen.outDir, file.path);
2215
- await (0, import_promises11.mkdir)((0, import_node_path12.dirname)(dest), { recursive: true });
2216
- await (0, import_promises11.writeFile)(dest, file.contents, "utf8");
2317
+ const dest = (0, import_node_path13.join)(config.codegen.outDir, file.path);
2318
+ await (0, import_promises12.mkdir)((0, import_node_path13.dirname)(dest), { recursive: true });
2319
+ await (0, import_promises12.writeFile)(dest, file.contents, "utf8");
2217
2320
  }
2218
2321
  }
2322
+ const outputFiles = await listOutputFiles(config.codegen.outDir);
2323
+ await writeManifest(config.codegen.outDir, {
2324
+ version: VERSION,
2325
+ hash: inputsHash,
2326
+ files: outputFiles
2327
+ });
2219
2328
  }
2220
2329
 
2221
2330
  // src/watch/watcher.ts
2222
- var import_promises14 = require("fs/promises");
2223
- var import_node_path16 = require("path");
2331
+ var import_promises15 = require("fs/promises");
2332
+ var import_node_path17 = require("path");
2224
2333
  var import_chokidar = __toESM(require("chokidar"), 1);
2225
2334
 
2226
2335
  // src/discovery/contracts-fast.ts
2227
- var import_node_path14 = require("path");
2228
- var import_fast_glob2 = __toESM(require("fast-glob"), 1);
2336
+ var import_node_path15 = require("path");
2337
+ var import_fast_glob3 = __toESM(require("fast-glob"), 1);
2229
2338
  var import_ts_morph9 = require("ts-morph");
2230
2339
 
2231
2340
  // src/discovery/dto-type-resolver.ts
@@ -2236,7 +2345,7 @@ var import_ts_morph4 = require("ts-morph");
2236
2345
 
2237
2346
  // src/discovery/type-ref-resolution.ts
2238
2347
  var import_node_fs = require("fs");
2239
- var import_node_path13 = require("path");
2348
+ var import_node_path14 = require("path");
2240
2349
  var import_ts_morph3 = require("ts-morph");
2241
2350
  var _EMPTY_CTX = { projectRoot: "", tsconfigPaths: null };
2242
2351
  var _ctxByProject = /* @__PURE__ */ new WeakMap();
@@ -2288,12 +2397,12 @@ function findTypeInFile(name, file) {
2288
2397
  }
2289
2398
  function resolveModuleSpecifier(moduleSpecifier, sourceFile, project) {
2290
2399
  if (moduleSpecifier.startsWith(".")) {
2291
- const dir = (0, import_node_path13.dirname)(sourceFile.getFilePath());
2400
+ const dir = (0, import_node_path14.dirname)(sourceFile.getFilePath());
2292
2401
  const noExt = moduleSpecifier.replace(/\.(js|ts)$/, "");
2293
2402
  return [
2294
- (0, import_node_path13.resolve)(dir, `${noExt}.ts`),
2295
- (0, import_node_path13.resolve)(dir, `${moduleSpecifier}.ts`),
2296
- (0, import_node_path13.resolve)(dir, moduleSpecifier, "index.ts")
2403
+ (0, import_node_path14.resolve)(dir, `${noExt}.ts`),
2404
+ (0, import_node_path14.resolve)(dir, `${moduleSpecifier}.ts`),
2405
+ (0, import_node_path14.resolve)(dir, moduleSpecifier, "index.ts")
2297
2406
  ];
2298
2407
  }
2299
2408
  const ctx = _ctxFor(project);
@@ -2314,8 +2423,8 @@ function resolveModuleSpecifier(moduleSpecifier, sourceFile, project) {
2314
2423
  const rest = moduleSpecifier.slice(prefix.length);
2315
2424
  const candidates = [];
2316
2425
  for (const mapping of mappings) {
2317
- const resolved = (0, import_node_path13.resolve)(baseUrl, mapping.replace("*", rest));
2318
- candidates.push(`${resolved}.ts`, (0, import_node_path13.resolve)(resolved, "index.ts"));
2426
+ const resolved = (0, import_node_path14.resolve)(baseUrl, mapping.replace("*", rest));
2427
+ candidates.push(`${resolved}.ts`, (0, import_node_path14.resolve)(resolved, "index.ts"));
2319
2428
  }
2320
2429
  dbg(" resolved candidates:", candidates);
2321
2430
  return candidates;
@@ -3987,7 +4096,7 @@ async function discoverContractsFast(opts) {
3987
4096
  const { cwd, glob, tsconfig } = opts;
3988
4097
  const tsconfigPath = resolveTsconfigPath(cwd, tsconfig);
3989
4098
  const project = createDiscoveryProject(tsconfigPath);
3990
- const files = await (0, import_fast_glob2.default)(glob, { cwd, absolute: true, onlyFiles: true });
4099
+ const files = await (0, import_fast_glob3.default)(glob, { cwd, absolute: true, onlyFiles: true });
3991
4100
  for (const f of files) {
3992
4101
  project.addSourceFileAtPath(f);
3993
4102
  }
@@ -3995,7 +4104,7 @@ async function discoverContractsFast(opts) {
3995
4104
  return extractAllRoutes(project);
3996
4105
  }
3997
4106
  function resolveTsconfigPath(cwd, tsconfig) {
3998
- return tsconfig ? (0, import_node_path14.resolve)(tsconfig) : (0, import_node_path14.join)(cwd, "tsconfig.json");
4107
+ return tsconfig ? (0, import_node_path15.resolve)(tsconfig) : (0, import_node_path15.join)(cwd, "tsconfig.json");
3999
4108
  }
4000
4109
  function createDiscoveryProject(tsconfigPath) {
4001
4110
  try {
@@ -4060,7 +4169,7 @@ var PersistentDiscovery = class _PersistentDiscovery {
4060
4169
  const project = createDiscoveryProject(tsconfigPath);
4061
4170
  bindDiscoveryContext(project, cwd, tsconfigPath);
4062
4171
  const instance = new _PersistentDiscovery(project, cwd, glob);
4063
- const files = await (0, import_fast_glob2.default)(glob, { cwd, absolute: true, onlyFiles: true });
4172
+ const files = await (0, import_fast_glob3.default)(glob, { cwd, absolute: true, onlyFiles: true });
4064
4173
  for (const f of files) {
4065
4174
  project.addSourceFileAtPath(f);
4066
4175
  instance.controllerPaths.add(f);
@@ -4081,7 +4190,7 @@ var PersistentDiscovery = class _PersistentDiscovery {
4081
4190
  async rediscover(changedPaths) {
4082
4191
  if (changedPaths) {
4083
4192
  for (const p of changedPaths) {
4084
- const abs = (0, import_node_path14.resolve)(p);
4193
+ const abs = (0, import_node_path15.resolve)(p);
4085
4194
  const sf = this.project.getSourceFile(abs);
4086
4195
  if (sf) {
4087
4196
  await sf.refreshFromFileSystem();
@@ -4089,7 +4198,7 @@ var PersistentDiscovery = class _PersistentDiscovery {
4089
4198
  }
4090
4199
  }
4091
4200
  const globbed = new Set(
4092
- await (0, import_fast_glob2.default)(this.glob, { cwd: this.cwd, absolute: true, onlyFiles: true })
4201
+ await (0, import_fast_glob3.default)(this.glob, { cwd: this.cwd, absolute: true, onlyFiles: true })
4093
4202
  );
4094
4203
  for (const f of globbed) {
4095
4204
  if (!this.controllerPaths.has(f)) {
@@ -4369,10 +4478,10 @@ function extractFromSourceFile(sourceFile, project) {
4369
4478
  }
4370
4479
 
4371
4480
  // src/watch/lock-file.ts
4372
- var import_promises12 = require("fs/promises");
4373
4481
  var import_promises13 = require("fs/promises");
4374
- var import_node_path15 = require("path");
4375
- var LOCK_FILE = ".watcher.lock";
4482
+ var import_promises14 = require("fs/promises");
4483
+ var import_node_path16 = require("path");
4484
+ var LOCK_FILE2 = ".watcher.lock";
4376
4485
  function isProcessAlive(pid) {
4377
4486
  try {
4378
4487
  process.kill(pid, 0);
@@ -4382,21 +4491,21 @@ function isProcessAlive(pid) {
4382
4491
  }
4383
4492
  }
4384
4493
  async function acquireLock(outDir) {
4385
- await (0, import_promises13.mkdir)(outDir, { recursive: true });
4386
- const lockPath = (0, import_node_path15.join)(outDir, LOCK_FILE);
4494
+ await (0, import_promises14.mkdir)(outDir, { recursive: true });
4495
+ const lockPath = (0, import_node_path16.join)(outDir, LOCK_FILE2);
4387
4496
  const lockData = { pid: process.pid, startedAt: (/* @__PURE__ */ new Date()).toISOString() };
4388
4497
  try {
4389
- const fd = await (0, import_promises12.open)(lockPath, "wx");
4498
+ const fd = await (0, import_promises13.open)(lockPath, "wx");
4390
4499
  await fd.writeFile(`${JSON.stringify(lockData, null, 2)}
4391
4500
  `, "utf8");
4392
4501
  await fd.close();
4393
4502
  } catch (err) {
4394
4503
  if (err.code === "EEXIST") {
4395
4504
  try {
4396
- const raw = await (0, import_promises13.readFile)(lockPath, "utf8");
4505
+ const raw = await (0, import_promises14.readFile)(lockPath, "utf8");
4397
4506
  const existing = JSON.parse(raw);
4398
4507
  if (isProcessAlive(existing.pid)) return null;
4399
- await (0, import_promises13.unlink)(lockPath);
4508
+ await (0, import_promises14.unlink)(lockPath);
4400
4509
  return acquireLock(outDir);
4401
4510
  } catch {
4402
4511
  return null;
@@ -4407,7 +4516,7 @@ async function acquireLock(outDir) {
4407
4516
  return {
4408
4517
  release: async () => {
4409
4518
  try {
4410
- await (0, import_promises13.unlink)(lockPath);
4519
+ await (0, import_promises14.unlink)(lockPath);
4411
4520
  } catch {
4412
4521
  }
4413
4522
  }
@@ -4418,12 +4527,12 @@ async function acquireLock(outDir) {
4418
4527
  var PAGES_DEBOUNCE_MS = 150;
4419
4528
  var NO_OP_WATCHER = { close: async () => {
4420
4529
  } };
4421
- async function watch(config, onChange) {
4530
+ async function watch(config, onChange, options = {}) {
4422
4531
  const lock = await acquireLock(config.codegen.outDir);
4423
4532
  if (lock === null) {
4424
4533
  let holderPid = "unknown";
4425
4534
  try {
4426
- const raw = await (0, import_promises14.readFile)((0, import_node_path16.join)(config.codegen.outDir, ".watcher.lock"), "utf8");
4535
+ const raw = await (0, import_promises15.readFile)((0, import_node_path17.join)(config.codegen.outDir, ".watcher.lock"), "utf8");
4427
4536
  const data = JSON.parse(raw);
4428
4537
  if (data.pid !== void 0) holderPid = String(data.pid);
4429
4538
  } catch {
@@ -4446,22 +4555,33 @@ async function watch(config, onChange) {
4446
4555
  }
4447
4556
  return discovery;
4448
4557
  }
4449
- try {
4450
- const initialRoutes = (await getDiscovery()).discover();
4451
- lastRoutes = initialRoutes;
4452
- await generate(config, initialRoutes);
4453
- } catch (err) {
4454
- console.warn(
4455
- `[nestjs-codegen] Initial route discovery failed, falling back to pages-only: ${err instanceof Error ? err.message : String(err)}`
4456
- );
4558
+ async function runInitialPass() {
4457
4559
  try {
4458
- await generate(config, lastRoutes);
4459
- } catch {
4560
+ const initialRoutes = (await getDiscovery()).discover();
4561
+ lastRoutes = initialRoutes;
4562
+ await generate(config, initialRoutes);
4563
+ } catch (err) {
4564
+ console.warn(
4565
+ `[nestjs-codegen] Initial route discovery failed, falling back to pages-only: ${err instanceof Error ? err.message : String(err)}`
4566
+ );
4567
+ try {
4568
+ await generate(config, lastRoutes);
4569
+ } catch {
4570
+ }
4460
4571
  }
4461
4572
  }
4573
+ if (options.deferInitialGenerate) {
4574
+ void runInitialPass().catch((err) => {
4575
+ console.warn(
4576
+ `[nestjs-codegen] Background initial generate failed: ${err instanceof Error ? err.message : String(err)}`
4577
+ );
4578
+ });
4579
+ } else {
4580
+ await runInitialPass();
4581
+ }
4462
4582
  let pagesDebounceTimer;
4463
4583
  const pagesGlob = config.pages?.glob ?? ".nestjs-codegen-no-pages";
4464
- const pagesWatcher = import_chokidar.default.watch((0, import_node_path16.join)(config.codegen.cwd, pagesGlob), {
4584
+ const pagesWatcher = import_chokidar.default.watch((0, import_node_path17.join)(config.codegen.cwd, pagesGlob), {
4465
4585
  ignoreInitial: true,
4466
4586
  persistent: true,
4467
4587
  awaitWriteFinish: { stabilityThreshold: 80, pollInterval: 20 }
@@ -4488,7 +4608,7 @@ async function watch(config, onChange) {
4488
4608
  pagesWatcher.on("unlink", schedulePagesRegenerate);
4489
4609
  let contractsDebounceTimer;
4490
4610
  const pendingChangedPaths = /* @__PURE__ */ new Set();
4491
- const contractsWatcher = import_chokidar.default.watch((0, import_node_path16.join)(config.codegen.cwd, config.contracts.glob), {
4611
+ const contractsWatcher = import_chokidar.default.watch((0, import_node_path17.join)(config.codegen.cwd, config.contracts.glob), {
4492
4612
  ignoreInitial: true,
4493
4613
  persistent: true,
4494
4614
  awaitWriteFinish: { stabilityThreshold: 80, pollInterval: 20 }
@@ -4518,7 +4638,7 @@ async function watch(config, onChange) {
4518
4638
  contractsWatcher.on("add", (p) => scheduleContractsRegenerate(p));
4519
4639
  contractsWatcher.on("change", (p) => scheduleContractsRegenerate(p));
4520
4640
  contractsWatcher.on("unlink", (p) => scheduleContractsRegenerate(p));
4521
- const formsWatcher = import_chokidar.default.watch((0, import_node_path16.join)(config.codegen.cwd, config.forms.watch), {
4641
+ const formsWatcher = import_chokidar.default.watch((0, import_node_path17.join)(config.codegen.cwd, config.forms.watch), {
4522
4642
  ignoreInitial: true,
4523
4643
  persistent: true,
4524
4644
  awaitWriteFinish: { stabilityThreshold: 80, pollInterval: 20 }
@@ -4628,7 +4748,7 @@ function createChainModuleRenderer(opts) {
4628
4748
  }
4629
4749
 
4630
4750
  // src/index.ts
4631
- var VERSION = "0.10.0";
4751
+ var VERSION = "0.12.0";
4632
4752
  // Annotate the CommonJS export names for ESM import in node:
4633
4753
  0 && (module.exports = {
4634
4754
  CodegenError,