@trackunit/migrations 0.2.157 → 0.2.159

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/CHANGELOG.md CHANGED
@@ -1,3 +1,11 @@
1
+ ## 0.2.159 (2026-11-13)
2
+
3
+ This was a version bump only for migrations to align it with other projects, there were no code changes.
4
+
5
+ ## 0.2.158 (2026-11-12)
6
+
7
+ This was a version bump only for migrations to align it with other projects, there were no code changes.
8
+
1
9
  ## 0.2.157 (2026-11-12)
2
10
 
3
11
  This was a version bump only for migrations to align it with other projects, there were no code changes.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"entry.js","sourceRoot":"","sources":["../../../../libs/migrations/migrations/entry.ts"],"names":[],"mappings":"","sourcesContent":["export {};\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trackunit/migrations",
3
- "version": "0.2.157",
3
+ "version": "0.2.159",
4
4
  "repository": "https://github.com/Trackunit/manager",
5
5
  "license": "SEE LICENSE IN LICENSE.txt",
6
6
  "engines": {
@@ -7,6 +7,7 @@ const path_1 = tslib_1.__importDefault(require("path"));
7
7
  const semver_1 = require("semver");
8
8
  const discover_packages_1 = require("../utils/discover-packages");
9
9
  const migrations_file_1 = require("../utils/migrations-file");
10
+ const release_policy_1 = require("../utils/release-policy/release-policy");
10
11
  const upgrade_dependencies_1 = require("../utils/upgrade-dependencies");
11
12
  /**
12
13
  * `pkg.version` is typed `string` but read from whatever package.json happens
@@ -213,7 +214,13 @@ const migrate = async (tree, options) => {
213
214
  // are owned by CI, so resolving them from the registry would fight the
214
215
  // release process. Migration discovery still covers them via libs/ and apps/.
215
216
  const inManagerWorkspace = (0, upgrade_dependencies_1.isManagerWorkspace)(tree);
216
- const upgrades = inManagerWorkspace ? [] : await (0, upgrade_dependencies_1.upgradeTrackunitDependencies)(tree, verbose);
217
+ // The npm release-age policy is read from the workspace root so the project's
218
+ // own .npmrc counts. It is only needed when versions are resolved from the
219
+ // registry, and an unreadable policy must stop the run before package.json is
220
+ // touched rather than fall back to an ungated lookup.
221
+ const upgrades = inManagerWorkspace
222
+ ? []
223
+ : await (0, upgrade_dependencies_1.upgradeTrackunitDependencies)(tree, verbose, process.versions.node, () => (0, release_policy_1.readReleasePolicy)(workspaceRoot));
217
224
  // Read before the install, because after it Nx has flushed and locked the
218
225
  // tree and this is the only handle on the workspace's existing state.
219
226
  const applied = (0, migrations_file_1.readAppliedMigrations)(tree);
@@ -0,0 +1 @@
1
+ {"version":3,"file":"generator.js","sourceRoot":"","sources":["../../../../../../libs/migrations/src/generators/migrate/generator.ts"],"names":[],"mappings":";;;;AAAA,uCASoB;AACpB,wDAAwB;AACxB,mCAA+B;AAC/B,kEAKoC;AACpC,8DAQkC;AAClC,2EAA2E;AAC3E,wEAMuC;AAsBvC;;;;;;;GAOG;AACH,MAAM,mBAAmB,GAAG,CAAC,OAA2B,EAAqB,EAAE,CAC7E,OAAO,KAAK,SAAS,IAAI,IAAA,cAAK,EAAC,OAAO,CAAC,KAAK,IAAI,CAAC;AAEnD,MAAM,oBAAoB,GAAG,CAAC,IAAU,EAAE,WAAmB,EAAsB,EAAE;IACnF,MAAM,WAAW,GAAG,IAAA,iBAAQ,EAAC,IAAI,EAAE,cAAc,CAAC,CAAC;IACnD,OAAO,WAAW,CAAC,YAAY,EAAE,CAAC,WAAW,CAAC,IAAI,WAAW,CAAC,eAAe,EAAE,CAAC,WAAW,CAAC,CAAC;AAC/F,CAAC,CAAC;AAEF,MAAM,gBAAgB,GAAG,CAAC,IAAU,EAAE,GAAsB,EAAQ,EAAE;IACpE,MAAM,UAAU,GAAG,oBAAoB,CAAC,IAAI,EAAE,GAAG,CAAC,IAAI,CAAC,CAAC;IACxD,IAAI,UAAU,KAAK,SAAS;QAAE,OAAO;IAErC,MAAM,cAAc,GAAG,IAAA,sCAAe,EAAC,UAAU,CAAC,CAAC;IACnD,IAAI,cAAc,KAAK,SAAS,IAAI,CAAC,mBAAmB,CAA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D,MAAM,GAAG,GAAG,IAAA,iCAAwB,EAAC,IAAA,6BAAoB,GAAE,CAAC,CAAC;YAC7D,eAAM,CAAC,KAAK,CACV,4GAA4G,GAAG,CAAC,OAAO,wCAAwC,CAChK,CAAC;YACF,MAAM,KAAK,CAAC;QACd,CAAC;QAED,yBAAyB,CAAC;YACxB,aAAa;YACb,OAAO;YACP,OAAO;YACP,iBAAiB,EAAE,SAAS;YAC5B,KAAK,EAAE,IAAA,wCAAsB,EAAC,aAAa,CAAC;SAC7C,CAAC,CAAC;IACL,CAAC,CAAC;AACJ,CAAC,CAAC;AA/EW,QAAA,OAAO,WA+ElB;AAEF,kBAAe,eAAO,CAAC","sourcesContent":["import {\n type GeneratorCallback,\n type Tree,\n detectPackageManager,\n getPackageManagerCommand,\n installPackagesTask,\n logger,\n readJson,\n updateJson,\n} from \"@nx/devkit\";\nimport path from \"path\";\nimport { valid } from \"semver\";\nimport {\n type DiscoveredPackage,\n compareVersions,\n discoverTrackunitPackages,\n loadMigrationsJson,\n} from \"../utils/discover-packages\";\nimport {\n type MigrationsFileWriter,\n type PendingMigration,\n TRACKUNIT_MIGRATIONS_FILE,\n fsMigrationsFileWriter,\n migrationId,\n readAppliedMigrations,\n treeMigrationsFileWriter,\n} from \"../utils/migrations-file\";\nimport { readReleasePolicy } from \"../utils/release-policy/release-policy\";\nimport {\n type DependencyUpgrade,\n applyVersionKeepingRange,\n isManagerWorkspace,\n pinnedVersionOf,\n upgradeTrackunitDependencies,\n} from \"../utils/upgrade-dependencies\";\n\ntype MigrateSchema = {\n readonly verbose?: boolean;\n readonly skipInstall?: boolean;\n};\n\ntype MigrationEntry = {\n /**\n * The release whose change this codemod prepares for. Used to order a\n * package's codemods and for nothing else -- see `collectMigrations`.\n */\n readonly version?: string;\n readonly description: string;\n readonly implementation: string;\n readonly cli?: string;\n};\n\ntype MigrationsJson = {\n readonly generators?: Record<string, MigrationEntry>;\n};\n\n/**\n * `pkg.version` is typed `string` but read from whatever package.json happens\n * to be on disk, so it is a compile-time claim rather than a runtime\n * guarantee, and `semver.compare` throws on anything it cannot parse. One\n * malformed version would otherwise abort the dependency pin for every other\n * package, in a walker deliberately built to survive broken packages rather\n * than crash on them.\n */\nconst isComparableVersion = (version: string | undefined): version is string =>\n version !== undefined && valid(version) !== null;\n\nconst getCurrentDepVersion = (tree: Tree, packageName: string): string | undefined => {\n const packageJson = readJson(tree, \"package.json\");\n return packageJson.dependencies?.[packageName] ?? packageJson.devDependencies?.[packageName];\n};\n\nconst updateDepVersion = (tree: Tree, pkg: DiscoveredPackage): void => {\n const currentDep = getCurrentDepVersion(tree, pkg.name);\n if (currentDep === undefined) return;\n\n const currentVersion = pinnedVersionOf(currentDep);\n if (currentVersion === undefined || !isComparableVersion(pkg.version)) {\n return;\n }\n\n if (compareVersions(pkg.version, currentVersion) <= 0) {\n return;\n }\n\n updateJson(tree, \"package.json\", json => {\n if (json.dependencies?.[pkg.name] !== undefined) {\n json.dependencies[pkg.name] = applyVersionKeepingRange(json.dependencies[pkg.name], pkg.version);\n }\n if (json.devDependencies?.[pkg.name] !== undefined) {\n json.devDependencies[pkg.name] = applyVersionKeepingRange(json.devDependencies[pkg.name], pkg.version);\n }\n return json;\n });\n\n logger.info(` Updated ${pkg.name} to ${pkg.version} in package.json`);\n};\n\n/**\n * Returns an implementation path that is relative to the workspace root when\n * the resolved path lives inside the workspace, so that\n * `trackunit-migrations.json` is portable between machines and checkouts.\n * Falls back to the absolute path for migrations sourced from outside the\n * workspace (e.g. node_modules in a non-default location).\n *\n * The root passed in is the tree's, which is also what `run-migrations`\n * resolves against. Relativising against the invocation directory instead\n * would store paths that only resolve when the second command happens to be\n * run from the same place.\n */\nconst portableImplementationPath = (absolutePath: string, workspaceRoot: string): string => {\n const relative = path.relative(workspaceRoot, absolutePath);\n if (relative === \"\" || relative.startsWith(\"..\") || path.isAbsolute(relative)) {\n return absolutePath;\n }\n return relative.split(path.sep).join(\"/\");\n};\n\n/**\n * Orders a package's codemods oldest change first.\n *\n * `version` is the release whose change a codemod prepares for, and it decides\n * order only. It is deliberately not a filter: a codemod is published only once\n * it is safe to run against the release shipping it, so everything a manifest\n * declares is applicable. `react-components@1.26.8` ships the `v2-0-0-*`\n * codemods for exactly that reason -- they migrate to APIs 1.26.8 already has,\n * which is the preparation a consumer needs *before* the major bump. Filtering\n * them out would withhold the work and leave the bump to break instead.\n *\n * An entry with no version, or one semver cannot read, keeps its manifest\n * position: authoring order is then the best signal available, and a malformed\n * version field must not silently reorder a package's codemods.\n */\nconst inExecutionOrder = (\n entries: ReadonlyArray<readonly [string, MigrationEntry]>\n): ReadonlyArray<readonly [string, MigrationEntry]> => {\n // Only the comparable entries take part in the sort, and they are written\n // back into the slots comparable entries already occupied. Comparing every\n // pair instead -- falling back to position whenever one side is unparseable\n // -- is not a total order: with 3.0.0, no-version, 1.5.0 you get\n // `a < b` and `b < c` by position but `a > c` by version, and `sort` may then\n // return anything. Both promises above break at once, and an unversioned\n // entry can even drift off its own index.\n const comparable = entries\n .map((entry, position) => ({ entry, position, version: entry[1].version }))\n .filter(\n (candidate): candidate is { entry: readonly [string, MigrationEntry]; position: number; version: string } =>\n isComparableVersion(candidate.version)\n );\n\n const sorted = [...comparable].sort(\n (left, right) => compareVersions(left.version, right.version) || left.position - right.position\n );\n\n const ordered = [...entries];\n comparable.forEach(({ position }, index) => {\n const replacement = sorted[index];\n if (replacement !== undefined) {\n ordered[position] = replacement.entry;\n }\n });\n\n return ordered;\n};\n\n/** Queues every migration in a package's manifest that has not already run. */\nconst collectMigrations = (\n pkg: DiscoveredPackage,\n applied: ReadonlySet<string>,\n migrationsJson: MigrationsJson,\n workspaceRoot: string\n): ReadonlyArray<PendingMigration> => {\n const pending: Array<PendingMigration> = [];\n const migrationsDir = path.dirname(pkg.migrationsJsonPath);\n\n for (const [name, entry] of inExecutionOrder(Object.entries(migrationsJson.generators ?? {}))) {\n if (applied.has(migrationId(pkg.name, name))) {\n continue;\n }\n\n const absoluteImpl = path.resolve(migrationsDir, entry.implementation);\n\n pending.push({\n package: pkg.name,\n name,\n version: entry.version,\n description: entry.description,\n implementation: portableImplementationPath(absoluteImpl, workspaceRoot),\n });\n }\n\n return pending;\n};\n\n// `--skipInstall` is the one case that cannot finish in a single run: the\n// migrations that ship inside the new versions are only discoverable once they\n// are on disk, and the caller has taken responsibility for putting them there.\nconst reportSkippedInstall = (upgrades: ReadonlyArray<DependencyUpgrade>): void => {\n const pmc = getPackageManagerCommand(detectPackageManager());\n\n logger.warn(\n `\\n${upgrades.length} dependency version(s) changed, so node_modules is now stale. Run:\\n ${pmc.install}\\n nx g @trackunit/migrations:migrate`\n );\n};\n\ntype MigrationCollection = {\n readonly workspaceRoot: string;\n readonly verbose: boolean;\n readonly applied: ReadonlySet<string>;\n /**\n * The tree, when it is still writable, so an installed version newer than the\n * declared one can be pinned back into package.json. Undefined after an\n * install: Nx has locked the tree by then, and package.json was just set\n * deliberately from the registry, so second-guessing it with whatever the\n * installer happened to resolve would fight that decision.\n */\n readonly pinDependenciesIn: Tree | undefined;\n readonly write: MigrationsFileWriter;\n};\n\n/**\n * Everything that depends on what is actually installed: discovery, the\n * already-applied filter, the summary, and the write.\n *\n * Split out because it has to run at two different points in the Nx generator\n * lifecycle. When no install is needed it runs inside the generator, against\n * the tree. When an install is needed it runs in the generator's callback,\n * after Nx has flushed and the install has refreshed node_modules -- which is\n * the only moment the new versions are visible at all.\n */\nconst collectAndWriteMigrations = (collection: MigrationCollection): void => {\n const packages = discoverTrackunitPackages(collection.workspaceRoot);\n\n logger.info(`Discovered ${packages.length} @trackunit/* package(s) with migrations`);\n\n const allPending: Array<PendingMigration> = [];\n\n for (const pkg of packages) {\n if (collection.pinDependenciesIn !== undefined) {\n updateDepVersion(collection.pinDependenciesIn, pkg);\n }\n\n const migrationsJson = loadMigrationsJson(pkg.migrationsJsonPath);\n\n // Discovery only yields a package whose manifest exists on disk, so\n // `undefined` means it is there and could not be parsed. Folding that into\n // \"declares nothing\" would drop whatever it declares without saying so,\n // leaving a short queue that looks complete -- the failure this library\n // keeps having to close.\n if (migrationsJson === undefined) {\n logger.warn(\n ` ${pkg.name}: could not read ${pkg.migrationsJsonPath}, so any migrations it declares are missing from this run.`\n );\n continue;\n }\n\n if (!migrationsJson.generators || Object.keys(migrationsJson.generators).length === 0) {\n if (collection.verbose) {\n logger.info(` ${pkg.name}: no migrations defined`);\n }\n continue;\n }\n\n const pending = collectMigrations(pkg, collection.applied, migrationsJson, collection.workspaceRoot);\n allPending.push(...pending);\n\n if (collection.verbose) {\n const total = Object.keys(migrationsJson.generators).length;\n logger.info(` ${pkg.name}: installed=${pkg.version}, ${total - pending.length} of ${total} already applied`);\n }\n\n if (pending.length > 0) {\n logger.info(`${pkg.name}@${pkg.version}: ${pending.length} pending migration(s)`);\n }\n }\n\n // The applied set is carried through untouched. `migrate` only ever proposes\n // work; `run-migrations` is what records that a migration ran, and only for\n // the ones that actually succeeded.\n collection.write({ appliedMigrations: [...collection.applied], migrations: allPending });\n\n if (allPending.length === 0) {\n logger.info(`No pending migrations. ${TRACKUNIT_MIGRATIONS_FILE} updated.`);\n } else {\n logger.info(`\\nWrote ${allPending.length} pending migration(s) to ${TRACKUNIT_MIGRATIONS_FILE}`);\n logger.info(\"Review the file, then run: nx g @trackunit/migrations:run-migrations\");\n }\n};\n\n/**\n * Step 1: Upgrades every `@trackunit/*` dependency to its latest published\n * version, discovers installed @trackunit packages, and writes\n * trackunit-migrations.json with pending migrations.\n *\n * The dependency upgrade is unconditional and independent of migrations:\n * a package without codemods still gets its version bumped.\n *\n * Usage: nx g @trackunit/migrations:migrate\n * Then: nx g @trackunit/migrations:run-migrations\n *\n * @param tree - The NX virtual file system for the workspace being migrated.\n * @param options - Generator options.\n * @returns {Promise<GeneratorCallback | undefined>} An install task when dependency versions changed, otherwise undefined.\n */\nexport const migrate = async (tree: Tree, options: MigrateSchema): Promise<GeneratorCallback | undefined> => {\n const verbose = options.verbose ?? false;\n\n // Nx does not normalise cwd for generators -- `getCwd()` exists in nx\n // precisely because it can be a subdirectory -- so the workspace root is the\n // tree's root and nothing here may read cwd instead. One root, used for all\n // three jobs: where node_modules is scanned, what implementation paths are\n // relative to, and where the file is written.\n //\n // Splitting them is worse than picking the wrong one, because the parts then\n // disagree and the run still reports success: from `apps/foo`, discovery\n // scans `apps/foo/node_modules` and queues nothing while the file lands at\n // the root looking like a clean workspace. `run-migrations` resolves stored\n // paths against this same root.\n const workspaceRoot = tree.root;\n\n // Inside manager the @trackunit libs are workspace projects whose versions\n // are owned by CI, so resolving them from the registry would fight the\n // release process. Migration discovery still covers them via libs/ and apps/.\n const inManagerWorkspace = isManagerWorkspace(tree);\n // The npm release-age policy is read from the workspace root so the project's\n // own .npmrc counts. It is only needed when versions are resolved from the\n // registry, and an unreadable policy must stop the run before package.json is\n // touched rather than fall back to an ungated lookup.\n const upgrades = inManagerWorkspace\n ? []\n : await upgradeTrackunitDependencies(tree, verbose, process.versions.node, () => readReleasePolicy(workspaceRoot));\n\n // Read before the install, because after it Nx has flushed and locked the\n // tree and this is the only handle on the workspace's existing state.\n const applied = readAppliedMigrations(tree);\n\n // Nothing changed, so node_modules already matches package.json and the\n // second stage can run here: through the tree, so Nx reports the change and\n // `--dry-run` suppresses it.\n if (upgrades.length === 0) {\n collectAndWriteMigrations({\n workspaceRoot,\n verbose,\n applied,\n pinDependenciesIn: tree,\n write: treeMigrationsFileWriter(tree),\n });\n return undefined;\n }\n\n if (options.skipInstall === true) {\n reportSkippedInstall(upgrades);\n return undefined;\n }\n\n // Versions changed, so anything discovered now would come from the packages\n // being replaced. Nothing is written here on purpose: a migrations file\n // produced before the install would assert a state that is about to stop\n // being true. Nx runs this callback after flushing package.json, which is the\n // first moment the new versions can be installed and therefore seen.\n return async () => {\n try {\n installPackagesTask(tree);\n } catch (error) {\n // The upgraded package.json is already flushed and is kept: it is the\n // work that succeeded. Rethrowing fails the run non-zero, which matters\n // because the migrations were never collected -- exiting 0 here would\n // report a workspace as migrated when discovery never ran.\n const pmc = getPackageManagerCommand(detectPackageManager());\n logger.error(\n `\\nThe install failed, so no migrations were collected. package.json keeps the upgraded versions. Run:\\n ${pmc.install}\\n nx g @trackunit/migrations:migrate`\n );\n throw error;\n }\n\n collectAndWriteMigrations({\n workspaceRoot,\n verbose,\n applied,\n pinDependenciesIn: undefined,\n write: fsMigrationsFileWriter(workspaceRoot),\n });\n };\n};\n\nexport default migrate;\n"]}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"generator.js","sourceRoot":"","sources":["../../../../../../libs/migrations/src/generators/run-migrations/generator.ts"],"names":[],"mappings":";;;;AAAA,uCAAsE;AACtE,2BAA8B;AAC9B,mCAAuC;AACvC,wDAAwB;AACxB,6BAAoC;AACpC,8DAKkC;AAMlC,MAAM,gBAAgB,GAAG,IAAA,sBAAa,EAAC,UAAU,CAAC,CAAC;AAEnD,MAAM,iBAAiB,GAA0B,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,CAAC,CAAC;AAExF,MAAM,MAAM,GAAG,CAAC,SAAiB,EAAW,EAAE;IAC5C,IAAI,CAAC;QACH,OAAO,IAAA,aAAQ,EAAC,SAAS,CAAC,CAAC,MAAM,EAAE,CAAC;IACtC,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,KAAK,CAAC;IACf,CAAC;AACH,CAAC,CAAC;AAEF;;;;;GAKG;AACH,MAAM,iBAAiB,GAAG,CAAC,QAAgB,EAAU,EAAE;IACrD,IAAI,MAAM,CAAC,QAAQ,CAAC;QAAE,OAAO,QAAQ,CAAC;IACtC,KAAK,MAAM,GAAG,IAAI,iBAAiB,EAAE,CAAC;QACpC,MAAM,SAAS,GAAG,GAAG,QAAQ,GAAG,GAAG,EAAE,CAAC;QACtC,IAAI,MAAM,CAAC,SAAS,CAAC;YAAE,OAAO,SAAS,CAAC;IAC1C,CAAC;IACD,KAAK,MAAM,GAAG,IAAI,iBAAiB,EAAE,CAAC;QACpC,MAAM,SAAS,GAAG,cAAI,CAAC,IAAI,C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qC,CAAC,CAAC;IACjE,IAAI,OAAO,GAAG,CAAC,EAAE,CAAC;QAChB,eAAM,CAAC,IAAI,CAAC,GAAG,OAAO,8EAA8E,CAAC,CAAC;IACxG,CAAC;IACD,IAAI,SAAS,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QACzB,eAAM,CAAC,IAAI,CACT,GAAG,SAAS,CAAC,MAAM,sCAAsC,2CAAyB,yEAAyE,CAC5J,CAAC;IACJ,CAAC;SAAM,CAAC;QACN,eAAM,CAAC,IAAI,CAAC,YAAY,2CAAyB,uCAAuC,CAAC,CAAC;IAC5F,CAAC;AACH,CAAC,CAAC;AAxEW,QAAA,aAAa,iBAwExB;AAEF,kBAAe,qBAAa,CAAC","sourcesContent":["import { type Tree, formatFiles, logger, readJson } from \"@nx/devkit\";\nimport { statSync } from \"fs\";\nimport { createRequire } from \"module\";\nimport path from \"path\";\nimport { pathToFileURL } from \"url\";\nimport {\n type PendingMigration,\n TRACKUNIT_MIGRATIONS_FILE,\n type TrackunitMigrationsFile,\n migrationId,\n} from \"../utils/migrations-file\";\n\ntype RunMigrationsSchema = {\n readonly verbose?: boolean;\n};\n\nconst requireMigration = createRequire(__filename);\n\nconst MODULE_EXTENSIONS: ReadonlyArray<string> = [\".js\", \".cjs\", \".mjs\", \".ts\", \".tsx\"];\n\nconst isFile = (candidate: string): boolean => {\n try {\n return statSync(candidate).isFile();\n } catch {\n return false;\n }\n};\n\n/**\n * `trackunit-migrations.json` stores implementation paths without a file\n * extension. Node's own resolution only probes `.js`/`.json`/`.node`, and\n * only for `require` (never for `import()`), so the stored path has to be\n * expanded to a concrete file before loading.\n */\nconst resolveModuleFile = (basePath: string): string => {\n if (isFile(basePath)) return basePath;\n for (const ext of MODULE_EXTENSIONS) {\n const candidate = `${basePath}${ext}`;\n if (isFile(candidate)) return candidate;\n }\n for (const ext of MODULE_EXTENSIONS) {\n const candidate = path.join(basePath, `index${ext}`);\n if (isFile(candidate)) return candidate;\n }\n return basePath;\n};\n\ntype TsConfigPaths = Record<string, ReadonlyArray<string>>;\n\ntype TsConfigLoadResult =\n | { readonly resultType: \"success\"; readonly absoluteBaseUrl: string; readonly paths: TsConfigPaths }\n | { readonly resultType: \"failed\" };\n\ntype TsConfigPathsModule = {\n readonly loadConfig: (cwd: string) => TsConfigLoadResult;\n readonly register: (options: { readonly baseUrl: string; readonly paths: TsConfigPaths }) => void;\n};\n\nlet typeScriptLoaderRegistered = false;\n\n/**\n * Running inside the manager monorepo discovers migrations as TypeScript\n * source, whose sibling imports are extensionless and whose `@trackunit/*`\n * imports resolve through workspace tsconfig path aliases. Nx's generator\n * runtime transpiles the explicitly-named generator files but does not add\n * a require hook that resolves either, so a real migration and everything\n * it imports must be loaded through a TypeScript register plus tsconfig\n * path resolution. Consumers run compiled `.js` and never reach this branch,\n * so the loaders stay dev-only dependencies of the manager monorepo.\n */\nconst ensureTypeScriptLoader = (workspaceRoot: string): void => {\n if (typeScriptLoaderRegistered) return;\n\n const tsConfigPaths: TsConfigPathsModule = requireMigration(\"tsconfig-paths\");\n const configResult = tsConfigPaths.loadConfig(path.join(workspaceRoot, \"tsconfig.base.json\"));\n if (configResult.resultType === \"success\") {\n tsConfigPaths.register({ baseUrl: configResult.absoluteBaseUrl, paths: configResult.paths });\n }\n\n requireMigration(\"@swc-node/register\");\n typeScriptLoaderRegistered = true;\n};\n\n/**\n * Resolves a stored implementation path. Relative paths in\n * `trackunit-migrations.json` are interpreted as relative to the workspace\n * root; absolute paths are used as-is. This keeps the on-disk file portable\n * between checkouts while preserving back-compat with absolute paths.\n *\n * The root is the tree's, matching what `migrate` relativised against. Using\n * the invocation directory would resolve to nothing whenever the two commands\n * are run from different places.\n */\nconst resolveImplementationPath = (storedPath: string, workspaceRoot: string): string =>\n path.isAbsolute(storedPath) ? storedPath : path.resolve(workspaceRoot, storedPath);\n\nconst isEsmRequireError = (error: unknown): boolean =>\n error instanceof Error && \"code\" in error && error.code === \"ERR_REQUIRE_ESM\";\n\n/**\n * Loads a migration module from an implementation path that is stored\n * without a file extension (see `portableImplementationPath` in the\n * `migrate` generator). The path is expanded to a concrete file, then\n * loaded with `require`, which resolves `.js` for the built/published\n * output consumers run and `.ts` for source when running inside the\n * manager monorepo (a TypeScript loader is registered on demand for that\n * case). Native `import()` performs no extension resolution and cannot load\n * these paths at all; it is kept only as a fallback for genuine ESM output\n * (rare — the migrations build emits CommonJS).\n */\nconst loadMigrationModule = async (resolvedPath: string, workspaceRoot: string): Promise<Record<string, unknown>> => {\n const file = resolveModuleFile(resolvedPath);\n\n if (file.endsWith(\".ts\") || file.endsWith(\".tsx\")) {\n ensureTypeScriptLoader(workspaceRoot);\n }\n\n try {\n return requireMigration(file);\n } catch (error) {\n if (!isEsmRequireError(error)) throw error;\n return import(pathToFileURL(file).href);\n }\n};\n\nconst runMigration = async (tree: Tree, migration: PendingMigration, verbose: boolean): Promise<boolean> => {\n try {\n const resolvedPath = resolveImplementationPath(migration.implementation, tree.root);\n const migrationModule = await loadMigrationModule(resolvedPath, tree.root);\n const migrationFn = migrationModule.default ?? migrationModule;\n\n if (typeof migrationFn !== \"function\") {\n logger.warn(` \"${migration.name}\" does not export a function, skipping`);\n return false;\n }\n\n if (verbose) {\n logger.info(` Running: ${migration.name} from ${migration.package}`);\n }\n\n migrationFn(tree);\n return true;\n } catch (error) {\n logger.error(` Failed \"${migration.name}\": ${error instanceof Error ? error.message : String(error)}`);\n return false;\n }\n};\n\n/**\n * Step 2: Reads trackunit-migrations.json and executes each pending\n * migration. Successful migrations are removed from the pending list and\n * recorded in `appliedMigrations`, which is what stops `migrate` offering\n * them again. Failures stay in the list and are not recorded, so they remain\n * retryable on the next run without having to go through `migrate` again.\n *\n * Usage: nx g @trackunit/migrations:run-migrations\n */\nexport const runMigrations = async (tree: Tree, options: RunMigrationsSchema): Promise<void> => {\n if (!tree.exists(TRACKUNIT_MIGRATIONS_FILE)) {\n logger.error(`${TRACKUNIT_MIGRATIONS_FILE} not found. Run \"nx g @trackunit/migrations:migrate\" first.`);\n return;\n }\n\n const file: TrackunitMigrationsFile = readJson(tree, TRACKUNIT_MIGRATIONS_FILE);\n\n if (file.migrations.length === 0) {\n logger.info(\"No pending migrations to run.\");\n return;\n }\n\n logger.info(`Running ${file.migrations.length} migration(s)...\\n`);\n\n let succeeded = 0;\n let skipped = 0;\n const remaining: Array<PendingMigration> = [];\n // A Set, because a migration that failed on an earlier run and succeeds now\n // is still in the pending list but may already be recorded.\n const applied = new Set(file.appliedMigrations);\n // The queue can name the same codemod twice -- a merge, a hand-edit, or the\n // legacy-format path that re-queues everything. Being in `applied` is the\n // same situation one run earlier.\n const attempted = new Set<string>();\n\n for (const migration of file.migrations) {\n const id = migrationId(migration.package, migration.name);\n\n // Executing a codemod a second time is not a no-op in general: a rename\n // that also rewrites an import list, or anything that appends, corrupts\n // source on the second pass, and `migrate` will not re-queue it afterwards\n // so nothing says it happened. The recorded set is only worth keeping if it\n // is enforced here.\n if (applied.has(id) || attempted.has(id)) {\n const reason = applied.has(id) ? \"already applied\" : \"listed more than once in this run\";\n logger.info(`${migration.package}: ${migration.name} - skipped, ${reason}`);\n skipped++;\n continue;\n }\n\n attempted.add(id);\n logger.info(`${migration.package}: ${migration.name} - ${migration.description}`);\n\n const ok = await runMigration(tree, migration, options.verbose ?? false);\n if (ok) {\n succeeded++;\n applied.add(id);\n } else {\n remaining.push(migration);\n }\n }\n\n const updated: TrackunitMigrationsFile = {\n appliedMigrations: [...applied],\n migrations: remaining,\n };\n tree.write(TRACKUNIT_MIGRATIONS_FILE, JSON.stringify(updated, null, 2));\n\n await formatFiles(tree);\n\n logger.info(`\\n${succeeded} migration(s) applied successfully.`);\n if (skipped > 0) {\n logger.info(`${skipped} migration(s) skipped as already applied, and removed from the pending list.`);\n }\n if (remaining.length > 0) {\n logger.warn(\n `${remaining.length} migration(s) failed and remain in ${TRACKUNIT_MIGRATIONS_FILE}. Fix the cause and re-run \"nx g @trackunit/migrations:run-migrations\".`\n );\n } else {\n logger.info(`\\nCommit ${TRACKUNIT_MIGRATIONS_FILE} to record which migrations have run.`);\n }\n};\n\nexport default runMigrations;\n"]}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"discover-packages.js","sourceRoot":"","sources":["../../../../../../libs/migrations/src/generators/utils/discover-packages.ts"],"names":[],"mappings":";;;;AAAA,uCAAoC;AACpC,2BAAsF;AACtF,wDAAwB;AAcxB,MAAM,eAAe,GAAG,CAAC,WAAmB,EAAyC,EAAE;IACrF,IAAI,CAAC;QACH,MAAM,GAAG,GAAG,IAAA,iBAAY,EAAC,WAAW,EAAE,OAAO,CAAC,CAAC;QAC/C,OAAO,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IACzB,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,SAAS,CAAC;IACnB,CAAC;AACH,CAAC,CAAC;AAEF,MAAM,qBAAqB,GAAG,CAAC,MAAc,EAAE,OAAkC,EAAsB,EAAE;IACvG,MAAM,UAAU,GAAG,OAAO,CAAC,UAAU,CAAC;IACtC,IAAI,UAAU,KAAK,SAAS;QAAE,OAAO,SAAS,CAAC;IAE/C,MAAM,cAAc,GAAG,OAAO,UAAU,KAAK,QAAQ,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,UAAU,CAAC,UAAU,CAAC;IAC3F,MAAM,QAAQ,GAAG,cAAI,CAAC,OAAO,CAAC,MAAM,EAAE,cAAc,CAAC,CAAC;IAEtD,OAAO,IAAA,eAAU,EAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,SAAS,CAAC;AACrD,CAAC,CAAC;AAEF,iGAAiG;AACjG,yDAAyD;AAClD,MAAM,kBAAkB,GAAG,CAChC,cAAsB,EAQV,EAAE;IACd,IAAI,CAAC;QACH,MAAM,GAAG,GAAG,IAAA,iBAAY,EAAC,cAAc,EAAE,OAAO,CAAC,CAAC;QAClD,OAAO,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IACzB,CAAC;IAAC,MAAM,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;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,WAAW,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;YAC3B,OAAO;QACT,CAAC;QAED,IAAI,SAAS,GAAG,IAAI,CAAC;QACrB,KAAK,IAAI,KAAK,GAAG,CAAC,EAAE,KAAK,GAAG,KAAK,EAAE,KAAK,IAAI,CAAC;YAAE,SAAS,GAAG,cAAI,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;QAEnF,IAAI,cAAI,CAAC,QAAQ,CAAC,SAAS,CAAC,KAAK,cAAc;YAAE,eAAe,CAAC,SAAS,CAAC,CAAC;IAC9E,CAAC;IAED,eAAe,CAAC,eAAe,CAAC,CAAC;IAEjC,IAAI,iBAAiB,CAAC,GAAG,CAAC,EAAE,CAAC;QAC3B,QAAQ,CAAC,IAAI,CAAC,GAAG,IAAA,0CAAkC,EAAC,GAAG,CAAC,CAAC,CAAC;IAC5D,CAAC;IAED,MAAM,MAAM,GAAG,IAAI,GAAG,EAA6B,CAAC;IACpD,KAAK,MAAM,GAAG,IAAI,QAAQ,EAAE,CAAC;QAC3B,MAAM,QAAQ,GAAG,MAAM,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QACtC,IAAI,CAAC,QAAQ,IAAI,IAAA,uBAAe,EAAC,GAAG,CAAC,OAAO,EAAE,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC;YACpE,MAAM,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;QAC5B,CAAC;IACH,CAAC;IAED,OAAO,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC;AAC9B,CAAC,CAAC;AAtFW,QAAA,yBAAyB,6BAsFpC","sourcesContent":["import { logger } from \"@nx/devkit\";\nimport { type Dirent, existsSync, readdirSync, readFileSync, realpathSync } from \"fs\";\nimport path from \"path\";\n\ntype PackageJsonWithMigrations = {\n readonly name?: string;\n readonly version: string;\n readonly migrations?: string | { readonly migrations: string };\n};\n\nexport type DiscoveredPackage = {\n readonly name: string;\n readonly version: string;\n readonly migrationsJsonPath: string;\n};\n\nconst readPackageJson = (pkgJsonPath: string): PackageJsonWithMigrations | undefined => {\n try {\n const raw = readFileSync(pkgJsonPath, \"utf-8\");\n return JSON.parse(raw);\n } catch {\n return undefined;\n }\n};\n\nconst resolveMigrationsPath = (pkgDir: string, pkgJson: PackageJsonWithMigrations): string | undefined => {\n const migrations = pkgJson.migrations;\n if (migrations === undefined) return undefined;\n\n const migrationsFile = typeof migrations === \"string\" ? migrations : migrations.migrations;\n const resolved = path.resolve(pkgDir, migrationsFile);\n\n return existsSync(resolved) ? resolved : undefined;\n};\n\n/** Compares two semver strings, returning negative/zero/positive like Array.sort comparators. */\n/** Loads and parses a migrations.json file from disk. */\nexport const loadMigrationsJson = (\n migrationsPath: string\n):\n | {\n readonly generators?: Record<\n string,\n { readonly version: string; readonly description: string; readonly implementation: string }\n >;\n }\n | undefined => {\n try {\n const raw = readFileSync(migrationsPath, \"utf-8\");\n return JSON.parse(raw);\n } catch {\n return undefined;\n }\n};\n\nimport { compare } from \"semver\";\n/**\n * Compare two semver strings, returning negative/zero/positive like Array.sort comparators.\n *\n * @param a - The first semver string to compare.\n * @param b - The second semver string to compare.\n * @returns {number} A negative number if a < b, 0 if a === b, and a positive number if a > b.\n */\nexport const compareVersions = (a: string, b: string): number => compare(a, b);\n\n// Swallowing a failed directory read shrinks the discovered package set, which\n// `migrate` then reports as \"no pending migrations\" -- indistinguishable from\n// the green-run-no-codemods symptom this walker exists to fix. Warning keeps\n// the walk crash-proof while making a truncated result visible.\nconst warnSkipped = (dir: string, error: unknown): void => {\n const reason = error instanceof Error ? error.message : String(error);\n logger.warn(\n `Skipped \"${dir}\" while discovering @trackunit packages: ${reason}. Discovered migrations may be incomplete.`\n );\n};\n\n// `existsSync` only says the entry resolved, not that it can be listed: an\n// unreadable store directory or a path that turns out to be a file still\n// throws. Every listing in this module goes through here so one bad directory\n// cannot abort discovery.\nconst readDirEntries = (dir: string): ReadonlyArray<Dirent> => {\n try {\n return readdirSync(dir, { withFileTypes: true });\n } catch (error) {\n warnSkipped(dir, error);\n return [];\n }\n};\n\nconst scanScopeDir = (scopeDir: string): ReadonlyArray<DiscoveredPackage> => {\n if (!existsSync(scopeDir)) return [];\n\n const entries = readDirEntries(scopeDir);\n const found: Array<DiscoveredPackage> = [];\n\n for (const entry of entries) {\n if (!entry.isDirectory() && !entry.isSymbolicLink()) continue;\n\n const pkgDir = path.join(scopeDir, entry.name);\n const pkgJsonPath = path.join(pkgDir, \"package.json\");\n const pkgJson = readPackageJson(pkgJsonPath);\n\n if (!pkgJson) continue;\n\n const migrationsJsonPath = resolveMigrationsPath(pkgDir, pkgJson);\n if (migrationsJsonPath) {\n found.push({\n name: pkgJson.name ?? `@trackunit/${entry.name}`,\n version: pkgJson.version,\n migrationsJsonPath,\n });\n }\n }\n\n return found;\n};\n\nconst MANAGER_REPO_PACKAGE_NAME = \"@trackunit/manager\";\nconst WORKSPACE_SCAN_ROOTS: ReadonlyArray<string> = [\"libs\", \"apps\"];\n\n// Levels to climb from a resolved package directory to reach the\n// `node_modules` holding it: `<store>/node_modules/name` versus\n// `<store>/node_modules/@scope/name`.\nconst UNSCOPED_DEPTH = 1;\nconst SCOPED_DEPTH = 2;\n\nconst isManagerMonorepo = (cwd: string): boolean => {\n const rootPkgJson = readPackageJson(path.join(cwd, \"package.json\"));\n return rootPkgJson?.name === MANAGER_REPO_PACKAGE_NAME;\n};\n\nconst walkForPackageJsons = (rootDir: string, onPackageJson: (pkgJsonPath: string) => void): void => {\n if (!existsSync(rootDir)) return;\n\n const stack: Array<string> = [rootDir];\n while (stack.length > 0) {\n const dir = stack.pop();\n if (dir === undefined) continue;\n\n for (const entry of readDirEntries(dir)) {\n if (entry.name === \"node_modules\" || entry.name.startsWith(\".\")) continue;\n const entryPath = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n stack.push(entryPath);\n } else if (entry.isFile() && entry.name === \"package.json\") {\n onPackageJson(entryPath);\n }\n }\n }\n};\n\n/**\n * In-monorepo fallback discovery: scans libs/ and apps/ for\n * package.json files whose name starts with \"@trackunit/\" and that\n * declare a \"migrations\" field. Used only when the engine is run\n * inside the manager monorepo (root package.json name is\n * \"@trackunit/manager\"), since internal workspace projects are not\n * symlinked under node_modules/@trackunit/* by Yarn.\n */\nexport const discoverWorkspaceTrackunitPackages = (cwd: string = process.cwd()): ReadonlyArray<DiscoveredPackage> => {\n const found: Array<DiscoveredPackage> = [];\n\n for (const root of WORKSPACE_SCAN_ROOTS) {\n walkForPackageJsons(path.join(cwd, root), pkgJsonPath => {\n const pkgJson = readPackageJson(pkgJsonPath);\n if (!pkgJson?.name || !pkgJson.name.startsWith(\"@trackunit/\")) return;\n\n const migrationsJsonPath = resolveMigrationsPath(path.dirname(pkgJsonPath), pkgJson);\n if (!migrationsJsonPath) return;\n\n found.push({\n name: pkgJson.name,\n version: pkgJson.version,\n migrationsJsonPath,\n });\n });\n }\n\n return found;\n};\n\n/**\n * Recursively walks node_modules directories looking for @trackunit/*\n * packages that declare a \"migrations\" field. Scans root node_modules\n * and nested node_modules inside every package. When the same package\n * is found at multiple levels, the highest semver version is kept.\n *\n * Works with hoisted layouts (npm, yarn) and with the isolated layouts\n * where dependencies are symlinks into a content store (Yarn\n * `nodeLinker: pnpm`, pnpm, bun), including pnpm with hoisting disabled,\n * where a package's dependencies are siblings of it inside the store\n * rather than nested beneath it.\n *\n * When invoked inside the manager monorepo (root package.json name\n * is \"@trackunit/manager\"), additionally scans libs/ and apps/ for\n * workspace packages that ship migrations, since those are not\n * linked under node_modules/@trackunit/.\n *\n * @param cwd - Workspace root to scan; defaults to the current directory\n * @returns {ReadonlyArray<DiscoveredPackage>} One entry per package name, at its highest discovered version\n */\nexport const discoverTrackunitPackages = (cwd: string = process.cwd()): ReadonlyArray<DiscoveredPackage> => {\n const rootNodeModules = path.resolve(cwd, \"node_modules\");\n const allFound: Array<DiscoveredPackage> = [];\n const visited = new Set<string>();\n\n const walkNodeModules = (nodeModulesDir: string): void => {\n if (!existsSync(nodeModulesDir)) return;\n\n // Isolated layouts (Yarn `nodeLinker: pnpm`, pnpm, bun) symlink every\n // dependency into a content store, so a mutual dependency produces\n // endless distinct logical paths pointing at the same real directories.\n // `path.resolve` normalises but does not follow symlinks, so it cannot\n // recognise the repeat and the walk grows the path until the OS rejects\n // it. Canonicalising through the real path is what makes this terminate.\n let canonical: string;\n try {\n canonical = realpathSync(nodeModulesDir);\n } catch (error) {\n warnSkipped(nodeModulesDir, error);\n return;\n }\n if (visited.has(canonical)) return;\n visited.add(canonical);\n\n const trackunitScope = path.join(nodeModulesDir, \"@trackunit\");\n allFound.push(...scanScopeDir(trackunitScope));\n\n for (const entry of readDirEntries(nodeModulesDir)) {\n if (!entry.isDirectory() && !entry.isSymbolicLink()) continue;\n\n const entryPath = path.join(nodeModulesDir, entry.name);\n\n if (entry.name.startsWith(\"@\")) {\n for (const scopeEntry of readDirEntries(entryPath)) {\n if (!scopeEntry.isDirectory() && !scopeEntry.isSymbolicLink()) continue;\n const scopedPkgDir = path.join(entryPath, scopeEntry.name);\n walkNodeModules(path.join(scopedPkgDir, \"node_modules\"));\n walkStoreSiblingsOf(scopedPkgDir, SCOPED_DEPTH);\n }\n } else {\n walkNodeModules(path.join(entryPath, \"node_modules\"));\n walkStoreSiblingsOf(entryPath, UNSCOPED_DEPTH);\n }\n }\n };\n\n /**\n * pnpm with hoisting disabled places a package's dependencies *alongside*\n * it inside the store rather than nested beneath it, so probing only\n * `<entry>/node_modules` never reaches a @trackunit package that is purely\n * transitive. Resolving the entry and walking the store `node_modules` that\n * contains it reaches those siblings. In hoisted layouts this resolves back\n * to a directory the walk has already scanned, so `visited` makes it free.\n */\n function walkStoreSiblingsOf(pkgDir: string, depth: number): void {\n if (!existsSync(pkgDir)) return;\n\n let real: string;\n try {\n real = realpathSync(pkgDir);\n } catch (error) {\n warnSkipped(pkgDir, error);\n return;\n }\n\n let candidate = real;\n for (let level = 0; level < depth; level += 1) candidate = path.dirname(candidate);\n\n if (path.basename(candidate) === \"node_modules\") walkNodeModules(candidate);\n }\n\n walkNodeModules(rootNodeModules);\n\n if (isManagerMonorepo(cwd)) {\n allFound.push(...discoverWorkspaceTrackunitPackages(cwd));\n }\n\n const byName = new Map<string, DiscoveredPackage>();\n for (const pkg of allFound) {\n const existing = byName.get(pkg.name);\n if (!existing || compareVersions(pkg.version, existing.version) > 0) {\n byName.set(pkg.name, pkg);\n }\n }\n\n return [...byName.values()];\n};\n"]}
@@ -0,0 +1,26 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.hasErrorCode = exports.errorCode = void 0;
4
+ /**
5
+ * The `code` of an error as Node and pacote report it (`ENOENT`, `ETARGET`, `ECONNRESET`, ...).
6
+ *
7
+ * @param error - Anything that was thrown.
8
+ * @returns {string | number | undefined} The code, or undefined when the value has none.
9
+ */
10
+ const errorCode = (error) => {
11
+ if (typeof error !== "object" || error === null || !("code" in error)) {
12
+ return undefined;
13
+ }
14
+ return typeof error.code === "string" || typeof error.code === "number" ? error.code : undefined;
15
+ };
16
+ exports.errorCode = errorCode;
17
+ /**
18
+ * Whether a thrown value carries a given error code.
19
+ *
20
+ * @param error - Anything that was thrown.
21
+ * @param code - The code to look for.
22
+ * @returns {boolean} True when the value's `code` is exactly `code`.
23
+ */
24
+ const hasErrorCode = (error, code) => (0, exports.errorCode)(error) === code;
25
+ exports.hasErrorCode = hasErrorCode;
26
+ //# sourceMappingURL=error-code.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"error-code.js","sourceRoot":"","sources":["../../../../../../../libs/migrations/src/generators/utils/error-code/error-code.ts"],"names":[],"mappings":";;;AAAA;;;;;GAKG;AACI,MAAM,SAAS,GAAG,CAAC,KAAc,EAA+B,EAAE;IACvE,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,CAAC,MAAM,IAAI,KAAK,CAAC,EAAE,CAAC;QACtE,OAAO,SAAS,CAAC;IACnB,CAAC;IACD,OAAO,OAAO,KAAK,CAAC,IAAI,KAAK,QAAQ,IAAI,OAAO,KAAK,CAAC,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC;AACnG,CAAC,CAAC;AALW,QAAA,SAAS,aAKpB;AAEF;;;;;;GAMG;AACI,MAAM,YAAY,GAAG,CAAC,KAAc,EAAE,IAAqB,EAAW,EAAE,CAAC,IAAA,iBAAS,EAAC,KAAK,CAAC,KAAK,IAAI,CAAC;AAA7F,QAAA,YAAY,gBAAiF","sourcesContent":["/**\n * The `code` of an error as Node and pacote report it (`ENOENT`, `ETARGET`, `ECONNRESET`, ...).\n *\n * @param error - Anything that was thrown.\n * @returns {string | number | undefined} The code, or undefined when the value has none.\n */\nexport const errorCode = (error: unknown): string | number | undefined => {\n if (typeof error !== \"object\" || error === null || !(\"code\" in error)) {\n return undefined;\n }\n return typeof error.code === \"string\" || typeof error.code === \"number\" ? error.code : undefined;\n};\n\n/**\n * Whether a thrown value carries a given error code.\n *\n * @param error - Anything that was thrown.\n * @param code - The code to look for.\n * @returns {boolean} True when the value's `code` is exactly `code`.\n */\nexport const hasErrorCode = (error: unknown, code: string | number): boolean => errorCode(error) === code;\n"]}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"migrations-file.js","sourceRoot":"","sources":["../../../../../../libs/migrations/src/generators/utils/migrations-file.ts"],"names":[],"mappings":";;;;AAAA,uCAAyD;AACzD,2BAAmC;AACnC,wDAAwB;AAEX,QAAA,yBAAyB,GAAG,2BAA2B,CAAC;AAoBrE;;;;;GAKG;AACI,MAAM,WAAW,GAAG,CAAC,WAAmB,EAAE,IAAY,EAAU,EAAE,CAAC,GAAG,WAAW,IAAI,IAAI,EAAE,CAAC;AAAtF,QAAA,WAAW,eAA2E;AAEnG;;;;;;GAMG;AACH,MAAM,oBAAoB,GAAG,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C,CAAC,CAAC;AAH9C,QAAA,wBAAwB,4BAGsB;AAE3D;;;;;GAKG;AACI,MAAM,sBAAsB,GACjC,CAAC,aAAqB,EAAwB,EAAE,CAChD,IAAI,CAAC,EAAE,CACL,IAAA,kBAAa,EAAC,cAAI,CAAC,IAAI,CAAC,aAAa,EAAE,iCAAyB,CAAC,EAAE,SAAS,CAAC,IAAI,CAAC,EAAE,OAAO,CAAC,CAAC;AAHpF,QAAA,sBAAsB,0BAG8D","sourcesContent":["import { type Tree, logger, readJson } from \"@nx/devkit\";\nimport { writeFileSync } from \"fs\";\nimport path from \"path\";\n\nexport const TRACKUNIT_MIGRATIONS_FILE = \"trackunit-migrations.json\";\n\nexport type PendingMigration = {\n readonly package: string;\n readonly name: string;\n /**\n * The release whose change this codemod prepares for. Recorded so the queued\n * order is explicable on inspection; it is not read back, and never decides\n * whether a migration runs.\n */\n readonly version?: string;\n readonly description: string;\n readonly implementation: string;\n};\n\nexport type TrackunitMigrationsFile = {\n readonly appliedMigrations: ReadonlyArray<string>;\n readonly migrations: ReadonlyArray<PendingMigration>;\n};\n\n/**\n * A migration's identity is the package it ships in plus its key in that\n * package's `migrations.json`. Nothing is parsed back out of this string --\n * the only operation is set membership -- so the separator just has to be a\n * character npm forbids in a package name, which `:` is.\n */\nexport const migrationId = (packageName: string, name: string): string => `${packageName}:${name}`;\n\n/**\n * A file that exists but cannot be read is not the same as no file at all, and\n * treating it as one loses the record twice over: this run re-queues\n * everything, then rewrites the file from what it just found, so the previous\n * contents are gone. Version control is the way back, which only helps a\n * developer who has been told.\n */\nconst warnRecordUnreadable = (): void => {\n logger.warn(\n `${TRACKUNIT_MIGRATIONS_FILE} exists but its record of applied migrations could not be read. Every migration is queued again, and this run overwrites the file -- recover the previous contents from version control if you need them. Migrations already applied are no-ops.`\n );\n};\n\n/**\n * Reads the set of migrations that have already run.\n *\n * A migration has run or it has not, and that is answered by identity. The\n * predecessor of this file instead tracked a semver high-water mark per package\n * and filtered on `entry.version > lastMigrated`, which could only ever be as\n * accurate as a hand-written tag and could be advanced past codemods that never\n * ran -- so a skipped migration stayed skipped for good.\n *\n * `migrations.json` still carries `version`, but only to order a package's\n * codemods. Nothing about whether a migration runs is read from it.\n */\nexport const readAppliedMigrations = (tree: Tree): ReadonlySet<string> => {\n if (!tree.exists(TRACKUNIT_MIGRATIONS_FILE)) return new Set();\n\n try {\n const file: Partial<TrackunitMigrationsFile> & { readonly migratedVersions?: unknown } = readJson(\n tree,\n TRACKUNIT_MIGRATIONS_FILE\n );\n\n if (Array.isArray(file.appliedMigrations)) {\n return new Set(file.appliedMigrations);\n }\n\n // The version-based format cannot be translated: it recorded how far each\n // package had got, never which codemods produced that. Saying so is the\n // only honest option, because the alternative -- guessing -- is what makes\n // a migration silently skipped forever.\n if (file.migratedVersions !== undefined) {\n logger.warn(\n `${TRACKUNIT_MIGRATIONS_FILE} uses the old per-package version format, which cannot say which migrations ran. Every migration is queued again; review the list before running it. Migrations already applied are no-ops.`\n );\n return new Set();\n }\n\n warnRecordUnreadable();\n return new Set();\n } catch {\n warnRecordUnreadable();\n return new Set();\n }\n};\n\n/**\n * `migrate` writes this file from two places that cannot share a mechanism.\n * When no install is needed it writes through the Nx `Tree`, so the change is\n * reported and honours `--dry-run`. When an install is needed the write has to\n * happen after it, and by then Nx has flushed and locked the tree\n * (`FsTree.assertUnlocked`), so the only route left is `fs`.\n *\n * Both go through this module so the serialisation cannot drift between them:\n * `run-migrations` parses whatever lands here, and the format is already\n * committed in consumer repos.\n */\nexport type MigrationsFileWriter = (file: TrackunitMigrationsFile) => void;\n\nconst serialise = (file: TrackunitMigrationsFile): string => JSON.stringify(file, null, 2);\n\n/**\n * Writes through the Nx tree, so Nx reports the change and `--dry-run` suppresses it.\n *\n * @param tree - The NX virtual file system for the workspace being migrated.\n * @returns {MigrationsFileWriter} A writer that records the file as a tree change.\n */\nexport const treeMigrationsFileWriter =\n (tree: Tree): MigrationsFileWriter =>\n file =>\n tree.write(TRACKUNIT_MIGRATIONS_FILE, serialise(file));\n\n/**\n * Writes straight to disk, for use after Nx has flushed and locked the tree.\n *\n * @param workspaceRoot - Absolute path the file is written relative to.\n * @returns {MigrationsFileWriter} A writer that writes the file with `fs`.\n */\nexport const fsMigrationsFileWriter =\n (workspaceRoot: string): MigrationsFileWriter =>\n file =>\n writeFileSync(path.join(workspaceRoot, TRACKUNIT_MIGRATIONS_FILE), serialise(file), \"utf-8\");\n"]}
@@ -0,0 +1,162 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.readReleasePolicy = exports.npmConfigGet = exports.NpmNotFoundError = void 0;
4
+ const devkit_1 = require("@nx/devkit");
5
+ const child_process_1 = require("child_process");
6
+ const fs_1 = require("fs");
7
+ const error_code_1 = require("../error-code/error-code");
8
+ const DAY_MS = 24 * 60 * 60 * 1000;
9
+ /** npm could not be started at all, as opposed to npm running and failing. */
10
+ class NpmNotFoundError extends Error {
11
+ /** Creates the error with a fixed message. */
12
+ constructor() {
13
+ super("npm was not found on PATH");
14
+ this.name = "NpmNotFoundError";
15
+ }
16
+ }
17
+ exports.NpmNotFoundError = NpmNotFoundError;
18
+ /**
19
+ * Reads npm config values by running one `npm config get` for all of `keys` in `cwd`.
20
+ *
21
+ * On Windows npm is `npm.cmd`, which a bare `execFile` cannot start (it reports
22
+ * ENOENT), so the command goes through the shell there -- as one string, since
23
+ * Node deprecates passing arguments alongside `shell: true` and the keys are
24
+ * always this module's own constants.
25
+ *
26
+ * @param keys - The npm config keys, e.g. `["min-release-age", "before"]`.
27
+ * @param cwd - The directory npm resolves the project `.npmrc` from.
28
+ * @returns {Promise<string>} What npm printed: one `key=value` line per key.
29
+ * @throws {NpmNotFoundError} When npm cannot be started because it is not installed.
30
+ */
31
+ const npmConfigGet = (keys, cwd) => new Promise((resolve, reject) => {
32
+ const onDone = (error, stdout, stderr) => {
33
+ if (!error) {
34
+ resolve(stdout);
35
+ return;
36
+ }
37
+ // ENOENT is also what a missing working directory produces, and reading that
38
+ // as "no npm" would silently drop the policy over a bad path.
39
+ if ((0, error_code_1.hasErrorCode)(error, "ENOENT")) {
40
+ reject((0, fs_1.existsSync)(cwd) ? new NpmNotFoundError() : new Error(`The workspace directory ${cwd} does not exist`));
41
+ return;
42
+ }
43
+ if (process.platform === "win32" && /not recognized/i.test(stderr)) {
44
+ reject(new NpmNotFoundError());
45
+ return;
46
+ }
47
+ reject(error);
48
+ };
49
+ if (process.platform === "win32") {
50
+ (0, child_process_1.execFile)(`npm config get ${keys.join(" ")}`, { cwd, shell: true }, onDone);
51
+ }
52
+ else {
53
+ (0, child_process_1.execFile)("npm", ["config", "get", ...keys], { cwd }, onDone);
54
+ }
55
+ });
56
+ exports.npmConfigGet = npmConfigGet;
57
+ const MIN_RELEASE_AGE = "min-release-age";
58
+ const BEFORE = "before";
59
+ // What `npm config get` prints after the `=` for "not set": `null` for a key with
60
+ // a null default (`before`, and `min-release-age` on an npm that has it),
61
+ // `undefined` for a key this npm does not know (an npm that predates
62
+ // `min-release-age`), and nothing at all for an explicitly empty value.
63
+ const UNSET_VALUES = new Set(["", "null", "undefined"]);
64
+ const isUnset = (value) => UNSET_VALUES.has(value);
65
+ const invalidSetting = (setting, value, expected) => new Error(`Cannot read your npm release-age policy: ${setting} is "${value}", which is not ${expected}. ` +
66
+ `Fix or remove ${setting} in your .npmrc (run \`npm config get ${setting}\` to see where it comes from), then run this generator again. ` +
67
+ `The generator will not continue without knowing the policy, because that could install versions your policy forbids.`);
68
+ const policyFromMinReleaseAge = (value, now) => {
69
+ if (isUnset(value))
70
+ return undefined;
71
+ if (!/^\d+(\.\d+)?$/.test(value)) {
72
+ throw invalidSetting(MIN_RELEASE_AGE, value, "a non-negative number of days");
73
+ }
74
+ const days = Number(value);
75
+ if (days === 0)
76
+ return undefined;
77
+ return {
78
+ cutoff: new Date(now.getTime() - days * DAY_MS),
79
+ source: "min-release-age",
80
+ setting: `min-release-age=${value}`,
81
+ };
82
+ };
83
+ // `npm config get before` prints the Date npm parsed, as a local-time string
84
+ // (`Thu Oct 01 2026 02:00:00 GMT+0200 (...)`), and prints `Invalid Date` -- with
85
+ // exit code 0 -- for a value it could not read. npm does not expose the text the
86
+ // developer wrote, so the error can only report what npm reports.
87
+ const policyFromBefore = (value) => {
88
+ if (isUnset(value))
89
+ return undefined;
90
+ const cutoff = new Date(value);
91
+ if (Number.isNaN(cutoff.getTime())) {
92
+ throw invalidSetting(BEFORE, value, "a valid date");
93
+ }
94
+ return { cutoff, source: "before", setting: `before=${cutoff.toISOString()}` };
95
+ };
96
+ // `npm config get a b` prints one `key=value` line per key. Parsed by key rather
97
+ // than by position, and split on the first `=` only, so neither the order nor a
98
+ // value that itself contains `=` matters. Lines without an `=` are ignored.
99
+ const parseConfigOutput = (output) => {
100
+ const config = new Map();
101
+ for (const line of output.split(/\r?\n/)) {
102
+ const separator = line.indexOf("=");
103
+ if (separator === -1)
104
+ continue;
105
+ config.set(line.slice(0, separator).trim(), line.slice(separator + 1).trim());
106
+ }
107
+ return config;
108
+ };
109
+ // Fail closed: a key with no line means the output is not what this parser
110
+ // knows, and guessing "unset" could install versions the policy forbids.
111
+ const valueOf = (config, key, output) => {
112
+ const value = config.get(key);
113
+ if (value === undefined) {
114
+ throw new Error(`Cannot read your npm release-age policy: \`npm config get\` printed no value for ${key} (it printed "${output.trim()}"). ` +
115
+ `The generator will not continue without knowing the policy, because that could install versions your policy forbids.`);
116
+ }
117
+ return value;
118
+ };
119
+ /**
120
+ * Reads the npm release-age policy that applies to the workspace, so the
121
+ * generator never selects a version npm would then refuse to install.
122
+ *
123
+ * `npx` does not forward npm settings to the processes it starts, and the
124
+ * policy can live in the project, user or global `.npmrc`, so the only reliable
125
+ * source is npm itself asked from the workspace root -- which is what makes the
126
+ * project's own `.npmrc` count. Both settings come from one `npm config get`.
127
+ *
128
+ * `min-release-age` and `before` are both cut-offs; when both are set the
129
+ * stricter (earlier) one applies. That is deliberate, and at least as strict as
130
+ * npm: npm does not take the stricter, it only derives `before` from
131
+ * `min-release-age` when `before` is not itself set at that config level, so an
132
+ * explicit `before` wins by precedence rather than by being earlier.
133
+ *
134
+ * @param workspaceRoot - The workspace root, used as npm's working directory.
135
+ * @param readConfig - Reads npm config values as `key=value` lines; defaults to running `npm config get`.
136
+ * @param now - The reference time `min-release-age` counts back from.
137
+ * @returns {Promise<ReleasePolicy | undefined>} The effective policy, or undefined when none is set (or npm is not installed).
138
+ * @throws {Error} When a policy value cannot be understood, or npm fails in a way that leaves the policy unknown.
139
+ */
140
+ const readReleasePolicy = async (workspaceRoot, readConfig = exports.npmConfigGet, now = new Date()) => {
141
+ let output;
142
+ try {
143
+ output = await readConfig([MIN_RELEASE_AGE, BEFORE], workspaceRoot);
144
+ }
145
+ catch (error) {
146
+ if (error instanceof NpmNotFoundError) {
147
+ devkit_1.logger.warn("npm was not found on PATH, so no npm release-age policy was applied.");
148
+ return undefined;
149
+ }
150
+ const reason = error instanceof Error ? error.message : String(error);
151
+ throw new Error(`Cannot read your npm release-age policy because \`npm config get\` failed: ${reason}. ` +
152
+ `The generator will not continue without knowing the policy, because that could install versions your policy forbids.`);
153
+ }
154
+ const config = parseConfigOutput(output);
155
+ const candidates = [
156
+ policyFromMinReleaseAge(valueOf(config, MIN_RELEASE_AGE, output), now),
157
+ policyFromBefore(valueOf(config, BEFORE, output)),
158
+ ].filter((policy) => policy !== undefined);
159
+ return candidates.reduce((strictest, candidate) => (strictest === undefined || candidate.cutoff < strictest.cutoff ? candidate : strictest), undefined);
160
+ };
161
+ exports.readReleasePolicy = readReleasePolicy;
162
+ //# sourceMappingURL=release-policy.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"release-policy.js","sourceRoot":"","sources":["../../../../../../../libs/migrations/src/generators/utils/release-policy/release-policy.ts"],"names":[],"mappings":";;;AAAA,uCAAoC;AACpC,iDAAyC;AACzC,2BAAgC;AAChC,yDAAwD;AAExD,MAAM,MAAM,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AA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,CAAC;KAClD,CAAC,MAAM,CAAC,CAAC,MAAM,EAA2B,EAAE,CAAC,MAAM,KAAK,SAAS,CAAC,CAAC;IAEpE,OAAO,UAAU,CAAC,MAAM,CACtB,CAAC,SAAS,EAAE,SAAS,EAAE,EAAE,CAAC,CAAC,SAAS,KAAK,SAAS,IAAI,SAAS,CAAC,MAAM,GAAG,SAAS,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,EAClH,SAAS,CACV,CAAC;AACJ,CAAC,CAAC;AA9BW,QAAA,iBAAiB,qBA8B5B","sourcesContent":["import { logger } from \"@nx/devkit\";\nimport { execFile } from \"child_process\";\nimport { existsSync } from \"fs\";\nimport { hasErrorCode } from \"../error-code/error-code\";\n\nconst DAY_MS = 24 * 60 * 60 * 1000;\n\n/**\n * The newest publish time the developer's npm configuration allows a dependency\n * to have, and the setting that decided it, so a failure can name what to adjust.\n */\nexport type ReleasePolicy = {\n readonly cutoff: Date;\n /** Which npm setting decided the cut-off, so advice can be specific to it. */\n readonly source: \"min-release-age\" | \"before\";\n /** The binding setting for messages, e.g. `min-release-age=7` or `before=2026-10-01T00:00:00.000Z`. */\n readonly setting: string;\n};\n\n/**\n * Reads npm config values as `npm config get <keys...>` prints them: one\n * `key=value` line per key. Injectable so specs never depend on the real npm\n * configuration of the machine they run on.\n */\nexport type NpmConfigReader = (keys: ReadonlyArray<string>, cwd: string) => Promise<string>;\n\n/** npm could not be started at all, as opposed to npm running and failing. */\nexport class NpmNotFoundError extends Error {\n /** Creates the error with a fixed message. */\n public constructor() {\n super(\"npm was not found on PATH\");\n this.name = \"NpmNotFoundError\";\n }\n}\n\n/**\n * Reads npm config values by running one `npm config get` for all of `keys` in `cwd`.\n *\n * On Windows npm is `npm.cmd`, which a bare `execFile` cannot start (it reports\n * ENOENT), so the command goes through the shell there -- as one string, since\n * Node deprecates passing arguments alongside `shell: true` and the keys are\n * always this module's own constants.\n *\n * @param keys - The npm config keys, e.g. `[\"min-release-age\", \"before\"]`.\n * @param cwd - The directory npm resolves the project `.npmrc` from.\n * @returns {Promise<string>} What npm printed: one `key=value` line per key.\n * @throws {NpmNotFoundError} When npm cannot be started because it is not installed.\n */\nexport const npmConfigGet: NpmConfigReader = (keys, cwd) =>\n new Promise((resolve, reject) => {\n const onDone = (error: Error | null, stdout: string, stderr: string): void => {\n if (!error) {\n resolve(stdout);\n return;\n }\n // ENOENT is also what a missing working directory produces, and reading that\n // as \"no npm\" would silently drop the policy over a bad path.\n if (hasErrorCode(error, \"ENOENT\")) {\n reject(existsSync(cwd) ? new NpmNotFoundError() : new Error(`The workspace directory ${cwd} does not exist`));\n return;\n }\n if (process.platform === \"win32\" && /not recognized/i.test(stderr)) {\n reject(new NpmNotFoundError());\n return;\n }\n reject(error);\n };\n\n if (process.platform === \"win32\") {\n execFile(`npm config get ${keys.join(\" \")}`, { cwd, shell: true }, onDone);\n } else {\n execFile(\"npm\", [\"config\", \"get\", ...keys], { cwd }, onDone);\n }\n });\n\nconst MIN_RELEASE_AGE = \"min-release-age\";\nconst BEFORE = \"before\";\n\n// What `npm config get` prints after the `=` for \"not set\": `null` for a key with\n// a null default (`before`, and `min-release-age` on an npm that has it),\n// `undefined` for a key this npm does not know (an npm that predates\n// `min-release-age`), and nothing at all for an explicitly empty value.\nconst UNSET_VALUES: ReadonlySet<string> = new Set([\"\", \"null\", \"undefined\"]);\n\nconst isUnset = (value: string): boolean => UNSET_VALUES.has(value);\n\nconst invalidSetting = (setting: string, value: string, expected: string): Error =>\n new Error(\n `Cannot read your npm release-age policy: ${setting} is \"${value}\", which is not ${expected}. ` +\n `Fix or remove ${setting} in your .npmrc (run \\`npm config get ${setting}\\` to see where it comes from), then run this generator again. ` +\n `The generator will not continue without knowing the policy, because that could install versions your policy forbids.`\n );\n\nconst policyFromMinReleaseAge = (value: string, now: Date): ReleasePolicy | undefined => {\n if (isUnset(value)) return undefined;\n if (!/^\\d+(\\.\\d+)?$/.test(value)) {\n throw invalidSetting(MIN_RELEASE_AGE, value, \"a non-negative number of days\");\n }\n\n const days = Number(value);\n if (days === 0) return undefined;\n\n return {\n cutoff: new Date(now.getTime() - days * DAY_MS),\n source: \"min-release-age\",\n setting: `min-release-age=${value}`,\n };\n};\n\n// `npm config get before` prints the Date npm parsed, as a local-time string\n// (`Thu Oct 01 2026 02:00:00 GMT+0200 (...)`), and prints `Invalid Date` -- with\n// exit code 0 -- for a value it could not read. npm does not expose the text the\n// developer wrote, so the error can only report what npm reports.\nconst policyFromBefore = (value: string): ReleasePolicy | undefined => {\n if (isUnset(value)) return undefined;\n\n const cutoff = new Date(value);\n if (Number.isNaN(cutoff.getTime())) {\n throw invalidSetting(BEFORE, value, \"a valid date\");\n }\n\n return { cutoff, source: \"before\", setting: `before=${cutoff.toISOString()}` };\n};\n\n// `npm config get a b` prints one `key=value` line per key. Parsed by key rather\n// than by position, and split on the first `=` only, so neither the order nor a\n// value that itself contains `=` matters. Lines without an `=` are ignored.\nconst parseConfigOutput = (output: string): ReadonlyMap<string, string> => {\n const config = new Map<string, string>();\n for (const line of output.split(/\\r?\\n/)) {\n const separator = line.indexOf(\"=\");\n if (separator === -1) continue;\n config.set(line.slice(0, separator).trim(), line.slice(separator + 1).trim());\n }\n return config;\n};\n\n// Fail closed: a key with no line means the output is not what this parser\n// knows, and guessing \"unset\" could install versions the policy forbids.\nconst valueOf = (config: ReadonlyMap<string, string>, key: string, output: string): string => {\n const value = config.get(key);\n if (value === undefined) {\n throw new Error(\n `Cannot read your npm release-age policy: \\`npm config get\\` printed no value for ${key} (it printed \"${output.trim()}\"). ` +\n `The generator will not continue without knowing the policy, because that could install versions your policy forbids.`\n );\n }\n return value;\n};\n\n/**\n * Reads the npm release-age policy that applies to the workspace, so the\n * generator never selects a version npm would then refuse to install.\n *\n * `npx` does not forward npm settings to the processes it starts, and the\n * policy can live in the project, user or global `.npmrc`, so the only reliable\n * source is npm itself asked from the workspace root -- which is what makes the\n * project's own `.npmrc` count. Both settings come from one `npm config get`.\n *\n * `min-release-age` and `before` are both cut-offs; when both are set the\n * stricter (earlier) one applies. That is deliberate, and at least as strict as\n * npm: npm does not take the stricter, it only derives `before` from\n * `min-release-age` when `before` is not itself set at that config level, so an\n * explicit `before` wins by precedence rather than by being earlier.\n *\n * @param workspaceRoot - The workspace root, used as npm's working directory.\n * @param readConfig - Reads npm config values as `key=value` lines; defaults to running `npm config get`.\n * @param now - The reference time `min-release-age` counts back from.\n * @returns {Promise<ReleasePolicy | undefined>} The effective policy, or undefined when none is set (or npm is not installed).\n * @throws {Error} When a policy value cannot be understood, or npm fails in a way that leaves the policy unknown.\n */\nexport const readReleasePolicy = async (\n workspaceRoot: string,\n readConfig: NpmConfigReader = npmConfigGet,\n now: Date = new Date()\n): Promise<ReleasePolicy | undefined> => {\n let output: string;\n try {\n output = await readConfig([MIN_RELEASE_AGE, BEFORE], workspaceRoot);\n } catch (error) {\n if (error instanceof NpmNotFoundError) {\n logger.warn(\"npm was not found on PATH, so no npm release-age policy was applied.\");\n return undefined;\n }\n const reason = error instanceof Error ? error.message : String(error);\n throw new Error(\n `Cannot read your npm release-age policy because \\`npm config get\\` failed: ${reason}. ` +\n `The generator will not continue without knowing the policy, because that could install versions your policy forbids.`\n );\n }\n\n const config = parseConfigOutput(output);\n const candidates = [\n policyFromMinReleaseAge(valueOf(config, MIN_RELEASE_AGE, output), now),\n policyFromBefore(valueOf(config, BEFORE, output)),\n ].filter((policy): policy is ReleasePolicy => policy !== undefined);\n\n return candidates.reduce<ReleasePolicy | undefined>(\n (strictest, candidate) => (strictest === undefined || candidate.cutoff < strictest.cutoff ? candidate : strictest),\n undefined\n );\n};\n"]}
@@ -5,6 +5,7 @@ const tslib_1 = require("tslib");
5
5
  const devkit_1 = require("@nx/devkit");
