@hublo/sentinel 1.4.0-alpha.1 → 1.4.0-alpha.10

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.
Files changed (44) hide show
  1. package/README.md +6 -4
  2. package/dist/bin/sentinel.d.ts +1 -0
  3. package/dist/bin/sentinel.js +1 -2
  4. package/dist/chunk-2XLX6PFR.js.map +1 -0
  5. package/dist/chunk-3TDUIKVQ.js.map +1 -0
  6. package/dist/chunk-CPCUPK4J.js +70 -0
  7. package/dist/chunk-CPCUPK4J.js.map +1 -0
  8. package/dist/chunk-CRKUEP4J.js +427 -0
  9. package/dist/chunk-CRKUEP4J.js.map +1 -0
  10. package/dist/{chunk-O3XCQGTJ.js → chunk-L7WS36XV.js} +1253 -194
  11. package/dist/chunk-PWV3BMDA.js.map +1 -0
  12. package/dist/chunk-WLFE5RUU.js.map +1 -0
  13. package/dist/index.d.ts +13 -0
  14. package/dist/index.js +1 -2
  15. package/dist/roles/test/nest/toolchain.d.ts +3 -23
  16. package/dist/roles/test/nest/toolchain.js +4 -203
  17. package/dist/roles/test/nest/toolchain.js.map +1 -1
  18. package/dist/roles/test/react/toolchain.d.ts +5 -1
  19. package/dist/roles/test/react/toolchain.js +11 -20
  20. package/dist/roles/test/react/toolchain.js.map +1 -1
  21. package/dist/roles/test/setup/{nest.js → jest-parity.js} +15 -67
  22. package/dist/roles/test/setup/jest-parity.js.map +1 -0
  23. package/dist/roles/test/setup/workspace-entry.d.ts +2 -0
  24. package/dist/roles/test/setup/workspace-entry.js +8 -0
  25. package/dist/roles/test/setup/workspace-entry.js.map +1 -0
  26. package/dist/roles/test/shared-test-config.d.ts +32 -0
  27. package/dist/roles/test/shared-test-config.js +8 -0
  28. package/dist/roles/test/shared-test-config.js.map +1 -0
  29. package/dist/roles/test/tools/msw.d.ts +1 -0
  30. package/dist/roles/test/tools/msw.js +3 -0
  31. package/dist/roles/test/tools/msw.js.map +1 -0
  32. package/docs/.gitkeep +0 -0
  33. package/docs/build-adoption.md +521 -0
  34. package/docs/format-adoption.md +321 -0
  35. package/docs/lint-adoption.md +290 -0
  36. package/docs/performance.md +49 -0
  37. package/docs/test-adoption.md +219 -0
  38. package/docs/typescript-adoption.md +184 -0
  39. package/docs/typescript-traces.md +798 -0
  40. package/docs/using-sentinel.md +195 -0
  41. package/docs/validating-a-change.md +101 -0
  42. package/package.json +17 -9
  43. package/dist/roles/test/setup/nest.js.map +0 -1
  44. /package/dist/roles/test/setup/{nest.d.ts → jest-parity.d.ts} +0 -0
package/README.md CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  `sentinel` is a standalone, semver-versioned package (published to a registry, consumed by a repo as a normal dependency) that unifies a repo's tooling, config, and quality checks into one place, so projects stop copying config files everywhere and stop carrying a pile of duplicated tooling dependencies.
6
6
 
7
- > Status: **the foundation, the TypeScript tool and the lint tool are shipped** (`@hublo/sentinel` on npm). The rest of this README is the design reference for the tools still to come, added one at a time on top of this foundation.
7
+ > Status: **the foundation, TypeScript, lint, format, build, dev and test are shipped** (`@hublo/sentinel` on npm). The rest of this README is the design reference for the tools still to come, added one at a time on top of this foundation.
8
8
 
9
9
  ---
10
10
 
@@ -43,8 +43,9 @@ A large monorepo accumulates:
43
43
 
44
44
  sentinel writes **standard config files** into a project (each just `extends` a sentinel preset) and runs the checks. Your editor and the tools read those **normal files natively**, they never call sentinel at runtime, so nothing is coupled to it or brittle.
45
45
 
46
- > **Shipped today:** the **TypeScript**, **lint**, **format**, **build** and **dev** tools. The
47
- > `--test` snippets below illustrate the end state and land with their own ticket.
46
+ > **Shipped today:** the **TypeScript**, **lint**, **format**, **build**, **dev** and **test**
47
+ > tools. `--test` migrates a module from jest to Vitest and proves the migration by comparing the
48
+ > full NAMES of the tests before and after; see [the test cheat sheet](docs/test-adoption.md).
48
49
 
49
50
  **Step 1 — put a module on sentinel** (once per module, by a dev; the files are committed). Run from the app dir; `--init` does it all, nothing is hand-edited:
50
51
 
@@ -168,6 +169,7 @@ throwaway run wants. Once a module has adopted, nothing is fetched any more: the
168
169
  - [`docs/format-adoption.md`](docs/format-adoption.md) — migrating a module from Prettier to oxfmt: why this config is materialized rather than a stub, how a module keeps its own formatting, and what did not survive the move.
169
170
  - [`docs/build-adoption.md`](docs/build-adoption.md) — moving a React app's Vite toolchain into sentinel: adoption changes the config's IMPORTS and nothing else, what sentinel owns versus what stays the app's, and why reading nothing is what makes losing nothing a guarantee.
170
171
  - [`docs/typescript-adoption.md`](docs/typescript-adoption.md) — the adoption cheat sheet: the two adoption steps, the command model (verb x type x location), options, reading a report, and troubleshooting.
172
+ - [`docs/test-adoption.md`](docs/test-adoption.md) — migrating a module from jest to Vitest: the two steps, what the migration rewrites and what it refuses BY NAME, how the baseline gate proves nothing was lost, and the failures worth recognising.
171
173
  - [`docs/typescript-traces.md`](docs/typescript-traces.md) — a **generated, versioned** reference of live command + output traces (every verb, option, config result and edge case) against the mock monorepo. Regenerate after CLI changes with `pnpm docs:traces`.
172
174
 
173
175
  ## Architecture: `target → runner → preset`
@@ -529,7 +531,7 @@ This scaffold is the foundation; each tool is added one at a time on top of it:
529
531
  2. **TypeScript** (`--typescript`) — runner `tsc` (later `tsgo`): presets react/nest/node, `--run`/`--inspect`/`--report`/`--init`, the composable grid, phased (non-breaking) strictness. **✅ shipped in `0.1.0-alpha.x`**
530
532
  3. **Lint** (`--lint`) — benchmark `eslint` vs `biome` vs `oxlint`.
531
533
  4. **Build** (`--build`) — `vite`.
532
- 5. **Test** (`--test`) — `vitest`, plus a11y / w3c setups.
534
+ 5. **Test** (`--test`) — `vitest`, migration from jest proven module by module against a name-level baseline. **✅ shipped in `1.4.0-alpha.x`**; a11y / w3c setups still to come.
533
535
  6. **Static analysis** (`--static-analysis`) — cycles, complexity, duplication, centrality.
534
536
  7. **Runtime analysis** (`--runtime-analysis`) — bundle, Lighthouse, web vitals.
535
537
  8. **Unified CI workflow + `--report --all` dashboard.**
@@ -4,3 +4,4 @@ import '@vitejs/plugin-react';
4
4
  import 'nitro/vite';
5
5
  import 'vite-plugin-svgr';
6
6
  import 'vite';
7
+ import 'msw';
@@ -16,7 +16,7 @@ import {
16
16
  registerAdapters,
17
17
  resolve,
18
18
  resolveBin
19
- } from "../chunk-O3XCQGTJ.js";
19
+ } from "../chunk-L7WS36XV.js";
20
20
  import {
21
21
  WORKSPACE_ROOT_MARKER,
22
22
  ensureWorkspacePrep,
@@ -792,4 +792,3 @@ sentinel: ${asMessage2(error)}
792
792
  `);
793
793
  void exitWithoutTruncating(1);
794
794
  });
795
- //# sourceMappingURL=sentinel.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/roles/test/setup/mock-extended.ts"],"sourcesContent":["/**\n * `jest-mock-extended`'s deep mocks, made answerable to the question Vitest's `spyOn` asks.\n *\n * A deep mock is a Proxy that invents a property the first time something READS it. Nothing exists\n * until then, so the object reports itself empty:\n *\n * const provider = mockDeep<InstitutionProvider>()\n * 'getAdminFirstAndLastNames' in provider // false\n * Object.getOwnPropertyDescriptor(provider, 'getAdmin...') // undefined\n * typeof provider.getAdminFirstAndLastNames // 'function', and now it exists\n *\n * jest's `spyOn` reads the property, so the Proxy created it and the spy worked. Vitest's asks the\n * object whether it HAS the property first, gets no for both questions, and throws\n * `The property \"getAdminFirstAndLastNames\" is not defined on the object.` The file then reports no\n * test at all, so its names simply go missing rather than failing.\n *\n * Measured on `apps/cloud/shift`: one such spy took 37 of its 108 tests away. The repo has 128 of\n * them across 29 files, mostly in `apps/nest/microservices` and\n * `apps/nest/backends-for-frontends`.\n *\n * ## Why it is fixed here and not in the 128 test files\n *\n * Because it is a difference between two runners, not something 29 suites each got wrong. A\n * codemod rewriting every site would put a migration artefact in front of every reader of those\n * files forever, and teams would carry it. One adapter keeps the test files exactly as they are.\n *\n * The two traps answer by doing what jest's `spyOn` did: read the property once, then answer. The\n * read is the Proxy's own documented way of materialising it, so nothing here reimplements the\n * mock, it only asks the question in the form the underlying object understands.\n *\n * `then` is never materialised. A deep mock that suddenly HAS a `then` is a thenable, and awaiting\n * it, or returning it from an async function, would hang on a promise nothing resolves.\n */\nimport * as mockExtended from 'vitest-mock-extended'\n\n/**\n * Keys that must stay absent however they are asked for.\n *\n * Not an arbitrary list: every one of them is a PROTOCOL PROBE, a property a framework reads to\n * decide what KIND of value it is holding. A deep mock invents whatever it is asked for, so it\n * answers yes to every probe, and each yes is a lie about what it is.\n *\n * then a thenable. Awaiting the mock, or returning it from an async function,\n * hangs on a promise nothing resolves.\n * asymmetricMatch an asymmetric matcher. Measured: `expect(p).rejects.toThrow(deepMock)`\n * answers `expected error to match asymmetric matcher` instead of comparing\n * against the class, so the assertion stops testing what it says.\n * $$typeof a React element. Serializers branch on it and read fields that are not\n * there.\n * nodeType a DOM node, which testing-library and serializers both branch on.\n *\n * Symbols never reach here: the materialiser returns early for a non-string key, so `Symbol.\n * iterator` and friends are already safe.\n */\nconst NEVER_MATERIALISED = new Set(['then', 'asymmetricMatch', '$$typeof', 'nodeType'])\n\nfunction materialise(target: object, key: PropertyKey): void {\n if (typeof key !== 'string' || NEVER_MATERIALISED.has(key)) return\n // The read IS the creation: that is how the deep mock's own Proxy works.\n void (target as Record<string, unknown>)[key]\n}\n\n/**\n * Wrap a deep mock so that `in` and `getOwnPropertyDescriptor` see what a read would create.\n *\n * Only the object handed back is wrapped, not what it returns: a nested spy would need its own\n * wrapper, and the corpus has none. Wrapping every read would also mean a new wrapper per access\n * unless they were cached, and an identity that changes between two reads is a worse bug than the\n * one being fixed.\n */\n/**\n * One proxy per underlying mock, so identity is stable.\n *\n * A suite holds on to `db.timeSlot` and compares it later, or passes it to `toHaveBeenCalledWith`.\n * Handing back a fresh proxy on every read would make the same mock unequal to itself.\n */\nconst wrappers = new WeakMap<object, object>()\n\nfunction answeringProxy<T extends object>(mock: T): T {\n return new Proxy(mock, {\n /*\n * A NESTED mock has to answer the same questions as the top-level one.\n *\n * The adapter used to wrap only what `mockDeep()` returned, and the level below it was a raw\n * mock again. Measured: `'deleteMany' in db.timeSlot` answered false and its descriptor was\n * absent, so `vi.spyOn(db.timeSlot, 'deleteMany')` failed with\n * `The property \"deleteMany\" is not defined on the function` — the exact error\n * `apps/nest/microservices/hublo-pool` reports, and the exact failure this adapter was written\n * to remove, one level down.\n *\n * Read from the TARGET, never with this proxy as the receiver: forwarding the receiver changes\n * what the deep mock hands back.\n */\n get(target, key) {\n if (typeof key === 'string' && NEVER_MATERIALISED.has(key)) return undefined\n\n const value = Reflect.get(target, key) as unknown\n if (value === null) return value\n if (typeof value !== 'object' && typeof value !== 'function') return value\n\n /*\n * A Proxy invariant, not a preference: for a property that is non-configurable AND\n * non-writable, `get` MUST hand back the target's own value. Wrapping one throws\n * `'get' on proxy: property 'mock' is a read-only and non-configurable data property on the\n * proxy target but the proxy did not return its actual value`, which is what a mock's own\n * `mock` record is.\n */\n const descriptor = Reflect.getOwnPropertyDescriptor(target, key)\n if (\n descriptor !== undefined &&\n descriptor.configurable === false &&\n descriptor.writable === false\n ) {\n return value\n }\n\n const existing = wrappers.get(value as object)\n if (existing !== undefined) return existing\n\n const wrapper = answeringProxy(value as object)\n wrappers.set(value as object, wrapper)\n return wrapper\n },\n has(target, key) {\n if (Reflect.has(target, key)) return true\n materialise(target, key)\n return Reflect.has(target, key)\n },\n getOwnPropertyDescriptor(target, key) {\n const existing = Reflect.getOwnPropertyDescriptor(target, key)\n if (existing !== undefined) return existing\n materialise(target, key)\n return Reflect.getOwnPropertyDescriptor(target, key)\n },\n })\n}\n\n/*\n * Everything the fork exports, so a module importing `jest-mock-extended` still gets `mockReset`,\n * `mockClear`, `anyString`, the matchers and the types. The two names below are declared after it:\n * an explicit export wins over a star export, which is what lets this file override exactly two\n * functions and pass the rest through untouched.\n */\nexport * from 'vitest-mock-extended'\n\n/*\n * And the same names again, one by one.\n *\n * `export *` from a CJS package forwards only what a static read of that package can SEE.\n * `vitest-mock-extended` ships CommonJS and assembles part of its exports at runtime, so the star\n * carries the types and loses several of the functions. A spec importing one of them then reads\n * `undefined` and dies at the call, naming the binding and nothing else. Measured on\n * `apps/nest/microservices/mission`:\n *\n * TypeError: (0 , __vite_ssr_import_3__.mockReset) is not a function\n *\n * It is the same shape as the automock namespace built from a static export list, which\n * `server.deps.inline` exists to answer; here the file doing the re-export is ours, so it can\n * simply say the names out loud. A name that ever disappears from the fork breaks the build\n * instead of a suite, which is the better end of that trade.\n */\nexport {\n any,\n anyArray,\n anyBoolean,\n anyFunction,\n anyMap,\n anyNumber,\n anyObject,\n anySet,\n anyString,\n anySymbol,\n arrayIncludes,\n calledWithFn,\n captor,\n isA,\n isMockObject,\n mapHas,\n matches,\n mockClear,\n mocked,\n mockedFn,\n mockFn,\n mockReset,\n notEmpty,\n notNull,\n notUndefined,\n objectContainsKey,\n} from 'vitest-mock-extended'\n\n/**\n * Every deep mock handed out, so `vi.resetAllMocks()` can reach them.\n *\n * ⚠️ Kept on `globalThis`, and that is not laziness. This file is reached by TWO specifiers: the\n * setup imports it by its path, and a spec imports `jest-mock-extended`, which the preset aliases\n * here. Vite resolves those to two ids and instantiates the module twice, so a registry held in\n * module scope would be filled by one instance and read by the other, and the reset would find\n * nothing. It is the same dual-identity trap the axios alias exists to close, one layer up.\n *\n * ⚠️ It does not reach them on its own, and that is a silent divergence. jest's\n * `jest.resetAllMocks()` reset these because `jest-mock-extended` built them with `jest.fn()`, so\n * they sat in jest's own registry. `vitest-mock-extended` builds them its own way, so\n * `vi.resetAllMocks()` walks past them and their call history survives into the next test.\n *\n * Measured on `apps/nest/microservices/activity`, whose suite does exactly what jest expected:\n *\n * beforeEach(() => mocked.findEvents.mockResolvedValue([]))\n * afterEach(() => vi.resetAllMocks())\n *\n * Eleven tests asserting `toHaveBeenCalledTimes(0)` saw the call left by the test before them.\n * Each one PASSES on its own and fails right after its neighbour, which is the signature of\n * leakage rather than of a broken assertion.\n *\n * A plain Set: a test file gets its own module instance, so the registry lives and dies with it.\n */\nconst REGISTRY = Symbol.for('@hublo/sentinel/deep-mocks')\nconst handedOut: Set<object> = ((globalThis as Record<symbol, unknown>)[REGISTRY] ??=\n new Set<object>()) as Set<object>\n\n/** Reset every deep mock this adapter created, the way jest's registry did. */\nexport function resetDeepMocks(): void {\n for (const created of handedOut) mockExtended.mockReset(created as never)\n}\n\n/** Clear their calls without touching their implementations. */\nexport function clearDeepMocks(): void {\n for (const created of handedOut) mockExtended.mockClear(created as never)\n}\n\nexport const mock = ((...args: unknown[]) => {\n const created = (mockExtended.mock as (...rest: unknown[]) => object)(...args)\n handedOut.add(created)\n return answeringProxy(created)\n}) as unknown as typeof mockExtended.mock\n\nexport const mockDeep = ((...args: unknown[]) => {\n const created = (mockExtended.mockDeep as (...rest: unknown[]) => object)(...args)\n handedOut.add(created)\n return answeringProxy(created)\n}) as unknown as typeof mockExtended.mockDeep\n"],"mappings":";AAiCA,YAAY,kBAAkB;AA8G9B,cAAc;AAkBd;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,aAAAA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,aAAAC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAtIP,IAAM,qBAAqB,oBAAI,IAAI,CAAC,QAAQ,mBAAmB,YAAY,UAAU,CAAC;AAEtF,SAAS,YAAY,QAAgB,KAAwB;AAC3D,MAAI,OAAO,QAAQ,YAAY,mBAAmB,IAAI,GAAG,EAAG;AAE5D,OAAM,OAAmC,GAAG;AAC9C;AAgBA,IAAM,WAAW,oBAAI,QAAwB;AAE7C,SAAS,eAAiCC,OAAY;AACpD,SAAO,IAAI,MAAMA,OAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAcrB,IAAI,QAAQ,KAAK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,aAAY,IAAI,SAAoB;AAC/C,QAAM,UAAwB,sBAA4C,GAAG,IAAI;AACjF,YAAU,IAAI,OAAO;AACrB,SAAO,eAAe,OAAO;AAC/B;","names":["mockClear","mockReset","mock","mockDeep"]}
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/roles/build/nest/decorator-metadata.ts","../src/roles/build/nest/tsconfig-aliases.ts"],"sourcesContent":["/**\n * Decorator metadata, which esbuild cannot emit and Nest cannot live without, plus the TypeScript\n * transformers a service declared on its webpack target.\n *\n * Vite's default transformer is esbuild, and esbuild does not implement `emitDecoratorMetadata`.\n * Nest resolves a constructor's parameters from exactly that metadata, so without it the DI\n * container comes up empty and the application fails on its first module. Measured in the\n * monorepo this ships to: `emitDecoratorMetadata: true` in `tsconfig.base.json`, and 7365 files\n * carrying `@Injectable`, `@Module` or `@Controller`.\n *\n * ## TWO modes, chosen exactly as nx chooses them\n *\n * This is the one decision in this file that is not ours, and trying to make it ours cost a day.\n *\n * `@nx/webpack` configures ts-loader with one line:\n *\n * transpileOnly: !hasPlugin // hasPlugin = this target declares `transformers`\n *\n * So webpack already had two behaviours. A service with no transformers compiled with\n * `transpileOnly`, which is `ts.transpileModule` semantics: no type checker, one file at a time.\n * A service WITH transformers compiled through a full `ts.Program`, because that is the only way\n * a TypeScript transformer can run at all.\n *\n * The difference is visible, and measured. On a property typed by an imported string enum:\n *\n * Program : __metadata(\"design:type\", String)\n * transpileModule : __metadata(\"design:type\", typeof (_a = ...) === \"function\" ? _a : Object)\n *\n * and on a `@Body()` whose DTO arrives through `import type`, a Program emits `Function` where\n * transpileOnly emits `Object`, which `@nestjs/swagger` turns into four `$ref: Function` request\n * bodies that the published contract does not have.\n *\n * This plugin used only the first mode and this file claimed it was \"the serializer ts-loader was\n * already using\". Half true, and the wrong half: it is what ts-loader uses for the 29 services\n * with no transformers, and those came back byte-identical. Then a Program was used for ALL of\n * them, which fixed the eight and moved the contract of `network`, which had been correct.\n *\n * Both were the same mistake: choosing one mode for everyone, when the tool being replaced chose\n * per service. So the condition is copied rather than invented, and there is no third case to\n * discover: nx has two, and both are reproduced here.\n *\n * The Program costs about six seconds more on the largest service (1419 files: ~1.9s to build it,\n * ~3.3ms per file against ~0.9ms). Only the services that declare a transformer pay it, which is\n * also what webpack did.\n *\n * ## The transformers, which are configuration and are read, never invented\n *\n * Eight services and BFFs declare `@nestjs/swagger/plugin` on their webpack target, with\n * `introspectComments` and `classValidatorShim`. It writes the `@ApiProperty` decorators a\n * developer would otherwise write by hand, turns JSDoc into descriptions, and projects\n * class-validator rules into the schema.\n *\n * Dropping it does not fail a build. Measured on `institution` by regenerating its committed\n * contract after a sentinel build: 385 insertions and 1378 deletions. Response schemas and every\n * `minItems`, `minimum`, `maximum`, `minLength` and `format` disappeared, silently.\n *\n * So `--init` reads the declaration off the webpack target and writes it into the generated Vite\n * config, and this plugin loads it. Nothing here decides which transformers a service runs.\n *\n * ## Why the MODULE's compiler now, and not sentinel's own\n *\n * This plugin used to pin sentinel's TypeScript, on the grounds that `typescript` in the consumer\n * could resolve to the 7.x native port, which exports a version and no compiler API. Measured\n * from a service today it resolves to `@typescript/typescript6` 6.0.2, with the full API.\n *\n * The pin cannot survive the transformers anyway: a plugin loaded from the module's\n * `node_modules` imports the module's TypeScript, and a transformer built against one compiler\n * cannot be handed a Program built by another. One compiler, the module's, is also what ts-loader\n * used, so it is the faithful answer rather than merely the workable one. The API is asserted at\n * `buildStart`, where a failure is reported.\n *\n * ## Why the module's own tsconfig, and not options chosen here\n *\n * Emit follows compiler options, so options invented here would be a second, silent source of\n * divergence from what ts-loader produced. `target` alone decides how classes and fields are\n * downlevelled: this workspace is on `es2021`, where `useDefineForClassFields` defaults to false\n * and a declared-but-unassigned DTO field is therefore NOT emitted. Defaulting to `es2022` here\n * would flip that, `Object.defineProperty` would write `undefined` over every field, and\n * `class-transformer` payloads would arrive empty at runtime with nothing in the build to explain\n * it.\n *\n * So the config is read, `extends` resolved by the compiler itself, and only what this plugin\n * genuinely owns is overridden.\n *\n * ## Still no type CHECKING, which is a different thing from having types\n *\n * The Program gives this plugin a type checker; it does not use it to report errors. Every Nest\n * project already runs `tsc -b` in its own `typecheck` target, and the build never was the thing\n * that type-checked. Emitting with type information and refusing to type-check are independent,\n * and only the first is needed to reproduce what ts-loader wrote.\n */\nimport { existsSync } from 'node:fs'\nimport { createRequire } from 'node:module'\nimport path from 'node:path'\n\nimport type TS from 'typescript'\nimport type { Plugin } from 'vite'\n\n/** Files this transform owns: TypeScript sources, never a dependency's compiled output. */\nconst TYPESCRIPT_SOURCE = /\\.ts$/\n\n/**\n * Where a Nest service keeps the config it builds with, most specific first.\n *\n * `tsconfig.app.json` is the one Nx generates for the application's own sources and the one\n * ts-loader was pointed at; `tsconfig.json` is the fallback for a service that never split them.\n * Measured on `main`: all 37 services still on webpack name `tsconfig.app.json`.\n */\nconst TSCONFIG_CANDIDATES = ['tsconfig.app.json', 'tsconfig.json']\n\n/** A TypeScript transformer a service runs at build time, as its build target declares it. */\nexport interface TransformerDeclaration {\n /** The package to load it from, e.g. `@nestjs/swagger/plugin`. */\n name: string\n /** Passed to the transformer's own factory, unread here. */\n options?: Record<string, unknown>\n}\n\nexport interface DecoratorMetadataOptions {\n /** The module being built. Its tsconfig is the one whose emit must be preserved. */\n root: string\n /**\n * An explicit tsconfig, when the service does not use either conventional name.\n *\n * Relative paths resolve against `root`.\n */\n tsconfig?: string\n /** The transformers this service declared, translated from its webpack target. */\n transformers?: readonly TransformerDeclaration[]\n}\n\n/**\n * The module's own TypeScript, with its emit API asserted.\n *\n * Resolved from `root` rather than from here, because a transformer loaded from the module binds\n * to the compiler the module resolves, and Programs are not interchangeable between compilers.\n */\nfunction loadCompiler(root: string): typeof TS {\n const require = createRequire(path.join(root, 'noop.js'))\n let compiler: typeof TS\n try {\n compiler = require('typescript') as typeof TS\n } catch {\n throw new Error(\n `sentinel build(nest): no \\`typescript\\` resolvable from ${root}. The build emits decorator ` +\n `metadata with the module's own compiler, so one has to be installed there.`,\n )\n }\n if (typeof compiler.createProgram !== 'function') {\n throw new Error(\n `sentinel build(nest): the typescript resolved from ${root} (${compiler.version ?? 'unknown'}) ` +\n `has no createProgram API. TypeScript 7 is the native port and exposes none; the emit API ` +\n `lives under @typescript/typescript6. Point this module's \\`typescript\\` at a compiler ` +\n `with an emit API, which is the one its \\`typecheck\\` target already uses.`,\n )\n }\n return compiler\n}\n\nfunction resolveTsconfig(options: DecoratorMetadataOptions): string {\n if (options.tsconfig) {\n const explicit = path.resolve(options.root, options.tsconfig)\n if (!existsSync(explicit)) {\n throw new Error(`sentinel build(nest): tsconfig not found at ${explicit}`)\n }\n return explicit\n }\n for (const candidate of TSCONFIG_CANDIDATES) {\n const found = path.join(options.root, candidate)\n if (existsSync(found)) return found\n }\n throw new Error(\n `sentinel build(nest): no ${TSCONFIG_CANDIDATES.join(' or ')} in ${options.root}. ` +\n `Pass \\`tsconfig\\` if this service keeps it elsewhere.`,\n )\n}\n\n/** The module's compiler options, with `extends` already resolved, plus what this plugin owns. */\nfunction readConfig(\n ts: typeof TS,\n options: DecoratorMetadataOptions,\n): { fileNames: string[]; compilerOptions: TS.CompilerOptions } {\n const configPath = resolveTsconfig(options)\n const parsed = ts.getParsedCommandLineOfConfigFile(configPath, {}, {\n ...ts.sys,\n onUnRecoverableConfigFileDiagnostic: (diagnostic) => {\n throw new Error(\n `sentinel build(nest): could not read ${configPath}: ` +\n ts.flattenDiagnosticMessageText(diagnostic.messageText, ' '),\n )\n },\n } as TS.ParseConfigFileHost)\n\n return {\n fileNames: parsed?.fileNames ?? [],\n compilerOptions: {\n ...parsed?.options,\n // ESM out, so Rollup sees imports and exports rather than an opaque `require` it cannot\n // follow. The service still SHIPS as CJS: that conversion is the bundler's, further down.\n module: ts.ModuleKind.ESNext,\n // Vite consumes the map; the tsconfig's own answer is about a different pipeline.\n sourceMap: true,\n inlineSourceMap: false,\n inlineSources: false,\n // Types are another target's job, and emitting them here would write into the source tree.\n declaration: false,\n declarationMap: false,\n emitDeclarationOnly: false,\n noEmit: false,\n // `composite` projects refuse to emit without a `tsBuildInfoFile`, and there is no\n // incremental build here to inform.\n composite: false,\n incremental: false,\n },\n }\n}\n\n/**\n * The declared transformers, loaded from the MODULE so each binds to the compiler it expects.\n *\n * A name that cannot be loaded, or a package that exports no `before`, fails the build here\n * rather than producing a bundle quietly missing what the transformer contributes. That failure\n * mode is the reason this exists: dropping `@nestjs/swagger/plugin` costs a service most of its\n * published contract and nothing in the build says so.\n */\nfunction loadTransformers(\n root: string,\n program: TS.Program,\n declared: readonly TransformerDeclaration[],\n): TS.TransformerFactory<TS.SourceFile>[] {\n const require = createRequire(path.join(root, 'noop.js'))\n return declared.map(({ name, options }) => {\n let loaded: { before?: unknown }\n try {\n loaded = require(name) as { before?: unknown }\n } catch (error) {\n throw new Error(\n `sentinel build(nest): the build target declares the transformer \\`${name}\\`, which ` +\n `cannot be loaded from ${root}: ${error instanceof Error ? error.message : String(error)}`,\n { cause: error },\n )\n }\n if (typeof loaded.before !== 'function') {\n throw new Error(\n `sentinel build(nest): \\`${name}\\` exports no \\`before\\` factory, so it cannot run as a ` +\n `TypeScript transformer. Building without it would drop whatever it contributes.`,\n )\n }\n const factory = loaded.before as (\n options: Record<string, unknown> | undefined,\n program: TS.Program,\n ) => TS.TransformerFactory<TS.SourceFile>\n return factory(options, program)\n })\n}\n\nexport const decoratorMetadata = (options: DecoratorMetadataOptions): Plugin => {\n /*\n * Everything is prepared in `buildStart`, and that placement is the whole point.\n *\n * It used to be resolved lazily inside `transform`, on the reasoning that an error belongs to\n * the build rather than to importing the preset. Half right: it belongs to the build, but\n * Rollup SWALLOWS a throwing `transform` hook. The wrong compiler, an unreadable tsconfig and a\n * missing one all produced the same symptom instead of their own message: \"1 modules\n * transformed\", nothing written, then an unrelated error from whichever later hook tripped over\n * the empty output directory. It cost two diagnoses to recognise.\n *\n * `buildStart` is reported. So the compiler is loaded, the config read, the Program built and\n * the transformers resolved exactly once, before a single file is transformed, where failing\n * says what failed.\n */\n /** `hasPlugin` in nx's own words: this service declares transformers, so it needs a Program. */\n const typeAware = (options.transformers ?? []).length > 0\n\n let ts: typeof TS | undefined\n let program: TS.Program | undefined\n let compilerOptions: TS.CompilerOptions | undefined\n let before: TS.TransformerFactory<TS.SourceFile>[] = []\n /** Files emitted without the Program, which is a fidelity gap and is reported, never silent. */\n const withoutTypes: string[] = []\n\n return {\n name: 'sentinel:decorator-metadata',\n // Before Vite's own transform, so esbuild never sees the decorators it cannot handle, and so\n // the source this plugin reads from the Program is still the source on disk.\n enforce: 'pre',\n buildStart() {\n ts = loadCompiler(options.root)\n const config = readConfig(ts, options)\n compilerOptions = config.compilerOptions\n // Built only in the type-aware mode. It costs ~1.9s on the largest service here and buys\n // nothing a service without transformers can use, which is why nx does not build one either.\n if (!typeAware) return\n program = ts.createProgram(config.fileNames, config.compilerOptions)\n before = loadTransformers(options.root, program, options.transformers ?? [])\n },\n transform(code, id) {\n if (!TYPESCRIPT_SOURCE.test(id) || id.includes('node_modules')) return null\n // Only reachable if `buildStart` did not run, which no Rollup build does. Named rather than\n // defaulted, so it cannot silently emit with TypeScript's defaults instead of the module's.\n if (ts === undefined || compilerOptions === undefined) {\n throw new Error(\n `sentinel build(nest): the compiler was never prepared, so ${id} would be emitted with ` +\n `defaults rather than this module's tsconfig.`,\n )\n }\n\n /*\n * The Program's own SourceFile, which is what carries the type information.\n *\n * Three cases emit without it. The service declares no transformer, which is `transpileOnly`\n * and is what ts-loader did for it. A file the Program never reached, because nothing\n * imports it from the entry. And a file another plugin has already rewritten, where the\n * Program's copy is no longer the truth: emitting that stale copy over someone else's\n * transform would be the worse failure.\n *\n * The last two are counted and reported at the end. The first is not a gap, it is the mode.\n *\n * Measured on the largest service here: neither of the last two fires, on any of its 5594\n * files. That is the point of reporting them rather than tolerating them quietly — a warning\n * from this build means something genuinely new, not a known rough edge.\n */\n const sourceFile = program?.getSourceFile(id)\n if (program === undefined || sourceFile === undefined || sourceFile.text !== code) {\n if (typeAware) withoutTypes.push(id)\n const output = ts.transpileModule(code, { fileName: id, compilerOptions })\n return { code: output.outputText, map: output.sourceMapText ?? null }\n }\n\n let emitted: string | undefined\n let map: string | undefined\n program.emit(\n sourceFile,\n (fileName, text) => {\n if (fileName.endsWith('.map')) map = text\n else emitted = text\n },\n undefined,\n false,\n { before },\n )\n if (emitted === undefined) {\n throw new Error(`sentinel build(nest): TypeScript emitted nothing for ${id}.`)\n }\n return { code: emitted, map: map ?? null }\n },\n closeBundle() {\n if (withoutTypes.length === 0) return\n const shown = withoutTypes.slice(0, 5).map((file) => path.relative(options.root, file))\n this.warn(\n `sentinel build(nest): ${withoutTypes.length} file(s) were emitted without type ` +\n `information, so their decorator metadata may differ from what ts-loader produced ` +\n `(${shown.join(', ')}${withoutTypes.length > shown.length ? ', …' : ''}). They are ` +\n `outside this module's tsconfig, or another plugin rewrote them first.`,\n )\n },\n }\n}\n","/**\n * The workspace's `paths` mappings, as Vite resolve aliases.\n *\n * They matter more than they look. The mappings point at SOURCE files, and that is what makes\n * a workspace library get BUNDLED rather than externalised: Vite treats anything outside\n * `node_modules` as source. Drop them and every `@hublo/nest/*` import becomes an external the\n * runtime cannot resolve, because those packages are never published.\n *\n * This reproduces what webpack did through `tsconfig-paths-webpack-plugin`, alongside\n * `webpack-node-externals` which only ever externalised real packages. Measured on the first\n * migrated service: 45 externals under Vite against 47 under webpack, and nothing externalised\n * by Vite that webpack did not.\n */\nimport { readFileSync } from 'node:fs'\nimport { join } from 'node:path'\n\nexport interface Alias {\n find: RegExp\n replacement: string\n}\n\n/** `tsconfig.base.json` carries `//` comments, which `JSON.parse` refuses. */\nconst stripLineComments = (json: string): string => json.replace(/^\\s*\\/\\/.*$/gm, '')\n\nconst toAlias = (workspaceRoot: string, pattern: string, target: string): Alias => {\n const escaped = pattern.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&').replace(/\\\\\\*/g, '(.*)')\n return {\n find: new RegExp(`^${escaped}$`),\n replacement: join(workspaceRoot, target.replace(/\\*/g, '$1')),\n }\n}\n\n/**\n * Read the mappings from the workspace's base tsconfig.\n *\n * Longest pattern first, because Vite takes the first alias that matches and the mappings\n * overlap by design: `@front/theme/node` must not be swallowed by `@front/theme`.\n */\nexport const tsconfigAliases = (workspaceRoot: string, file = 'tsconfig.base.json'): Alias[] => {\n const raw = readFileSync(join(workspaceRoot, file), 'utf8')\n const { compilerOptions } = JSON.parse(stripLineComments(raw)) as {\n compilerOptions?: { paths?: Record<string, string[]> }\n }\n return Object.entries(compilerOptions?.paths ?? {})\n .flatMap(([pattern, targets]) => {\n const [target] = targets\n return target === undefined ? [] : [toAlias(workspaceRoot, pattern, target)]\n })\n .sort((a, b) => b.find.source.length - a.find.source.length)\n}\n"],"mappings":";AA2FA,SAAS,kBAAkB;AAC3B,SAAS,qBAAqB;AAC9B,OAAO,UAAU;AAMjB,IAAM,oBAAoB;AAS1B,IAAM,sBAAsB,CAAC,qBAAqB,eAAe;AA6BjE,SAAS,aAAa,MAAyB;AAC7C,QAAMA,WAAU,cAAc,KAAK,KAAK,MAAM,SAAS,CAAC;AACxD,MAAI;AACJ,MAAI;AACF,eAAWA,SAAQ,YAAY;AAAA,EACjC,QAAQ;AACN,UAAM,IAAI;AAAA,MACR,2DAA2D,IAAI;AAAA,IAEjE;AAAA,EACF;AACA,MAAI,OAAO,SAAS,kBAAkB,YAAY;AAChD,UAAM,IAAI;AAAA,MACR,sDAAsD,IAAI,KAAK,SAAS,WAAW,SAAS;AAAA,IAI9F;AAAA,EACF;AACA,SAAO;AACT;AAEA,SAAS,gBAAgB,SAA2C;AAClE,MAAI,QAAQ,UAAU;AACpB,UAAM,WAAW,KAAK,QAAQ,QAAQ,MAAM,QAAQ,QAAQ;AAC5D,QAAI,CAAC,WAAW,QAAQ,GAAG;AACzB,YAAM,IAAI,MAAM,+CAA+C,QAAQ,EAAE;AAAA,IAC3E;AACA,WAAO;AAAA,EACT;AACA,aAAW,aAAa,qBAAqB;AAC3C,UAAM,QAAQ,KAAK,KAAK,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SAAY,CAAC,IAAI,CAAC,QAAQ,eAAe,SAAS,MAAM,CAAC;AAAA,EAC7E,CAAC,EACA,KAAK,CAAC,GAAG,MAAM,EAAE,KAAK,OAAO,SAAS,EAAE,KAAK,OAAO,MAAM;AAC/D;","names":["require"]}
@@ -0,0 +1,70 @@
1
+ import {
2
+ findWorkspaceRoot
3
+ } from "./chunk-WLFE5RUU.js";
4
+
5
+ // src/roles/test/setup/workspace.ts
6
+ import { createRequire } from "module";
7
+ import { join } from "path";
8
+ function isMissingModule(error) {
9
+ return error?.code === "ERR_MODULE_NOT_FOUND";
10
+ }
11
+ async function optional(specifier, use) {
12
+ try {
13
+ use(await import(
14
+ /* @vite-ignore */
15
+ specifier
16
+ ));
17
+ } catch (error) {
18
+ if (!isMissingModule(error)) throw error;
19
+ }
20
+ }
21
+ function fromModule(specifier) {
22
+ try {
23
+ const require2 = createRequire(join(process.cwd(), "noop.cjs"));
24
+ return require2(specifier);
25
+ } catch {
26
+ return void 0;
27
+ }
28
+ }
29
+ async function loadEnvironment() {
30
+ await optional("dotenv-flow", (module) => {
31
+ const flow = module;
32
+ const config = flow.config ?? flow.default?.config;
33
+ const workspaceRoot = findWorkspaceRoot(process.cwd());
34
+ config?.({
35
+ silent: true,
36
+ purge_dotenv: true,
37
+ ...workspaceRoot === void 0 ? {} : { path: workspaceRoot }
38
+ });
39
+ });
40
+ }
41
+ async function pinLuxonZone() {
42
+ let pinned = false;
43
+ await optional("luxon", (module) => {
44
+ const settings = module.Settings;
45
+ if (settings === void 0) return;
46
+ settings.defaultZone = "utc";
47
+ pinned = true;
48
+ });
49
+ if (pinned) return;
50
+ const own = fromModule("luxon");
51
+ if (own?.Settings !== void 0) {
52
+ own.Settings.defaultZone = "utc";
53
+ return;
54
+ }
55
+ process.stderr.write(
56
+ "sentinel (test): luxon was not found in this module, so the UTC default zone is NOT pinned. Dates will follow the machine zone, as they did not under jest.\n"
57
+ );
58
+ }
59
+ async function installWorkspaceSetup() {
60
+ await loadEnvironment();
61
+ }
62
+ async function pinWorkspaceTimezone() {
63
+ await pinLuxonZone();
64
+ }
65
+
66
+ export {
67
+ installWorkspaceSetup,
68
+ pinWorkspaceTimezone
69
+ };
70
+ //# sourceMappingURL=chunk-CPCUPK4J.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/roles/test/setup/workspace.ts"],"sourcesContent":["/**\n * The rest of what a migrated suite needs before its tests, loaded DEFENSIVELY.\n *\n * ## Why this is in sentinel and not in the repo\n *\n * Because it is config, and an app must depend on its own config and nothing outside it. The first\n * version of the generated config referenced `'../../../../vitest.setup.mts'`, a relative path\n * climbing four levels to the workspace root — which is exactly the external link this whole\n * migration exists to remove. A module that reaches outside itself cannot move on its own.\n *\n * ## Why loading is conditional, and why that is the point rather than a precaution\n *\n * Unlike the msw lifecycle beside it, nothing here reacts to the RUNNER. `dotenv-flow` and luxon's\n * zone would behave identically under jest, Vitest or `node:test`; what they react to is the REPO,\n * which chose those two packages. So the conditional load is the statement of ownership: sentinel\n * offers the behaviour, and the repo that installed the package decides whether it happens.\n *\n * That is also what keeps sentinel installable elsewhere. Neither package can be a hard dependency,\n * so each is loaded only if present and skipped in silence if not. Elsewhere this file does nothing;\n * here both are present and the behaviour is the one the jest setup had.\n *\n * Silence is the right answer for an absent package and the wrong one for a broken package, so a\n * load that fails for any other reason is re-thrown rather than swallowed.\n */\nimport { createRequire } from 'node:module'\nimport { join } from 'node:path'\n\nimport { findWorkspaceRoot } from '../../../core/workspace-prep.js'\n\n/** Was this module absent, as opposed to present and broken? */\nfunction isMissingModule(error: unknown): boolean {\n return (error as { code?: string } | null)?.code === 'ERR_MODULE_NOT_FOUND'\n}\n\n/**\n * Optional by construction: `import()` inside a try, so a missing package is a no-op rather than a\n * failure at load time. A static import would make every one of them a hard dependency.\n */\nasync function optional(specifier: string, use: (module: unknown) => void): Promise<void> {\n try {\n use(await import(/* @vite-ignore */ specifier))\n } catch (error) {\n if (!isMissingModule(error)) throw error\n }\n}\n\n/**\n * The MODULE's copy of a package, not sentinel's.\n *\n * Under pnpm, an import written here resolves from sentinel's own directory, so it sees only\n * sentinel's dependencies. That is right for anything whose effect is GLOBAL, and wrong for\n * anything whose effect is per-copy: pinning `Settings.defaultZone` on sentinel's luxon leaves\n * the module's luxon in the machine's local zone, and the tests drift by an hour twice a year\n * with nothing saying why.\n *\n * Measured 2026-09-21: neither `luxon` nor `dotenv-flow` resolves from sentinel, while both\n * resolve from the module under test. The silent `optional` above therefore skipped BOTH, so a\n * migrated suite lost the `.env` cascade and the UTC pin at once, without a word.\n */\nfunction fromModule(specifier: string): unknown | undefined {\n try {\n const require = createRequire(join(process.cwd(), 'noop.cjs'))\n return require(specifier)\n } catch {\n return undefined\n }\n}\n\n/**\n * `dotenv-flow`, which the root jest setup loaded first.\n *\n * Vite's own `.env` handling does NOT replace it, which was checked before writing this. Measured on\n * Vitest 4 against a fixture holding `.env` and `.env.test`: the cascade is read and `MODE` is\n * `test`, but only `VITE_`-prefixed values are exposed, and only on `import.meta.env`. `process.env`\n * comes back untouched, and the code under test reads unprefixed `process.env`.\n *\n * `purge_dotenv` is carried across: it clears variables a previous load left behind, and without it\n * a value from one run leaks into the next. Not a detail in a suite that asserts on URLs.\n */\nasync function loadEnvironment(): Promise<void> {\n // A plain dependency of sentinel now: it mutates `process.env`, which is global, so WHICH copy\n // runs does not matter. It is the other half of replacing the root setup, and the root is going\n // away (Héla, 2026-09-21: \"mon but est de supprimer la config root\").\n await optional('dotenv-flow', (module) => {\n const flow = module as {\n config?: (options: Record<string, unknown>) => void\n default?: unknown\n }\n const config =\n flow.config ?? (flow.default as { config?: (o: Record<string, unknown>) => void })?.config\n /*\n * From the WORKSPACE ROOT, not from the module.\n *\n * dotenv-flow reads its cascade from the current directory, and the two runners do not share\n * one: jest ran from the repo root, where `.env`, `.env.test` and `.env.token` live, while\n * `sentinel --run --test` runs from the module, where there is nothing to read. Measured on\n * `libs/cloud/events-notifications`: from the module, a service call waits for an endpoint its\n * env never named and the test dies on a 5 s timeout; from the root, it answers in 200 ms.\n *\n * The root is found rather than configured: the setup cannot be handed a value, since a module\n * that overrides `test.env` would replace whatever the preset injected there.\n */\n const workspaceRoot = findWorkspaceRoot(process.cwd())\n config?.({\n silent: true,\n purge_dotenv: true,\n ...(workspaceRoot === undefined ? {} : { path: workspaceRoot }),\n })\n })\n}\n\n/**\n * Luxon's default zone, carried as luxon's own setting and NOT translated to `process.env.TZ`.\n *\n * They are different instructions: one configures luxon, the other the whole process, `Date` and\n * `Intl` included. Swapping them would change what a suite does while claiming to migrate it, and\n * timezone is not a detail here — a machine's zone accounted for a large part of 345 local failures\n * on `host-admin` that did not exist in CI.\n */\nasync function pinLuxonZone(): Promise<void> {\n // The module's copy, deliberately: `Settings` is per-copy state, so sentinel's own luxon is the\n // one package this setup must NOT configure.\n /*\n * Through the RUNNER's resolver first, which is what the tests use. `fromModule` goes through\n * `require`, and a package shipping both builds hands it the CJS one while Vite hands the tests\n * the ESM one. Two copies, two `Settings`, and the pin lands on the one nobody reads: measured on\n * `libs/cloud/events-notifications`, whose suite ran in `Europe/Paris` and compared timestamps\n * two hours apart. The preset aliases luxon to one path so both routes agree.\n */\n let pinned = false\n await optional('luxon', (module) => {\n const settings = (module as { Settings?: { defaultZone: string } }).Settings\n if (settings === undefined) return\n settings.defaultZone = 'utc'\n pinned = true\n })\n if (pinned) return\n\n const own = fromModule('luxon') as { Settings?: { defaultZone: string } } | undefined\n if (own?.Settings !== undefined) {\n own.Settings.defaultZone = 'utc'\n return\n }\n\n // Said out loud rather than skipped: a suite whose dates silently run in the machine's zone is\n // the kind of failure that gets blamed on the migration months later.\n process.stderr.write(\n 'sentinel (test): luxon was not found in this module, so the UTC default zone is NOT pinned. ' +\n 'Dates will follow the machine zone, as they did not under jest.\\n',\n )\n}\n\n/**\n * Everything the workspace needs beyond the msw lifecycle.\n *\n * NOT included: the `jest.mock('dynamoose')` and `jest.mock('@opentelemetry/exporter-metrics-otlp-grpc')`\n * calls the jest setup made. A module mock is a per-suite decision that `vi.mock` must make in the\n * file that needs it, and hoisting it into a shared setup is what makes a test pass for a reason\n * nobody can see. The migration reports them instead, so the module that relies on one declares it.\n */\nexport async function installWorkspaceSetup(): Promise<void> {\n await loadEnvironment()\n}\n\n/**\n * Luxon's default zone, split out because it is not in the same class as the rest.\n *\n * ⚠️ These two were one function until 23/09 and moving them together broke three modules.\n *\n * The `.env` cascade is needed by any suite whose code reads `process.env`, whatever setup its\n * jest config named: under jest those modules got it from a `globalSetup` running in the main\n * process, and Vitest's workers do not inherit it the same way. Removing it cost\n * `libs/front/logic` 23 tests and `libs/front/api` 44, all with `missing env var\n * NEXT_PUBLIC_MONOREPO_BASE_URL`.\n *\n * The UTC pin is a decision ONE file at the workspace root made, and only the modules naming that\n * file ever had it. So it is conditional and the cascade is not.\n */\nexport async function pinWorkspaceTimezone(): Promise<void> {\n await pinLuxonZone()\n}\n"],"mappings":";;;;;AAwBA,SAAS,qBAAqB;AAC9B,SAAS,YAAY;AAKrB,SAAS,gBAAgB,OAAyB;AAChD,SAAQ,OAAoC,SAAS;AACvD;AAMA,eAAe,SAAS,WAAmB,KAA+C;AACxF,MAAI;AACF,QAAI,MAAM;AAAA;AAAA,MAA0B;AAAA,KAAU;AAAA,EAChD,SAAS,OAAO;AACd,QAAI,CAAC,gBAAgB,KAAK,EAAG,OAAM;AAAA,EACrC;AACF;AAeA,SAAS,WAAW,WAAwC;AAC1D,MAAI;AACF,UAAMA,WAAU,cAAc,KAAK,QAAQ,IAAI,GAAG,UAAU,CAAC;AAC7D,WAAOA,SAAQ,SAAS;AAAA,EAC1B,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAaA,eAAe,kBAAiC;AAI9C,QAAM,SAAS,eAAe,CAAC,WAAW;AACxC,UAAM,OAAO;AAIb,UAAM,SACJ,KAAK,UAAW,KAAK,SAA+D;AAatF,UAAM,gBAAgB,kBAAkB,QAAQ,IAAI,CAAC;AACrD,aAAS;AAAA,MACP,QAAQ;AAAA,MACR,cAAc;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