6
6
  const pacote = tslib_1.__importStar(require("pacote"));
7
7
  const semver_1 = require("semver");
8
+ const error_code_1 = require("./error-code/error-code");
8
9
  const TRACKUNIT_SCOPE = "@trackunit/";
9
10
  const MANAGER_REPO_PACKAGE_NAME = "@trackunit/manager";
10
11
  const DEPENDENCY_FIELDS = ["dependencies", "devDependencies"];
@@ -95,7 +96,45 @@ const collectTrackunitDependencies = (tree) => {
95
96
  return found;
96
97
  };
97
98
  exports.collectTrackunitDependencies = collectTrackunitDependencies;
98
- const registryOptions = () => process.env.TU_NPM_REGISTRY ? { registry: process.env.TU_NPM_REGISTRY } : undefined;
99
+ /**
100
+ * The registry override, the one place pacote options start from. No override leaves the options out entirely.
101
+ * A release-age policy's cut-off goes in as `before` where a manifest is picked, so pacote only considers
102
+ * versions the policy allows.
103
+ */
104
+ const registryOverride = () => {
105
+ const registry = process.env.TU_NPM_REGISTRY;
106
+ return registry ? { registry } : undefined;
107
+ };
108
+ const toValidDate = (value) => {
109
+ if (typeof value !== "string")
110
+ return undefined;
111
+ const date = new Date(value);
112
+ return Number.isNaN(date.getTime()) ? undefined : date;
113
+ };
114
+ /**
115
+ * What a packument reports about when a version was published, as a date, or `undefined` when it does not say or
116
+ * says something that is not a time. A version whose publish time is unknown cannot be shown to be within a
117
+ * policy, and cannot be blamed on one either, so callers read `undefined` as "cannot tell" and decide which way
118
+ * that fails.
119
+ *
120
+ * Only the full packument, which a release-age policy asks for, carries publish times.
121
+ */
122
+ const publishedAt = (packument, version) => toValidDate(packument.time?.[version]);
123
+ // A version whose publish time is missing cannot be shown to be within the
124
+ // policy, and the one thing this note must never do is name a version the policy
125
+ // forbids -- so unknown counts as outside.
126
+ const isPublishedWithinPolicy = (packument, version, policy) => {
127
+ const published = publishedAt(packument, version);
128
+ return published !== undefined && published <= policy.cutoff;
129
+ };
130
+ // The opposite question: is there evidence that the policy forbids this
131
+ // version? Only a known publish time after the cut-off counts. A missing time,
132
+ // or no packument at all, is "cannot tell", and the policy is never blamed on a
133
+ // guess -- that would send developers to loosen their .npmrc for nothing.
134
+ const isPublishedAfterCutoff = (packument, version, policy) => {
135
+ const published = publishedAt(packument, version);
136
+ return published !== undefined && published > policy.cutoff;
137
+ };
99
138
  /**
100
139
  * `pacote.manifest` already applies npm-pick-manifest's engine filter against
101
140
  * the running Node version, so the version it hands back can be far behind the
@@ -111,28 +150,39 @@ const registryOptions = () => process.env.TU_NPM_REGISTRY ? { registry: process.
111
150
  * deliberately left untagged, for an upgrade it was never a candidate for on
112
151
  * any Node version.
113
152
  *
153
+ * Under a release-age policy the `latest` tag can point at a version published
154
+ * after the cut-off. Naming it would tell the developer about a version their
155
+ * own policy forbids, so it is only named when its publish time shows it is
156
+ * within the cut-off.
157
+ *
114
158
  * Only an unsatisfied `engines.node` counts. A malformed range is treated as
115
159
  * "cannot tell" rather than "blocked", so a bad `engines` field never invents
116
160
  * a cap, and a prerelease tagged `latest` is not what a consumer is missing
117
161
  * out on.
118
162
  */
119
- const findEngineCap = async (name, reached, nodeVersion) => {
120
- if ((0, semver_1.valid)(reached) === null || (0, semver_1.valid)(nodeVersion) === null)
121
- return undefined;
122
- let packument;
163
+ const fetchPackument = async (name, policy) => {
123
164
  try {
124
- packument = await pacote.packument(name, registryOptions());
165
+ // Publish times live only in the full packument, so a policy has to ask for it.
166
+ return policy === undefined
167
+ ? await pacote.packument(name, registryOverride())
168
+ : await pacote.packument(name, { ...registryOverride(), fullMetadata: true });
125
169
  }
126
170
  catch {
127
171
  // The upgrade itself already succeeded; this lookup only annotates it, so a
128
172
  // failure here must stay silent rather than imply no cap exists.
129
173
  return undefined;
130
174
  }
175
+ };
176
+ const findEngineCap = (packument, reached, nodeVersion, policy) => {
177
+ if (packument === undefined || (0, semver_1.valid)(reached) === null || (0, semver_1.valid)(nodeVersion) === null)
178
+ return undefined;
131
179
  const latest = packument["dist-tags"]?.latest;
132
180
  if (latest === undefined || (0, semver_1.valid)(latest) === null)
133
181
  return undefined;
134
182
  if ((0, semver_1.prerelease)(latest) !== null || !(0, semver_1.gt)(latest, reached))
135
183
  return undefined;
184
+ if (policy !== undefined && !isPublishedWithinPolicy(packument, latest, policy))
185
+ return undefined;
136
186
  const requiredNode = packument.versions?.[latest]?.engines?.node;
137
187
  if (requiredNode === undefined || (0, semver_1.validRange)(requiredNode) === null)
138
188
  return undefined;
@@ -140,19 +190,95 @@ const findEngineCap = async (name, reached, nodeVersion) => {
140
190
  return undefined;
141
191
  return { reached, skipped: latest, requiredNode };
142
192
  };
193
+ // Codes pacote reports when nothing could be fetched at all, as opposed to the
194
+ // registry answering with something unusable.
195
+ const NETWORK_ERROR_CODES = new Set([
196
+ "ECONNREFUSED",
197
+ "ECONNRESET",
198
+ "ENOTFOUND",
199
+ "ETIMEDOUT",
200
+ "EAI_AGAIN",
201
+ "EHOSTUNREACH",
202
+ "ENETUNREACH",
203
+ "FETCH_ERROR",
204
+ ]);
205
+ // npm-pick-manifest reports a policy that leaves nothing to pick as
206
+ // ENOVERSIONS (every version is newer than `before`) or ETARGET (versions exist
207
+ // but none match). Without a policy neither says anything about it, so they are
208
+ // only read as policy exhaustion when one is set.
209
+ const POLICY_EXCLUSION_CODES = new Set(["ENOVERSIONS", "ETARGET"]);
210
+ // Under a policy these codes are taken at face value, with no second lookup to
211
+ // confirm: a package declared in a working package.json always has published
212
+ // versions, so "nothing to pick" can only mean they are all newer than `before`.
213
+ const classifyFailure = (error, policy) => {
214
+ const reason = error instanceof Error ? error.message : String(error);
215
+ const code = String((0, error_code_1.errorCode)(error) ?? "");
216
+ if (policy !== undefined && POLICY_EXCLUSION_CODES.has(code))
217
+ return { kind: "policy-excluded", reason };
218
+ if (NETWORK_ERROR_CODES.has(code))
219
+ return { kind: "unreachable", reason };
220
+ return { kind: "failed", reason };
221
+ };
222
+ const adjustAdvice = (policy) => policy.source === "before" ? "Move before to a later date or remove it" : "Lower min-release-age or remove it";
223
+ /** The registry's answer cannot be shown to respect the policy, which must stop the run, not skip a package. */
224
+ class PolicyViolationError extends Error {
225
+ /**
226
+ * Creates the error.
227
+ *
228
+ * @param message - What could not be verified, and against which setting.
229
+ */
230
+ constructor(message) {
231
+ super(message);
232
+ this.name = "PolicyViolationError";
233
+ }
234
+ }
235
+ const assertPublishedWithinPolicy = (name, manifest, policy) => {
236
+ // `_time` is declared by the module augmentation at the top of this file.
237
+ const published = toValidDate(manifest._time);
238
+ const label = `${name}@${manifest.version}`;
239
+ if (published === undefined) {
240
+ throw new PolicyViolationError(`The registry did not report when ${label} was published, so it cannot be checked against your npm release-age policy (${policy.setting}). ` +
241
+ `Nothing was upgraded. Check that your registry serves publish times -- a mirror or proxy may strip them.`);
242
+ }
243
+ if (published > policy.cutoff) {
244
+ throw new PolicyViolationError(`${label} was published ${published.toISOString()}, after the cut-off ${policy.cutoff.toISOString()} of your npm release-age policy (${policy.setting}), ` +
245
+ `so it was not installed. Nothing was upgraded.`);
246
+ }
247
+ };
143
248
  // A single unreachable or unpublished package must not abort the upgrade of the
144
249
  // other 30, so a failed lookup degrades to "leave this one alone" and says so.
145
- const resolveLatestVersion = async (name) => {
250
+ // There is deliberately no retry without the policy: a lookup that fails under a
251
+ // policy stays failed rather than quietly picking a version the policy forbids.
252
+ const resolveLatestVersion = async (name, policy) => {
146
253
  try {
147
- const manifest = await pacote.manifest(name, registryOptions());
148
- return manifest.version;
254
+ if (policy === undefined) {
255
+ const manifest = await pacote.manifest(name, registryOverride());
256
+ return { kind: "resolved", version: manifest.version };
257
+ }
258
+ const picked = await pacote.manifest(name, { ...registryOverride(), before: policy.cutoff });
259
+ // `before` only gates when the registry reports publish times. If it does
260
+ // not, pacote returns the newest version as if there were no policy, so a
261
+ // pick has to be shown to be within the cut-off rather than assumed to be.
262
+ assertPublishedWithinPolicy(name, picked, policy);
263
+ return { kind: "resolved", version: picked.version };
149
264
  }
150
265
  catch (error) {
151
- const reason = error instanceof Error ? error.message : String(error);
152
- devkit_1.logger.warn(` Could not resolve the latest version of ${name}: ${reason}. Left unchanged.`);
153
- return undefined;
266
+ if (error instanceof PolicyViolationError)
267
+ throw error;
268
+ const failure = classifyFailure(error, policy);
269
+ if (failure.kind === "policy-excluded" && policy !== undefined) {
270
+ devkit_1.logger.warn(` No version of ${name} was published before ${policy.cutoff.toISOString()}, the cut-off from your npm ${policy.setting}. Left unchanged.`);
271
+ }
272
+ else {
273
+ devkit_1.logger.warn(` Could not resolve the latest version of ${name}: ${failure.reason}. Left unchanged.`);
274
+ }
275
+ return failure;
154
276
  }
155
277
  };
278
+ const policyExcludedEverythingError = (policy, count) => new Error(`Your npm release-age policy (${policy.setting}) excludes every available version of the ${count} @trackunit/* dependency(ies), so nothing was upgraded. ` +
279
+ `${adjustAdvice(policy)} in your .npmrc (or with \`npm config\`), then run this generator again.`);
280
+ const registryUnreachableError = (reason) => new Error(`Could not reach the npm registry: ${reason}. Nothing was upgraded. ` +
281
+ `Check your network connection, proxy settings and TU_NPM_REGISTRY if you set it, then run this generator again.`);
156
282
  /**
157
283
  * Moves every `@trackunit/*` dependency in the consumer's package.json to its
158
284
  * latest published version.
@@ -166,27 +292,38 @@ const resolveLatestVersion = async (name) => {
166
292
  *
167
293
  * @param tree - The NX virtual file system for the workspace being migrated.
168
294
  * @param verbose - Log per-package decisions, including packages left alone.
295
+ * @param nodeVersion - The Node version the run is on, for reporting engine-capped upgrades.
296
+ * @param readPolicy - Reads the npm release-age policy, called only once there is something to resolve; when it yields a policy, no version published after its cut-off is selected.
169
297
  * @returns {Promise<ReadonlyArray<DependencyUpgrade>>} One entry per declaration whose specifier changed.
170
298
  * @throws {Error} When not one dependency could be resolved from the registry, which means the upgrade never happened.
171
299
  */
172
- const upgradeTrackunitDependencies = async (tree, verbose, nodeVersion = process.versions.node) => {
300
+ const upgradeTrackunitDependencies = async (tree, verbose, nodeVersion = process.versions.node, readPolicy = () => Promise.resolve(undefined)) => {
173
301
  const declared = (0, exports.collectTrackunitDependencies)(tree);
174
302
  const names = [...new Set(declared.map(declaration => declaration.name))];
175
303
  if (names.length === 0) {
176
304
  devkit_1.logger.info("No @trackunit/* dependencies declared in package.json");
177
305
  return [];
178
306
  }
307
+ const policy = await readPolicy();
179
308
  devkit_1.logger.info(`Resolving latest versions for ${names.length} @trackunit/* dependency(ies)`);
180
309
  // Keyed by name, not by declaration, so a package declared in both fields
181
310
  // still costs one registry round trip.
182
311
  const latestByName = new Map();
312
+ const failureByName = new Map();
183
313
  const capByName = new Map();
314
+ const packumentByName = new Map();
184
315
  await Promise.all(names.map(async (name) => {
185
- const latest = await resolveLatestVersion(name);
186
- if (latest === undefined)
316
+ const resolution = await resolveLatestVersion(name, policy);
317
+ if (resolution.kind !== "resolved") {
318
+ failureByName.set(name, resolution);
187
319
  return;
320
+ }
321
+ const latest = resolution.version;
188
322
  latestByName.set(name, latest);
189
- const cap = await findEngineCap(name, latest, nodeVersion);
323
+ const packument = await fetchPackument(name, policy);
324
+ if (packument !== undefined)
325
+ packumentByName.set(name, packument);
326
+ const cap = findEngineCap(packument, latest, nodeVersion, policy);
190
327
  if (cap !== undefined)
191
328
  capByName.set(name, cap);
192
329
  }));
@@ -202,6 +339,17 @@ const upgradeTrackunitDependencies = async (tree, verbose, nodeVersion = process
202
339
  // symptom this generator exists to remove: a green run that changed nothing.
203
340
  const unresolved = names.filter(name => !latestByName.has(name));
204
341
  if (unresolved.length === names.length) {
342
+ // Every lookup failed for the same reason, so say that reason plainly
343
+ // instead of the generic registry-access hint, which would send a developer
344
+ // with a too-strict policy off to debug their network.
345
+ const failures = [...failureByName.values()];
346
+ if (policy !== undefined && failures.every(failure => failure.kind === "policy-excluded")) {
347
+ throw policyExcludedEverythingError(policy, names.length);
348
+ }
349
+ const unreachable = failures.find(failure => failure.kind === "unreachable");
350
+ if (unreachable !== undefined && failures.every(failure => failure.kind === "unreachable")) {
351
+ throw registryUnreachableError(unreachable.reason);
352
+ }
205
353
  throw new Error(`Could not resolve any of the ${names.length} @trackunit/* dependency(ies) from the registry, so nothing was upgraded. ` +
206
354
  `Check your registry access -- network, npm authentication, and TU_NPM_REGISTRY if you set it -- then run this generator again. ` +
207
355
  `The per-package reasons are in the warnings above.`);
@@ -211,6 +359,8 @@ const upgradeTrackunitDependencies = async (tree, verbose, nodeVersion = process
211
359
  `(${unresolved.join(", ")}). This upgrade is incomplete.`);
212
360
  }
213
361
  const upgrades = [];
362
+ const tooNewForPolicy = [];
363
+ const aheadOfResolved = [];
214
364
  for (const { name, field, specifier } of declared) {
215
365
  const latest = latestByName.get(name);
216
366
  if (latest === undefined)
@@ -225,6 +375,22 @@ const upgradeTrackunitDependencies = async (tree, verbose, nodeVersion = process
225
375
  devkit_1.logger.info(` ${name} (${field}): left alone, "${specifier}" is not a pinned version`);
226
376
  continue;
227
377
  }
378
+ // Upgrades only move forward, so a declaration ahead of the resolved
379
+ // version is always kept. Under a policy, `latest` is both release-age and
380
+ // engine filtered, so being ahead of it does not by itself mean the policy
381
+ // forbids the declaration: a version the policy allows can sit above an
382
+ // engine-capped `latest`. Only a publish time after the cut-off is blamed on
383
+ // the policy; anything else is reported as ahead, without a policy warning.
384
+ if (policy !== undefined && (0, semver_1.gt)(parsed.version, latest)) {
385
+ const packument = packumentByName.get(name);
386
+ if (packument !== undefined && isPublishedAfterCutoff(packument, parsed.version, policy)) {
387
+ tooNewForPolicy.push({ name, field, specifier, newestAllowed: latest });
388
+ }
389
+ else {
390
+ aheadOfResolved.push({ name, field, specifier, resolved: latest });
391
+ }
392
+ continue;
393
+ }
228
394
  if (!(0, semver_1.gt)(latest, parsed.version)) {
229
395
  if (verbose)
230
396
  devkit_1.logger.info(` ${name} (${field}): already at ${specifier}`);
@@ -232,8 +398,26 @@ const upgradeTrackunitDependencies = async (tree, verbose, nodeVersion = process
232
398
  }
233
399
  upgrades.push({ name, field, from: specifier, to: `${parsed.prefix}${latest}` });
234
400
  }
401
+ for (const { name, field, specifier, newestAllowed } of tooNewForPolicy) {
402
+ devkit_1.logger.warn(` ${name} (${field}): declared as ${specifier}, newer than your npm release-age policy (${policy?.setting}) allows; ` +
403
+ `the newest allowed version is ${newestAllowed}. It was left unchanged because migrate never downgrades, ` +
404
+ `but an npm install under this policy will fail for it until the policy allows that version.`);
405
+ }
406
+ for (const { name, field, specifier, resolved } of aheadOfResolved) {
407
+ const newest = capByName.has(name)
408
+ ? `the newest version Node ${nodeVersion} can run`
409
+ : "the newest version resolved";
410
+ devkit_1.logger.info(` ${name} (${field}): declared as ${specifier}, ahead of ${resolved}, ${newest}; left unchanged`);
411
+ }
412
+ // Calling the workspace "at the newest allowed version" would hide a
413
+ // declaration that is past the cut-off, or ahead of what was resolved.
414
+ if (upgrades.length === 0 && (tooNewForPolicy.length > 0 || aheadOfResolved.length > 0)) {
415
+ return [];
416
+ }
235
417
  if (upgrades.length === 0) {
236
- devkit_1.logger.info("All @trackunit/* dependencies are already at their latest version");
418
+ devkit_1.logger.info(policy === undefined
419
+ ? "All @trackunit/* dependencies are already at their latest version"
420
+ : `All @trackunit/* dependencies are already at the newest version allowed by your npm release-age policy (${policy.setting})`);
237
421
  return [];
238
422
  }
239
423
  (0, devkit_1.updateJson)(tree, "package.json", json => {
@@ -0,0 +1 @@
1
+ {"version":3,"file":"upgrade-dependencies.js","sourceRoot":"","sources":["../../../../../../libs/migrations/src/generators/utils/upgrade-dependencies.ts"],"names":[],"mappings":";;;;AAAA,uCAAqE;AAErE,uDAAiC;AACjC,mCAAsE;AACtE,wDAAoD;AAWpD,MAAM,eAAe,GAAG,aAAa,CAAC;AACtC,MAAM,yBAAyB,GAAG,oBAAoB,CAAC;AACvD,MAAM,iBAAiB,GAAG,CAAC,cAAc,EAAE,iBAAiB,CAAU,CAAC;AAEvE;;;;;GAKG;AACH,MAAM,cAAc,GAAG,uBAAuB,CAAC;AAiC/C,4EAA4E;AAC5E,4EAA4E;AAC5E,iEAAiE;AACjE,MAAM,cAAc,GAAG,CAAC,SAAiB,EAA+B,EAAE;IACxE,MAAM,KAAK,GAAG,cAAc,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE,CAAC,CAAC;IACpD,IAAI,CAAC,KAAK;QAAE,OAAO,SAAS,CAAC;IAE7B,MAAM,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC,GAAG,KAAK,CAAC;IAClC,IAAI,OAAO,KAAK,SAAS,IAAI,IAAA,cAA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C,CAAC,EAAE,CAAC;QACxF,OAAO,EAAE,CAAC;IACZ,CAAC;IAED,IAAI,QAAQ,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAC1B,eAAM,CAAC,IAAI,CACT,MAAM,KAAK,SAAS;YAClB,CAAC,CAAC,mEAAmE;YACrE,CAAC,CAAC,2GAA2G,MAAM,CAAC,OAAO,GAAG,CACjI,CAAC;QACF,OAAO,EAAE,CAAC;IACZ,CAAC;IAED,IAAA,mBAAU,EAAyC,IAAI,EAAE,cAAc,EAAE,IAAI,CAAC,EAAE;QAC9E,KAAK,MAAM,OAAO,IAAI,QAAQ,EAAE,CAAC;YAC/B,MAAM,YAAY,GAAG,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;YACzC,IAAI,YAAY,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,SAAS,EAAE,CAAC;gBAC/C,YAAY,CAAC,OAAO,CAAC,IAAI,CAAC,GAAG,OAAO,CAAC,EAAE,CAAC;YAC1C,CAAC;QACH,CAAC;QACD,OAAO,IAAI,CAAC;IACd,CAAC,CAAC,CAAC;IAEH,KAAK,MAAM,OAAO,IAAI,QAAQ,EAAE,CAAC;QAC/B,eAAM,CAAC,IAAI,CAAC,KAAK,OAAO,CAAC,IAAI,KAAK,OAAO,CAAC,IAAI,OAAO,OAAO,CAAC,EAAE,EAAE,CAAC,CAAC;IACrE,CAAC;IACD,eAAM,CAAC,IAAI,CAAC,WAAW,QAAQ,CAAC,MAAM,+CAA+C,CAAC,CAAC;IAEvF,OAAO,QAAQ,CAAC;AAClB,CAAC,CAAC;AApLW,QAAA,4BAA4B,gCAoLvC","sourcesContent":["import { type Tree, logger, readJson, updateJson } from \"@nx/devkit\";\nimport type { Manifest, ManifestResult, Options } from \"pacote\";\nimport * as pacote from \"pacote\";\nimport { gt, prerelease, satisfies, valid, validRange } from \"semver\";\nimport { errorCode } from \"./error-code/error-code\";\nimport type { ReleasePolicy } from \"./release-policy/release-policy\";\n\n// pacote copies the picked version's publish time from the full packument onto the manifest as `_time`\n// (registry.js), set when fetched with `before` or `fullMetadata`. No published type declares it.\ndeclare module \"pacote\" {\n interface ManifestResult {\n _time?: string;\n }\n}\n\nconst TRACKUNIT_SCOPE = \"@trackunit/\";\nconst MANAGER_REPO_PACKAGE_NAME = \"@trackunit/manager\";\nconst DEPENDENCY_FIELDS = [\"dependencies\", \"devDependencies\"] as const;\n\n/**\n * Splits a specifier into the range operator we can carry over to the\n * replacement and the rest. Deciding whether the rest is actually a version is\n * left entirely to `semver.valid`, so there is one authority on that rather\n * than a pattern here that has to agree with it.\n */\nconst RANGE_OPERATOR = /^(\\^|~|>=|>)?\\s*(.+)$/;\n\ntype ConsumerPackageJson = {\n readonly name?: string;\n readonly dependencies?: Record<string, string>;\n readonly devDependencies?: Record<string, string>;\n};\n\ntype MutablePackageJson = {\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n};\n\ntype DependencyField = (typeof DEPENDENCY_FIELDS)[number];\n\nexport type DeclaredDependency = {\n readonly name: string;\n readonly field: DependencyField;\n readonly specifier: string;\n};\n\nexport type DependencyUpgrade = {\n readonly name: string;\n readonly field: DependencyField;\n readonly from: string;\n readonly to: string;\n};\n\ntype PinnedSpecifier = {\n readonly prefix: string;\n readonly version: string;\n};\n\n// `workspace:*`, `npm:` aliases, `file:`/`link:`/`portal:` paths, git URLs,\n// `*`, `latest` and multi-clause ranges all fall out here: rewriting any of\n// them to a plain version would change what the specifier means.\nconst parseSpecifier = (specifier: string): PinnedSpecifier | undefined => {\n const match = RANGE_OPERATOR.exec(specifier.trim());\n if (!match) return undefined;\n\n const [, prefix, version] = match;\n if (version === undefined || valid(version) === null) return undefined;\n\n return { prefix: prefix ?? \"\", version };\n};\n\n/**\n * Extracts the concrete version a specifier resolves to, for comparing against\n * a candidate upgrade.\n *\n * @param specifier - The specifier currently in package.json, e.g. `^1.2.3`.\n * @returns {string | undefined} The version without its range operator, or undefined when the specifier is not a pinned version.\n */\nexport const pinnedVersionOf = (specifier: string): string | undefined => parseSpecifier(specifier)?.version;\n\n/**\n * Rewrites a dependency specifier to a new version while keeping the range\n * operator the consumer chose, so a `^`-ranged dependency does not silently\n * become pinned (and vice versa).\n *\n * @param specifier - The specifier currently in package.json, e.g. `^1.2.3`.\n * @param version - The concrete version to move to, e.g. `1.3.0`.\n * @returns {string} The new specifier, or the original when it is not a pinned version.\n */\nexport const applyVersionKeepingRange = (specifier: string, version: string): string => {\n const parsed = parseSpecifier(specifier);\n return parsed === undefined ? specifier : `${parsed.prefix}${version}`;\n};\n\n/**\n * Reports whether the tree being generated into is the manager monorepo itself,\n * where `@trackunit/*` versions are workspace-internal and CI-managed rather\n * than resolved from the registry.\n *\n * @param tree - The NX virtual file system for the workspace being migrated.\n * @returns {boolean} True when the workspace root package.json is `@trackunit/manager`.\n */\nexport const isManagerWorkspace = (tree: Tree): boolean => {\n try {\n const packageJson: ConsumerPackageJson = readJson(tree, \"package.json\");\n return packageJson.name === MANAGER_REPO_PACKAGE_NAME;\n } catch {\n return false;\n }\n};\n\n/**\n * Collects every `@trackunit/*` declaration in the consumer's `dependencies`\n * and `devDependencies`. package.json is the source of truth rather than\n * node_modules, so this still reports the full set when the install is stale or\n * missing entirely -- the state an outdated app is in before its first upgrade.\n *\n * A package declared in both fields yields one entry per field, because the two\n * can carry different specifiers and each has to be judged on its own: a\n * `workspace:*` devDependency must survive an upgrade of the `dependencies`\n * entry beside it.\n *\n * @param tree - The NX virtual file system for the workspace being migrated.\n * @returns {ReadonlyArray<DeclaredDependency>} One entry per declaration, in field order.\n */\nexport const collectTrackunitDependencies = (tree: Tree): ReadonlyArray<DeclaredDependency> => {\n const packageJson: ConsumerPackageJson = readJson(tree, \"package.json\");\n const found: Array<DeclaredDependency> = [];\n\n for (const field of DEPENDENCY_FIELDS) {\n for (const [name, specifier] of Object.entries(packageJson[field] ?? {})) {\n if (!name.startsWith(TRACKUNIT_SCOPE) || typeof specifier !== \"string\") continue;\n found.push({ name, field, specifier });\n }\n }\n\n return found;\n};\n\n/**\n * The registry override, the one place pacote options start from. No override leaves the options out entirely.\n * A release-age policy's cut-off goes in as `before` where a manifest is picked, so pacote only considers\n * versions the policy allows.\n */\nconst registryOverride = (): Options | undefined => {\n const registry = process.env.TU_NPM_REGISTRY;\n return registry ? { registry } : undefined;\n};\n\nconst toValidDate = (value: unknown): Date | undefined => {\n if (typeof value !== \"string\") return undefined;\n\n const date = new Date(value);\n return Number.isNaN(date.getTime()) ? undefined : date;\n};\n\n/**\n * The parts of a registry packument this module reads, every one of them optional. `@types/pacote` describes a\n * well-formed packument (`Packument` always has `time` and `dist-tags`), but what a registry mirror or proxy serves\n * is not always that: publish times are stripped, tags are missing. Every read here treats an absent part as\n * \"cannot tell\", so the type says so, and a `Packument` or `AbbreviatedPackument` from pacote fits it as it is.\n */\ntype RegistryPackument = {\n readonly versions?: Readonly<Record<string, { readonly engines?: Readonly<Record<string, string>> }>>;\n readonly time?: Readonly<Record<string, string>>;\n readonly \"dist-tags\"?: { readonly latest?: string };\n};\n\n/**\n * What a packument reports about when a version was published, as a date, or `undefined` when it does not say or\n * says something that is not a time. A version whose publish time is unknown cannot be shown to be within a\n * policy, and cannot be blamed on one either, so callers read `undefined` as \"cannot tell\" and decide which way\n * that fails.\n *\n * Only the full packument, which a release-age policy asks for, carries publish times.\n */\nconst publishedAt = (packument: RegistryPackument, version: string): Date | undefined =>\n toValidDate(packument.time?.[version]);\n\n// A version whose publish time is missing cannot be shown to be within the\n// policy, and the one thing this note must never do is name a version the policy\n// forbids -- so unknown counts as outside.\nconst isPublishedWithinPolicy = (packument: RegistryPackument, version: string, policy: ReleasePolicy): boolean => {\n const published = publishedAt(packument, version);\n return published !== undefined && published <= policy.cutoff;\n};\n\n// The opposite question: is there evidence that the policy forbids this\n// version? Only a known publish time after the cut-off counts. A missing time,\n// or no packument at all, is \"cannot tell\", and the policy is never blamed on a\n// guess -- that would send developers to loosen their .npmrc for nothing.\nconst isPublishedAfterCutoff = (packument: RegistryPackument, version: string, policy: ReleasePolicy): boolean => {\n const published = publishedAt(packument, version);\n return published !== undefined && published > policy.cutoff;\n};\n\ntype EngineCap = {\n readonly reached: string;\n readonly skipped: string;\n readonly requiredNode: string;\n};\n\n/**\n * `pacote.manifest` already applies npm-pick-manifest's engine filter against\n * the running Node version, so the version it hands back can be far behind the\n * registry's `latest` with nothing said about it -- which reads as the tool\n * failing to upgrade rather than as a deliberate, correct choice. Naming what\n * was passed over needs the packument, which carries `engines` in its cheap\n * abbreviated form and is served from pacote's cache after the manifest lookup.\n *\n * The only version worth naming is the one the `latest` dist-tag points at,\n * because that is what `pacote.manifest` resolves and therefore the only thing\n * the engine filter can have taken away. Scanning for the highest published\n * version instead would blame a hotfix from a maintenance branch, or anything\n * deliberately left untagged, for an upgrade it was never a candidate for on\n * any Node version.\n *\n * Under a release-age policy the `latest` tag can point at a version published\n * after the cut-off. Naming it would tell the developer about a version their\n * own policy forbids, so it is only named when its publish time shows it is\n * within the cut-off.\n *\n * Only an unsatisfied `engines.node` counts. A malformed range is treated as\n * \"cannot tell\" rather than \"blocked\", so a bad `engines` field never invents\n * a cap, and a prerelease tagged `latest` is not what a consumer is missing\n * out on.\n */\nconst fetchPackument = async (\n name: string,\n policy: ReleasePolicy | undefined\n): Promise<RegistryPackument | undefined> => {\n try {\n // Publish times live only in the full packument, so a policy has to ask for it.\n return policy === undefined\n ? await pacote.packument(name, registryOverride())\n : await pacote.packument(name, { ...registryOverride(), fullMetadata: true });\n } catch {\n // The upgrade itself already succeeded; this lookup only annotates it, so a\n // failure here must stay silent rather than imply no cap exists.\n return undefined;\n }\n};\n\nconst findEngineCap = (\n packument: RegistryPackument | undefined,\n reached: string,\n nodeVersion: string,\n policy: ReleasePolicy | undefined\n): EngineCap | undefined => {\n if (packument === undefined || valid(reached) === null || valid(nodeVersion) === null) return undefined;\n\n const latest = packument[\"dist-tags\"]?.latest;\n if (latest === undefined || valid(latest) === null) return undefined;\n if (prerelease(latest) !== null || !gt(latest, reached)) return undefined;\n if (policy !== undefined && !isPublishedWithinPolicy(packument, latest, policy)) return undefined;\n\n const requiredNode = packument.versions?.[latest]?.engines?.node;\n if (requiredNode === undefined || validRange(requiredNode) === null) return undefined;\n if (satisfies(nodeVersion, requiredNode)) return undefined;\n\n return { reached, skipped: latest, requiredNode };\n};\n\n// Codes pacote reports when nothing could be fetched at all, as opposed to the\n// registry answering with something unusable.\nconst NETWORK_ERROR_CODES: ReadonlySet<string> = new Set([\n \"ECONNREFUSED\",\n \"ECONNRESET\",\n \"ENOTFOUND\",\n \"ETIMEDOUT\",\n \"EAI_AGAIN\",\n \"EHOSTUNREACH\",\n \"ENETUNREACH\",\n \"FETCH_ERROR\",\n]);\n\n// npm-pick-manifest reports a policy that leaves nothing to pick as\n// ENOVERSIONS (every version is newer than `before`) or ETARGET (versions exist\n// but none match). Without a policy neither says anything about it, so they are\n// only read as policy exhaustion when one is set.\nconst POLICY_EXCLUSION_CODES: ReadonlySet<string> = new Set([\"ENOVERSIONS\", \"ETARGET\"]);\n\ntype Failure = { readonly kind: \"policy-excluded\" | \"unreachable\" | \"failed\"; readonly reason: string };\ntype Resolution = { readonly kind: \"resolved\"; readonly version: string } | Failure;\n\n// Under a policy these codes are taken at face value, with no second lookup to\n// confirm: a package declared in a working package.json always has published\n// versions, so \"nothing to pick\" can only mean they are all newer than `before`.\nconst classifyFailure = (error: unknown, policy: ReleasePolicy | undefined): Failure => {\n const reason = error instanceof Error ? error.message : String(error);\n const code = String(errorCode(error) ?? \"\");\n\n if (policy !== undefined && POLICY_EXCLUSION_CODES.has(code)) return { kind: \"policy-excluded\", reason };\n if (NETWORK_ERROR_CODES.has(code)) return { kind: \"unreachable\", reason };\n return { kind: \"failed\", reason };\n};\n\nconst adjustAdvice = (policy: ReleasePolicy): string =>\n policy.source === \"before\" ? \"Move before to a later date or remove it\" : \"Lower min-release-age or remove it\";\n\n/** The registry's answer cannot be shown to respect the policy, which must stop the run, not skip a package. */\nclass PolicyViolationError extends Error {\n /**\n * Creates the error.\n *\n * @param message - What could not be verified, and against which setting.\n */\n public constructor(message: string) {\n super(message);\n this.name = \"PolicyViolationError\";\n }\n}\n\nconst assertPublishedWithinPolicy = (name: string, manifest: Manifest & ManifestResult, policy: ReleasePolicy): void => {\n // `_time` is declared by the module augmentation at the top of this file.\n const published = toValidDate(manifest._time);\n const label = `${name}@${manifest.version}`;\n\n if (published === undefined) {\n throw new PolicyViolationError(\n `The registry did not report when ${label} was published, so it cannot be checked against your npm release-age policy (${policy.setting}). ` +\n `Nothing was upgraded. Check that your registry serves publish times -- a mirror or proxy may strip them.`\n );\n }\n if (published > policy.cutoff) {\n throw new PolicyViolationError(\n `${label} was published ${published.toISOString()}, after the cut-off ${policy.cutoff.toISOString()} of your npm release-age policy (${policy.setting}), ` +\n `so it was not installed. Nothing was upgraded.`\n );\n }\n};\n\n// A single unreachable or unpublished package must not abort the upgrade of the\n// other 30, so a failed lookup degrades to \"leave this one alone\" and says so.\n// There is deliberately no retry without the policy: a lookup that fails under a\n// policy stays failed rather than quietly picking a version the policy forbids.\nconst resolveLatestVersion = async (name: string, policy: ReleasePolicy | undefined): Promise<Resolution> => {\n try {\n if (policy === undefined) {\n const manifest = await pacote.manifest(name, registryOverride());\n return { kind: \"resolved\", version: manifest.version };\n }\n\n const picked = await pacote.manifest(name, { ...registryOverride(), before: policy.cutoff });\n // `before` only gates when the registry reports publish times. If it does\n // not, pacote returns the newest version as if there were no policy, so a\n // pick has to be shown to be within the cut-off rather than assumed to be.\n assertPublishedWithinPolicy(name, picked, policy);\n return { kind: \"resolved\", version: picked.version };\n } catch (error) {\n if (error instanceof PolicyViolationError) throw error;\n const failure = classifyFailure(error, policy);\n\n if (failure.kind === \"policy-excluded\" && policy !== undefined) {\n logger.warn(\n ` No version of ${name} was published before ${policy.cutoff.toISOString()}, the cut-off from your npm ${policy.setting}. Left unchanged.`\n );\n } else {\n logger.warn(` Could not resolve the latest version of ${name}: ${failure.reason}. Left unchanged.`);\n }\n return failure;\n }\n};\n\nconst policyExcludedEverythingError = (policy: ReleasePolicy, count: number): Error =>\n new Error(\n `Your npm release-age policy (${policy.setting}) excludes every available version of the ${count} @trackunit/* dependency(ies), so nothing was upgraded. ` +\n `${adjustAdvice(policy)} in your .npmrc (or with \\`npm config\\`), then run this generator again.`\n );\n\nconst registryUnreachableError = (reason: string): Error =>\n new Error(\n `Could not reach the npm registry: ${reason}. Nothing was upgraded. ` +\n `Check your network connection, proxy settings and TU_NPM_REGISTRY if you set it, then run this generator again.`\n );\n\n/**\n * Moves every `@trackunit/*` dependency in the consumer's package.json to its\n * latest published version.\n *\n * This is deliberately independent of migration discovery. Migrations only\n * exist inside published packages, so gating the version bump on finding a\n * `migrations` field means an outdated workspace can never upgrade: its\n * installed packages predate the field, nothing is discovered, and nothing is\n * bumped. Resolving from the registry instead of from node_modules is what\n * makes the first upgrade of a stale workspace possible at all.\n *\n * @param tree - The NX virtual file system for the workspace being migrated.\n * @param verbose - Log per-package decisions, including packages left alone.\n * @param nodeVersion - The Node version the run is on, for reporting engine-capped upgrades.\n * @param readPolicy - Reads the npm release-age policy, called only once there is something to resolve; when it yields a policy, no version published after its cut-off is selected.\n * @returns {Promise<ReadonlyArray<DependencyUpgrade>>} One entry per declaration whose specifier changed.\n * @throws {Error} When not one dependency could be resolved from the registry, which means the upgrade never happened.\n */\nexport const upgradeTrackunitDependencies = async (\n tree: Tree,\n verbose: boolean,\n nodeVersion: string = process.versions.node,\n readPolicy: () => Promise<ReleasePolicy | undefined> = () => Promise.resolve(undefined)\n): Promise<ReadonlyArray<DependencyUpgrade>> => {\n const declared = collectTrackunitDependencies(tree);\n const names = [...new Set(declared.map(declaration => declaration.name))];\n\n if (names.length === 0) {\n logger.info(\"No @trackunit/* dependencies declared in package.json\");\n return [];\n }\n\n const policy = await readPolicy();\n\n logger.info(`Resolving latest versions for ${names.length} @trackunit/* dependency(ies)`);\n\n // Keyed by name, not by declaration, so a package declared in both fields\n // still costs one registry round trip.\n const latestByName = new Map<string, string>();\n const failureByName = new Map<string, Failure>();\n const capByName = new Map<string, EngineCap>();\n const packumentByName = new Map<string, RegistryPackument>();\n await Promise.all(\n names.map(async name => {\n const resolution = await resolveLatestVersion(name, policy);\n if (resolution.kind !== \"resolved\") {\n failureByName.set(name, resolution);\n return;\n }\n const latest = resolution.version;\n latestByName.set(name, latest);\n\n const packument = await fetchPackument(name, policy);\n if (packument !== undefined) packumentByName.set(name, packument);\n const cap = findEngineCap(packument, latest, nodeVersion, policy);\n if (cap !== undefined) capByName.set(name, cap);\n })\n );\n\n // Reported before the up-to-date branch below, because a workspace can be at\n // the newest version its Node can run and still be capped -- which is exactly\n // the case where \"already at their latest version\" is most misleading.\n for (const [name, cap] of capByName) {\n logger.info(\n ` ${name}: stopped at ${cap.reached}; ${cap.skipped} requires Node ${cap.requiredNode} and this run is on Node ${nodeVersion}`\n );\n }\n\n // Resolving nothing at all is an environment failure -- no network, a\n // proxying or private registry, an expired token -- not a workspace that\n // happens to be current. Reporting it as success would recreate the exact\n // symptom this generator exists to remove: a green run that changed nothing.\n const unresolved = names.filter(name => !latestByName.has(name));\n if (unresolved.length === names.length) {\n // Every lookup failed for the same reason, so say that reason plainly\n // instead of the generic registry-access hint, which would send a developer\n // with a too-strict policy off to debug their network.\n const failures = [...failureByName.values()];\n if (policy !== undefined && failures.every(failure => failure.kind === \"policy-excluded\")) {\n throw policyExcludedEverythingError(policy, names.length);\n }\n const unreachable = failures.find(failure => failure.kind === \"unreachable\");\n if (unreachable !== undefined && failures.every(failure => failure.kind === \"unreachable\")) {\n throw registryUnreachableError(unreachable.reason);\n }\n\n throw new Error(\n `Could not resolve any of the ${names.length} @trackunit/* dependency(ies) from the registry, so nothing was upgraded. ` +\n `Check your registry access -- network, npm authentication, and TU_NPM_REGISTRY if you set it -- then run this generator again. ` +\n `The per-package reasons are in the warnings above.`\n );\n }\n\n if (unresolved.length > 0) {\n logger.warn(\n `${unresolved.length} of ${names.length} @trackunit/* dependency(ies) could not be resolved and were left unchanged ` +\n `(${unresolved.join(\", \")}). This upgrade is incomplete.`\n );\n }\n\n const upgrades: Array<DependencyUpgrade> = [];\n const tooNewForPolicy: Array<{\n readonly name: string;\n readonly field: string;\n readonly specifier: string;\n readonly newestAllowed: string;\n }> = [];\n const aheadOfResolved: Array<{\n readonly name: string;\n readonly field: string;\n readonly specifier: string;\n readonly resolved: string;\n }> = [];\n\n for (const { name, field, specifier } of declared) {\n const latest = latestByName.get(name);\n if (latest === undefined) continue;\n\n // Each declaration is judged against its own specifier. Reusing one field's\n // result for the other would overwrite a specifier that was never read --\n // turning a `workspace:*` devDependency into a plain version, or swapping\n // one field's range operator for the other's.\n const parsed = parseSpecifier(specifier);\n if (parsed === undefined) {\n if (verbose) logger.info(` ${name} (${field}): left alone, \"${specifier}\" is not a pinned version`);\n continue;\n }\n\n // Upgrades only move forward, so a declaration ahead of the resolved\n // version is always kept. Under a policy, `latest` is both release-age and\n // engine filtered, so being ahead of it does not by itself mean the policy\n // forbids the declaration: a version the policy allows can sit above an\n // engine-capped `latest`. Only a publish time after the cut-off is blamed on\n // the policy; anything else is reported as ahead, without a policy warning.\n if (policy !== undefined && gt(parsed.version, latest)) {\n const packument = packumentByName.get(name);\n if (packument !== undefined && isPublishedAfterCutoff(packument, parsed.version, policy)) {\n tooNewForPolicy.push({ name, field, specifier, newestAllowed: latest });\n } else {\n aheadOfResolved.push({ name, field, specifier, resolved: latest });\n }\n continue;\n }\n\n if (!gt(latest, parsed.version)) {\n if (verbose) logger.info(` ${name} (${field}): already at ${specifier}`);\n continue;\n }\n\n upgrades.push({ name, field, from: specifier, to: `${parsed.prefix}${latest}` });\n }\n\n for (const { name, field, specifier, newestAllowed } of tooNewForPolicy) {\n logger.warn(\n ` ${name} (${field}): declared as ${specifier}, newer than your npm release-age policy (${policy?.setting}) allows; ` +\n `the newest allowed version is ${newestAllowed}. It was left unchanged because migrate never downgrades, ` +\n `but an npm install under this policy will fail for it until the policy allows that version.`\n );\n }\n\n for (const { name, field, specifier, resolved } of aheadOfResolved) {\n const newest = capByName.has(name)\n ? `the newest version Node ${nodeVersion} can run`\n : \"the newest version resolved\";\n logger.info(` ${name} (${field}): declared as ${specifier}, ahead of ${resolved}, ${newest}; left unchanged`);\n }\n\n // Calling the workspace \"at the newest allowed version\" would hide a\n // declaration that is past the cut-off, or ahead of what was resolved.\n if (upgrades.length === 0 && (tooNewForPolicy.length > 0 || aheadOfResolved.length > 0)) {\n return [];\n }\n\n if (upgrades.length === 0) {\n logger.info(\n policy === undefined\n ? \"All @trackunit/* dependencies are already at their latest version\"\n : `All @trackunit/* dependencies are already at the newest version allowed by your npm release-age policy (${policy.setting})`\n );\n return [];\n }\n\n updateJson<MutablePackageJson, MutablePackageJson>(tree, \"package.json\", json => {\n for (const upgrade of upgrades) {\n const dependencies = json[upgrade.field];\n if (dependencies?.[upgrade.name] !== undefined) {\n dependencies[upgrade.name] = upgrade.to;\n }\n }\n return json;\n });\n\n for (const upgrade of upgrades) {\n logger.info(` ${upgrade.name}: ${upgrade.from} -> ${upgrade.to}`);\n }\n logger.info(`Updated ${upgrades.length} @trackunit/* dependency(ies) in package.json`);\n\n return upgrades;\n};\n"]}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../libs/migrations/src/index.ts"],"names":[],"mappings":";;;AAAA,4DAAyD;AAAhD,oGAAA,OAAO,OAAA;AAChB,mEAAsE;AAA7D,0GAAA,aAAa,OAAA","sourcesContent":["export { migrate } from \"./generators/migrate/generator\";\nexport { runMigrations } from \"./generators/run-migrations/generator\";\n"]}