@hublo/sentinel 1.4.0-alpha.9 → 1.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/README.md +1 -0
  2. package/dist/bin/sentinel.js +45 -101
  3. package/dist/{chunk-7PUVK4YM.js → chunk-5VNYQIFD.js} +224 -13
  4. package/dist/chunk-5VNYQIFD.js.map +1 -0
  5. package/dist/chunk-DYJ6J43A.js +6419 -0
  6. package/dist/chunk-ELZHIN6E.js +16 -0
  7. package/dist/chunk-ELZHIN6E.js.map +1 -0
  8. package/dist/{chunk-L7WS36XV.js → chunk-GRK2KRFI.js} +221 -4427
  9. package/dist/chunk-H3GSGAX2.js +11 -0
  10. package/dist/chunk-H3GSGAX2.js.map +1 -0
  11. package/dist/{chunk-WLFE5RUU.js → chunk-KMKQDGI6.js} +6 -8
  12. package/dist/chunk-KMKQDGI6.js.map +1 -0
  13. package/dist/{chunk-PWV3BMDA.js → chunk-MMKBDO5V.js} +11 -2
  14. package/dist/chunk-MMKBDO5V.js.map +1 -0
  15. package/dist/chunk-NUOQXAYR.js +14 -0
  16. package/dist/chunk-NUOQXAYR.js.map +1 -0
  17. package/dist/chunk-O7REVMOC.js +38 -0
  18. package/dist/chunk-O7REVMOC.js.map +1 -0
  19. package/dist/chunk-QXFCZON7.js +16 -0
  20. package/dist/chunk-QXFCZON7.js.map +1 -0
  21. package/dist/{chunk-3TDUIKVQ.js → chunk-SWWQ7X7B.js} +11 -8
  22. package/dist/{chunk-3TDUIKVQ.js.map → chunk-SWWQ7X7B.js.map} +1 -1
  23. package/dist/{chunk-CPCUPK4J.js → chunk-Z7L4FGKP.js} +5 -12
  24. package/dist/chunk-Z7L4FGKP.js.map +1 -0
  25. package/dist/index.d.ts +28 -5
  26. package/dist/index.js +7 -3
  27. package/dist/roles/build/nest/toolchain.js +11 -33
  28. package/dist/roles/build/nest/toolchain.js.map +1 -1
  29. package/dist/roles/test/nest/toolchain.js +3 -2
  30. package/dist/roles/test/nest/toolchain.js.map +1 -1
  31. package/dist/roles/test/react/toolchain.js +3 -2
  32. package/dist/roles/test/react/toolchain.js.map +1 -1
  33. package/dist/roles/test/setup/a11y.d.ts +45 -0
  34. package/dist/roles/test/setup/a11y.js +72 -0
  35. package/dist/roles/test/setup/a11y.js.map +1 -0
  36. package/dist/roles/test/setup/file-boundary-close.d.ts +2 -0
  37. package/dist/roles/test/setup/file-boundary-close.js +8 -0
  38. package/dist/roles/test/setup/file-boundary-close.js.map +1 -0
  39. package/dist/roles/test/setup/file-boundary.d.ts +2 -0
  40. package/dist/roles/test/setup/file-boundary.js +62 -0
  41. package/dist/roles/test/setup/file-boundary.js.map +1 -0
  42. package/dist/roles/test/setup/jest-parity.js +19 -2
  43. package/dist/roles/test/setup/jest-parity.js.map +1 -1
  44. package/dist/roles/test/setup/msw-lifecycle.js +2 -1
  45. package/dist/roles/test/setup/msw-lifecycle.js.map +1 -1
  46. package/dist/roles/test/setup/msw-server.js +2 -1
  47. package/dist/roles/test/setup/msw-server.js.map +1 -1
  48. package/dist/roles/test/setup/w3c.d.ts +75 -0
  49. package/dist/roles/test/setup/w3c.js +49 -0
  50. package/dist/roles/test/setup/w3c.js.map +1 -0
  51. package/dist/roles/test/setup/workspace-entry.js +3 -2
  52. package/dist/roles/test/setup/workspace-entry.js.map +1 -1
  53. package/dist/roles/test/shared-test-config.d.ts +13 -0
  54. package/dist/roles/test/shared-test-config.js +3 -2
  55. package/dist/validate-57H7GK5B.js +170 -0
  56. package/docs/test-adoption.md +282 -5
  57. package/docs/using-sentinel.md +17 -1
  58. package/docs/validating-a-change.md +35 -2
  59. package/package.json +25 -1
  60. package/types/jest-global.d.ts +85 -0
  61. package/types/mock-extended.d.ts +52 -0
  62. package/dist/chunk-7PUVK4YM.js.map +0 -1
  63. package/dist/chunk-CPCUPK4J.js.map +0 -1
  64. package/dist/chunk-PWV3BMDA.js.map +0 -1
  65. package/dist/chunk-WLFE5RUU.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/roles/test/setup/jest-parity.ts","../../../../src/roles/test/setup/constructor-semantics.ts","../../../../src/roles/test/setup/deep-mock-reset.ts","../../../../src/roles/test/setup/error-equality.ts","../../../../src/roles/test/setup/fake-timers.ts","../../../../src/roles/test/setup/jest-global.ts","../../../../src/roles/test/setup/mock-reset.ts","../../../../src/roles/test/setup/rejected-function.ts"],"sourcesContent":["/**\n * The setup any migrated suite runs before its tests, as ONE entry point.\n *\n * Referenced by name from a generated config, never by a relative path:\n * `setupFiles: ['@hublo/sentinel/test/setup/jest-parity']`. Measured: Vitest resolves a bare\n * package specifier there, so nothing has to know where sentinel sits relative to the module.\n *\n * ⚠️ This was exported as `test/setup/nest` until 23/09, which was wrong in the one place it is\n * read. Nothing below is Nest-specific: every line restores a `jest.*` semantic under Vitest, plus\n * the `.env` cascade. But the name is COMMITTED into each adopting module's config, so a React\n * module ended up with `setupFiles: ['@hublo/sentinel/test/setup/nest', './jest.setup.js']` sitting\n * in its repository, which reads like the bug where a module was handed the wrong family's preset.\n * A reviewer cannot tell that apart from the real thing without opening our source. The name says\n * what the file does instead: parity with jest.\n *\n * ## What it replaces, line for line\n *\n * The repo's root `jest.setup.after.env.js`, loaded by 99 of the 111 jest configs:\n *\n * require('dotenv-flow').config({ silent: true, purge_dotenv: true })\n * const { Settings } = require('luxon')\n * const { server } = require('./libs/nest/tests/src/msw/server')\n * jest.mock('dynamoose')\n * jest.mock('@opentelemetry/exporter-metrics-otlp-grpc')\n * beforeAll(() => server.listen({ onUnhandledRequest: 'error' }))\n * afterEach(() => { if (global.gc) global.gc() })\n * afterAll(() => server.close())\n * Settings.defaultZone = 'utc'\n *\n * Everything here is a transcription of that, not an improvement on it. Where the original made a\n * choice that looks questionable, the choice is carried across and reported, because a migration\n * that also changes behaviour cannot be verified against its own baseline.\n *\n * ONE line is not transcribed: `server.listen()` also runs when this file is evaluated, not only\n * inside `beforeAll`. The runners differ on when a module's exports can still be patched, so the\n * original placement silently disabled interception under Vitest and let tests reach the real\n * internet. `./msw.js` carries the measurement.\n *\n * ## Two halves, and why one of them is loaded defensively\n *\n * The msw lifecycle used to live here and now has its own file, `./msw-lifecycle.js`, added to a\n * module's `setupFiles` only when that module actually uses msw. Installing it everywhere patches\n * `http`/`https` and refuses unmatched requests for modules that never asked: measured on\n * `libs/nest/starter`, 11 of 11 became 10 of 11 with `TypeError: Invalid URL` in the interceptor,\n * on a test fetching the Fastify server the suite starts itself.\n *\n * `dotenv-flow` and luxon's zone react to the REPO, not to the runner: they would read the same\n * under jest, Vitest or `node:test`. So `./workspace.js` loads them only if they are installed and\n * skips them in silence otherwise. That defensiveness is not a precaution bolted on, it IS the\n * statement that these belong to whoever installed them. Elsewhere, sentinel installs and that half\n * does nothing.\n *\n * `dotenv-flow` cannot simply be dropped in favour of Vite's own `.env` handling, which was the\n * first thing checked. Measured on Vitest 4: it does read the cascade and sets `MODE=test`, but it\n * exposes only `VITE_`-prefixed values, and only on `import.meta.env`. `process.env` is left\n * untouched, and Nest code reads unprefixed `process.env`.\n *\n * ## What is NOT here\n *\n * The two `jest.mock` calls. A module mock is a per-suite decision that `vi.mock` must make in the\n * file that needs it; hoisting it into a shared setup is what makes a test pass for a reason nobody\n * can see. The migration reports them so the module relying on one declares it.\n *\n * And `Settings.defaultZone = 'utc'` is carried as luxon's own setting, never translated to\n * `process.env.TZ`. One configures luxon, the other the whole process, `Date` and `Intl` included.\n * Swapping them would change what the suite does while claiming to migrate it, and timezone is not\n * a detail: measured on `host-admin`, a machine's zone accounted for a large part of 345 local\n * failures that did not exist in CI.\n */\nimport { expect, vi } from 'vitest'\n\nimport { installJestConstructorSemantics } from './constructor-semantics.js'\nimport { installDeepMockReset } from './deep-mock-reset.js'\nimport { installJestErrorEquality } from './error-equality.js'\nimport { installJestFakeTimerOptions } from './fake-timers.js'\nimport { installJestGlobal } from './jest-global.js'\nimport { installJestMockReset } from './mock-reset.js'\nimport { installJestRejectedFunction } from './rejected-function.js'\nimport { installWorkspaceSetup } from './workspace.js'\n\ninstallJestErrorEquality(expect)\ninstallJestMockReset(vi)\ninstallJestConstructorSemantics(vi)\ninstallDeepMockReset(vi)\ninstallJestFakeTimerOptions(vi)\ninstallJestRejectedFunction()\ninstallJestGlobal(vi)\n\n/*\n * The `.env` cascade, unconditionally: a suite reading `process.env` needs it whatever setup its\n * jest config named, because Vitest's workers do not inherit what a `globalSetup` set in the main\n * process. Awaited at the top level, so it is loaded before the first test file is imported: a\n * module read at import time would already have captured an unset variable.\n *\n * ⚠️ What is NOT here any more is luxon's UTC zone. That was a decision ONE file at the workspace\n * root made, and only the 97 modules naming it ever had it; it lives in\n * `@hublo/sentinel/test/setup/workspace`, which the generated config adds only for those.\n */\nawait installWorkspaceSetup()\n","/**\n * `new` on a mock, the way jest answered it.\n *\n * ## The divergence, measured on the same source under both runners\n *\n * jest vitest\n * mockImplementation(() => obj), then new the obj TypeError: not a constructor\n * mockImplementation(function(){}), new works works\n * mockReturnValue(obj), then new the obj TypeError, with an explanation\n *\n * jest calls the implementation as a PLAIN function when the mock is constructed and hands back\n * what it returned. Vitest applies real `new` semantics, and an arrow function has no [[Construct]]\n * slot, so it throws.\n *\n * The pattern this breaks is the ordinary way to stand in for a class: automock the module, then\n * say what `new` should give back.\n *\n * jest.mock('@hublo/cloud/event-scheduler-sdk')\n * ;(EventSchedulerSDK as jest.MockedClass<typeof EventSchedulerSDK>)\n * .mockImplementation(() => mockEventSchedulerSDK)\n *\n * Measured across the nest and cloud campaigns: 2 modules, 15 tests.\n * `apps/nest/microservices/client-management` (9, an SDK) and `apps/nest/microservices/hublo-pool`\n * (6, a mocked `Date`).\n *\n * ## Why this is safe to do for everybody, which is the part that matters\n *\n * It only changes a case that THROWS today. An implementation without a `prototype` cannot be\n * constructed at all under Vitest, so no suite anywhere can be relying on what it does: the only\n * behaviours available are \"throws\" and \"answers like jest\". Nothing that works today changes\n * shape, and a constructable implementation is passed through untouched.\n *\n * That bound is asserted by the tests, not just claimed here.\n *\n * ## `mockReturnValue(obj)` then `new`, which this used to leave alone\n *\n * It was left out on the grounds that answering it would decide \"a return value and a constructed\n * instance are the same thing\", a claim about the suite. That reading was wrong on both halves.\n *\n * It is not a claim about the suite, because jest's answer is not ambiguous: it hands back the\n * value, exactly as it does for `mockImplementation(() => obj)`, which this file already restores.\n * Treating the two differently would be the arbitrary choice.\n *\n * And \"no module in this repo hit it\" stopped being true the moment the front family was measured.\n * `libs/front/components` mocks Google Maps the ordinary way and constructs it:\n *\n * AutocompleteService: jest.fn().mockReturnValue({ getPlacePredictions: jest.fn() })\n * // and the hook: new window.google.maps.places.AutocompleteService()\n *\n * 7 tests, all with the same TypeError. The safety bound is unchanged and it is the whole reason\n * this is allowed: Vitest THROWS on that call today, so no suite anywhere can depend on what it\n * does, and the only behaviours available are \"throws\" and \"answers like jest\".\n *\n * Expressed by routing the value through the implementation, rather than by a second mechanism:\n * `mockReturnValue(v)` IS `mockImplementation(() => v)`, so it goes through the same wrapper and\n * `new` works for the same reason.\n */\n\n/** The mocking surface this touches. Vitest's own type is not needed to say it. */\ninterface MockLike {\n mockImplementation(implementation: (...args: unknown[]) => unknown): unknown\n mockImplementationOnce(implementation: (...args: unknown[]) => unknown): unknown\n mockReturnValue(value: unknown): unknown\n mockReturnValueOnce(value: unknown): unknown\n}\n\ninterface ViLike {\n fn(implementation?: (...args: unknown[]) => unknown): MockLike\n /**\n * ⚠️ The REST, not `(target, key)`.\n *\n * Vitest's third argument is the access type, `'get'` or `'set'`, and the first version of the\n * wrapper below forwarded two arguments and dropped it. `vi.spyOn(el, 'scrollWidth', 'get')`\n * then became a spy on the VALUE of an accessor that only exists on a prototype, and jsdom\n * answered `'get scrollWidth' called on an object that is not a valid instance of Element`.\n *\n * Measured on `libs/front/components`, 2 tests, and invisible to every nest module because none\n * of them spies on a DOM accessor.\n */\n spyOn(target: object, ...rest: unknown[]): MockLike\n}\n\n/**\n * Can this function be used with `new`?\n *\n * Asked of the `prototype` property rather than of the source text: an arrow function, a shorthand\n * method and a bound function all lack it, and all three are exactly the cases that throw. A\n * class and a plain `function` have it.\n */\nfunction constructable(value: unknown): boolean {\n return (\n typeof value === 'function' && Object.getOwnPropertyDescriptor(value, 'prototype') !== undefined\n )\n}\n\n/**\n * The same implementation, reachable through `new`.\n *\n * A plain `function` that forwards the call and RETURNS the result. JavaScript's own `new` then\n * hands that object back, which is what jest did, so nothing here imitates jest by hand: it\n * restores the one property the arrow was missing and lets the language do the rest.\n */\nfunction asConstructable(\n implementation: (...args: unknown[]) => unknown,\n): (...args: unknown[]) => unknown {\n if (constructable(implementation)) return implementation\n\n return function forwarded(this: unknown, ...args: unknown[]): unknown {\n return implementation.apply(this, args)\n }\n}\n\n/**\n * Wrap `vi.fn` and `vi.spyOn` so every mock they produce accepts `new` the way jest's did.\n *\n * Wrapped at the factory, like `installJestMockReset`, because the behaviour belongs to every mock\n * a suite makes and a suite should not have to ask for it.\n */\nexport function installJestConstructorSemantics(vi: ViLike): void {\n const patch = (mock: MockLike): MockLike => {\n const { mockImplementation, mockImplementationOnce } = mock\n\n mock.mockImplementation = function (implementation) {\n return mockImplementation.call(this, asConstructable(implementation))\n }\n mock.mockImplementationOnce = function (implementation) {\n return mockImplementationOnce.call(this, asConstructable(implementation))\n }\n\n /*\n * Routed through the implementation rather than given a mechanism of its own: the two are the\n * same statement, and one of them already accepts `new`.\n */\n mock.mockReturnValue = function (value) {\n return this.mockImplementation(() => value)\n }\n mock.mockReturnValueOnce = function (value) {\n return this.mockImplementationOnce(() => value)\n }\n return mock\n }\n\n const { fn, spyOn } = vi\n\n vi.fn = function (implementation) {\n return patch(fn.call(this, implementation && asConstructable(implementation)))\n }\n vi.spyOn = function (target, ...rest) {\n return patch(spyOn.call(this, target, ...rest))\n }\n}\n","/**\n * `vi.resetAllMocks()` reaching the deep mocks, the way jest's registry did.\n *\n * ## The divergence, and why it is invisible\n *\n * jest built `jest-mock-extended`'s mocks with `jest.fn()`, so they sat in jest's own registry and\n * `jest.resetAllMocks()` cleared them with everything else. `vitest-mock-extended` builds them its\n * own way, so `vi.resetAllMocks()` walks past them and their call history survives into the next\n * test.\n *\n * Nothing announces it. The suite still runs, and an assertion fails several tests later with a\n * count that is off by exactly what its neighbour did.\n *\n * Measured on `apps/nest/microservices/activity`, whose suite does 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 one before them. Each\n * PASSES on its own and fails as soon as its neighbour runs first, which is the signature of\n * leakage rather than of a wrong assertion.\n *\n * ## What this installs, and what it leaves alone\n *\n * `resetAllMocks` and `clearAllMocks` do what they did, then extend to the deep mocks: `reset`\n * drops implementations as well as calls, `clear` drops only calls, which is the same distinction\n * the two names already carry.\n *\n * `restoreAllMocks` is NOT extended. It restores spies to their originals, and a deep mock has no\n * original to go back to: it was invented. Extending it would mean deciding what \"restore\" means\n * for something that never existed, which is a claim, not a translation.\n */\nimport { clearDeepMocks, resetDeepMocks } from './mock-extended.js'\n\n/** The part of `vi` this touches. Vitest's own type is not needed to say it. */\ninterface ViLike {\n resetAllMocks(): unknown\n clearAllMocks(): unknown\n}\n\nexport function installDeepMockReset(vi: ViLike): void {\n const { resetAllMocks, clearAllMocks } = vi\n\n vi.resetAllMocks = function extended(this: unknown): unknown {\n const answer = resetAllMocks.call(this)\n resetDeepMocks()\n return answer\n }\n\n vi.clearAllMocks = function extended(this: unknown): unknown {\n const answer = clearAllMocks.call(this)\n clearDeepMocks()\n return answer\n }\n}\n","/**\n * How two `Error` values compare, which the two runners disagree about.\n *\n * A suite that asserts on a thrown or captured error usually writes the error it expects by hand:\n *\n * expect(save).toHaveBeenCalledWith({ error: new AxiosError('Request failed with status code 500'), ... })\n *\n * Under jest that passes whatever else the real error carries. Under Vitest it fails, and the\n * report is 6600 lines of an axios error's `config`, `request` and `response`, which reads like a\n * broken test rather than a runner difference.\n *\n * ## What each runner actually does, measured on the same four cases\n *\n * | two errors | jest 29 | Vitest 4 |\n * | --------------------------------- | -------- | ----------- |\n * | same message, same type | equal | equal |\n * | same message, DIFFERENT types | equal | not equal |\n * | same message, extra properties | equal | not equal |\n * | different messages | not equal| not equal |\n *\n * jest compares errors by their MESSAGE and nothing else: a `TypeError` and a `RangeError` with the\n * same text are equal to it. Vitest compares the type and the own properties too.\n *\n * ## Why the looser rule is the one restored\n *\n * Because it is the one 3481 test files were written against. Tightening it here would turn green\n * tests red during a migration whose whole promise is that the suite means the same thing\n * afterwards, and a baseline gate cannot tell that kind of loss from a real one.\n *\n * The question is reported rather than settled: comparing the type as well would be a better rule,\n * and it may cost nothing on this corpus. That is a measurement to run and a change to make on its\n * own, once the suites no longer move. Measured need so far: `libs/cloud/shared`, whose last\n * missing test was exactly this.\n */\nimport type { expect as ExpectApi } from 'vitest'\n\n/**\n * Restore jest's rule: two errors are equal when their messages are.\n *\n * Returning `undefined` for anything else hands the pair back to the default comparison, which is\n * what an equality tester is expected to do for values it has no opinion about.\n */\nexport function errorsCompareByMessage(left: unknown, right: unknown): boolean | undefined {\n if (left instanceof Error && right instanceof Error) return left.message === right.message\n return undefined\n}\n\nexport function installJestErrorEquality(expect: typeof ExpectApi): void {\n expect.addEqualityTesters([errorsCompareByMessage])\n}\n","/**\n * `useFakeTimers({ doNotFake: [...] })`, which Vitest accepts and ignores.\n *\n * jest names what to LEAVE ALONE, Vitest names what to FAKE. The option Vitest does not know is\n * dropped in silence, so a suite that carefully kept `setTimeout` real gets it faked, and anything\n * awaiting a timer never resolves.\n *\n * Measured on both runners with the same source:\n *\n * useFakeTimers({ doNotFake: ['setTimeout'] }) jest: setTimeout real Vitest: setTimeout FAKED\n * useFakeTimers({ toFake: ['Date'] }) Vitest: setTimeout real\n *\n * Found on `libs/cloud/events-notifications`: 4 tests in one file died on `Test timed out in\n * 5000ms` with nothing else to show, because the code under test awaits a real timer. The repo has\n * 2 files using `doNotFake`, the other in `apps/nest/microservices/institution`.\n *\n * ## The translation, and what it inherits\n *\n * `doNotFake: [a, b]` becomes `toFake: <everything the runner fakes by default> minus [a, b]`. The\n * default set is Vitest's, measured rather than assumed, and NOT jest's, which is wider: jest also\n * fakes `nextTick`, `queueMicrotask` and the animation-frame pair. Subtracting from Vitest's own\n * default is what every other `useFakeTimers()` call in the corpus already gets, so this keeps one\n * behaviour for the whole migration instead of two.\n */\n\n/**\n * What `vi.useFakeTimers()` replaces when told nothing, measured on Vitest 4 by comparing each\n * global before and after the call.\n */\nconst FAKED_BY_DEFAULT = [\n 'setTimeout',\n 'clearTimeout',\n 'setInterval',\n 'clearInterval',\n 'setImmediate',\n 'clearImmediate',\n 'Date',\n 'performance',\n 'hrtime',\n] as const\n\n/** The options both runners take, plus the one only jest knows. */\ninterface TimerOptions {\n toFake?: string[]\n doNotFake?: string[]\n}\n\n/**\n * Turn \"leave these alone\" into \"fake those\", leaving anything else untouched.\n *\n * Exported for its own test: the translation is the whole rule, and asserting it directly says more\n * than asserting that a wrapper was installed.\n */\nexport function withoutJestOnlyOptions<T>(options: T): T {\n const given = options as TimerOptions | undefined\n if (given?.doNotFake === undefined) return options\n\n const { doNotFake, ...rest } = given\n const base = rest.toFake ?? [...FAKED_BY_DEFAULT]\n\n return { ...rest, toFake: base.filter((timer) => !doNotFake.includes(timer)) } as T\n}\n\n/**\n * The one function this touches, named by its shape rather than by Vitest's type.\n *\n * `Options` is the caller's own parameter type: the wrapper hands back exactly what it was given,\n * minus the option Vitest does not know, so it must not narrow what the runner accepts.\n */\ninterface FakeTimerApi<Options> {\n useFakeTimers: (options?: Options) => unknown\n}\n\n/** Wrap `vi.useFakeTimers` so a jest-shaped options object still means what it said. */\nexport function installJestFakeTimerOptions<Options>(vi: FakeTimerApi<Options>): void {\n const inherited = vi.useFakeTimers.bind(vi)\n vi.useFakeTimers = (options?: Options) => inherited(withoutJestOnlyOptions(options))\n}\n","/**\n * The `jest` global, kept alive for helpers that a migrating module is not allowed to edit.\n *\n * ## Why a module cannot solve this for itself\n *\n * The codemod rewrites a module's own test files. It does not rewrite files in OTHER projects, and\n * it must not: a shared helper is imported by modules still on jest, so migrating it would break\n * them, and leaving it breaks the migrated one. That is the constraint the whole per-module plan\n * rests on.\n *\n * But those helpers call the jest API at MODULE scope. `libs/front/tests/src/mocks/**` does\n * `jest.fn()` when it is imported, before any test runs, so a migrated module dies on\n * `ReferenceError: jest is not defined` the moment it imports one.\n *\n * Measured repo-wide, excluding documentation: **50 files use the jest API without being test\n * files**, in `jest.setup.js`, `*.mock.ts`, `*.test-helper.ts`, `*.test-wrapper.ts`. Three\n * independent hand migrations reached this same line without knowing about each other:\n * `libs/front/components` (8 shared helpers, 16 sites), `apps/nest/microservices/mission` and\n * `apps/nest/backends-for-frontends/admin`.\n *\n * ## It is `vi`, not a fake jest\n *\n * The global IS Vitest's `vi`, so anything Vitest does not have keeps failing loudly:\n * `jest.requireActual` and `jest.isolateModules` are still errors, and a module relying on them\n * still has to be migrated properly. Handing over a hand-written imitation would turn those into\n * silent wrong behaviour, which is the opposite of the point.\n *\n * ## ⚠️ What it does NOT cover, and this bound is measured\n *\n * `jest.mock()`. Vitest hoists mock registrations above the imports by scanning the source\n * STATICALLY, and that scan only recognises the receivers `vi` and `vitest` (`@vitest/mocker`,\n * `hoistMocksPlugin`). A `jest.mock()` left in place is therefore NOT hoisted: it runs after the\n * imports it was meant to intercept and does nothing at all, in silence. Measured on\n * `apps/front/front-legacy`, where 216 of 427 files call it.\n *\n * So this covers a helper that CALLS the jest API. It does not make an unmigrated test file work,\n * and the codemod's rename stays load-bearing rather than cosmetic.\n */\n\n/** The part of `vi` this installs. Vitest's own type is not needed to say it. */\ntype JestLike = object\n\n/**\n * Put `vi` on `globalThis` under the name `jest`.\n *\n * Assigned rather than defined with a getter: a helper may well write to it (`jest.fn = ...` in a\n * test double), and a getter-only property would throw where jest allowed it.\n */\nexport function installJestGlobal(vi: JestLike): void {\n ;(globalThis as Record<string, unknown>).jest = vi\n}\n","/**\n * What `mockReset()` leaves behind, which is where the two runners disagree most dangerously.\n *\n * jest REMOVES the implementation: a reset spy returns `undefined` and the real function is not\n * called. Vitest puts the ORIGINAL implementation back: a reset spy calls the real function again.\n *\n * Measured on both runners with the same source:\n *\n * after resetAllMocks() on a spy jest: undefined Vitest: the real function\n * after mockReset() on a spy jest: undefined Vitest: the real function\n * after mockReset() on fn(impl) jest: undefined Vitest: impl\n *\n * The shape this breaks is ordinary and common: a suite spies on a provider in `beforeAll` and\n * resets its mocks in `beforeEach`. Under jest the provider stayed neutralised for every test.\n * Under Vitest the first `beforeEach` hands the real provider back, and every test after it runs\n * the real code. Measured on `libs/cloud/events-notifications`, that meant real HTTP: 19 tests\n * failed on `captured a request without a matching request handler` for the hermes API and 23 more\n * timed out waiting on it. Nothing in any report named a reset.\n *\n * 240 files in this repo both spy and reset, in every family: 111 under `apps/nest`, 77 under\n * `libs/cloud`, 31 under `apps/front`.\n *\n * ## Why here and not in the 240 files\n *\n * Because a codemod would have to decide, per spy, whether the suite wanted the real function\n * back, and the answer is in the test's intent rather than in its text. The runner-level rule is\n * the one that was true for all 240 while they were written, so restoring it is the transcription\n * and rewriting them would be the guess.\n *\n * Vitest routes `vi.resetAllMocks()` through each mock's own `mockReset`, measured, so overriding\n * that method covers the bulk form as well as the direct one. `mockRestore` is untouched: it puts\n * the original back under both runners, which is what it is for.\n */\n\n/** The part of a mock this file touches. Vitest's own types are not needed to say it. */\ninterface ResettableMock {\n mockReset: () => unknown\n mockImplementation: (fn: (...args: unknown[]) => unknown) => unknown\n}\n\nfunction isResettable(value: unknown): value is ResettableMock {\n return (\n typeof value === 'function' &&\n typeof (value as Partial<ResettableMock>).mockReset === 'function' &&\n typeof (value as Partial<ResettableMock>).mockImplementation === 'function'\n )\n}\n\n/**\n * Make one mock forget its implementation on reset, as jest's did.\n *\n * The override is installed on the instance rather than on a prototype: mocks are functions with\n * their own properties, and there is no shared prototype to reach.\n */\nfunction resetLikeJest<T>(mock: T): T {\n if (!isResettable(mock)) return mock\n\n const inherited = mock.mockReset.bind(mock)\n mock.mockReset = () => {\n inherited()\n mock.mockImplementation(() => undefined)\n return mock\n }\n return mock\n}\n\n/** The two factories a suite gets its mocks from. */\ntype MockFactories = { fn: (...args: never[]) => unknown; spyOn: (...args: never[]) => unknown }\n\n/**\n * Wrap `vi.fn` and `vi.spyOn` so everything they hand out resets the way jest's did.\n *\n * Called with the `vi` a setup file imports, so nothing here reaches for a global.\n */\nexport function installJestMockReset(vi: MockFactories): void {\n for (const name of ['fn', 'spyOn'] as const) {\n const factory = vi[name].bind(vi) as (...args: never[]) => unknown\n vi[name] = ((...args: never[]) => resetLikeJest(factory(...args))) as MockFactories[typeof name]\n }\n}\n","/**\n * A rejected value that is a FUNCTION, which jest calls and Vitest does not.\n *\n * ## The divergence, measured rather than reasoned\n *\n * jest's `toThrow` decides what was thrown like this: under `.rejects` it uses the rejection\n * reason ONLY when that reason is an Error. Otherwise it falls through to the ordinary branch,\n * sees a function, and CALLS it, asserting on whatever that call throws.\n *\n * Probed on this repo under jest 29, with controls:\n *\n * reject(() => { throw new Error('some error') })\n * await expect(…).rejects.toThrow(new Error('some error')) -> passes\n * await expect(…).rejects.toThrow(new Error('other text')) -> fails\n * await expect(…).rejects.toThrow('other text') -> fails\n *\n * The two controls are what make the first line mean something: jest is not passing everything,\n * it really is comparing the message of the error the CALL produced.\n *\n * Vitest treats the rejection reason as the thrown value, so the assertion is made against a\n * function. A function has no `message`, and the failure reads\n * `Cannot read properties of undefined (reading 'indexOf')`, which names nothing near the cause.\n *\n * ## Where it shows, and what it is worth\n *\n * Measured across the nest campaign: 4 tests in 3 modules.\n * `apps/nest/microservices/worker` (1), `apps/nest/microservices/institution` (2) and\n * `apps/nest/microservices/mission` (1). All four write the same shape, a mock rejecting with a\n * thunk that throws, or a `throw <a function>`.\n *\n * ## What this changes, and what it cannot\n *\n * Only a case that CANNOT work today: under `.rejects`, a reason that is a function and not an\n * Error. Vitest has no useful behaviour there, so nothing that passes today changes shape. An\n * Error reason, a string, an object, a rejected value of any other kind, and every assertion\n * outside `.rejects` all reach Vitest's own matcher untouched.\n *\n * ⚠️ It is jest's behaviour, not a good one. A suite reaching it is asserting on a function it\n * never meant to hand over, and it passed by accident of the runner. Reproducing it is what keeps\n * the migration honest: the gate promises the suite means the same thing afterwards, and a test\n * that was green cannot be turned red by us and called a finding. The teams own the cleanup.\n */\nimport { chai } from 'vitest'\n\n/** The part of a chai assertion this touches. Chai's own types are not needed to say it. */\ninterface AssertionLike {\n _obj: unknown\n}\n\ntype Matcher = (this: AssertionLike, ...args: unknown[]) => unknown\n\n/**\n * What calling the function throws, or the function itself when it throws nothing.\n *\n * Returning it unchanged matters: a function that completes is not \"nothing was thrown\", and\n * handing Vitest the same value it had leaves the report exactly as it would have been.\n */\nfunction thrownByCalling(candidate: () => unknown): unknown {\n try {\n candidate()\n } catch (thrown) {\n return thrown\n }\n return candidate\n}\n\nexport function installJestRejectedFunction(): void {\n const { Assertion, util } = chai as unknown as {\n Assertion: { prototype: Record<string, unknown> }\n util: { flag(object: unknown, key: string): unknown }\n }\n\n for (const name of ['toThrow', 'toThrowError']) {\n const original = Assertion.prototype[name] as Matcher | undefined\n if (typeof original !== 'function') continue\n\n Assertion.prototype[name] = function patched(this: AssertionLike, ...args: unknown[]): unknown {\n const reason = this._obj\n const rejected = util.flag(this, 'promise') === 'rejects'\n\n if (rejected && typeof reason === 'function' && !(reason instanceof Error)) {\n this._obj = thrownByCalling(reason as () => unknown)\n }\n\n return original.apply(this, args)\n } as unknown as Matcher\n }\n}\n"],"mappings":";;;;;;;;;;AAqEA,SAAS,QAAQ,UAAU;;;ACoB3B,SAAS,cAAc,OAAyB;AAC9C,SACE,OAAO,UAAU,cAAc,OAAO,yBAAyB,OAAO,WAAW,MAAM;AAE3F;AASA,SAAS,gBACP,gBACiC;AACjC,MAAI,cAAc,cAAc,EAAG,QAAO;AAE1C,SAAO,SAAS,aAA4B,MAA0B;AACpE,WAAO,eAAe,MAAM,MAAM,IAAI;AAAA,EACxC;A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ACrCA,SAAS,YAAY;AAerB,SAAS,gBAAgB,WAAmC;AAC1D,MAAI;AACF,cAAU;AAAA,EACZ,SAAS,QAAQ;AACf,WAAO;AAAA,EACT;AACA,SAAO;AACT;AAEO,SAAS,8BAAoC;AAClD,QAAM,EAAE,WAAW,KAAK,IAAI;AAK5B,aAAW,QAAQ,CAAC,WAAW,cAAc,GAAG;AAC9C,UAAM,WAAW,UAAU,UAAU,IAAI;AACzC,QAAI,OAAO,aAAa,WAAY;AAEpC,cAAU,UAAU,IAAI,IAAI,SAAS,WAAgC,MAA0B;AAC7F,YAAM,SAAS,KAAK;AACpB,YAAM,WAAW,KAAK,KAAK,MAAM,SAAS,MAAM;AAEhD,UAAI,YAAY,OAAO,WAAW,cAAc,EAAE,kBAAkB,QAAQ;AAC1E,aAAK,OAAO,gBAAgB,MAAuB;AAAA,MACrD;AAEA,aAAO,SAAS,MAAM,MAAM,IAAI;AAAA,IAClC;AAAA,EACF;AACF;;;APPA,yBAAyB,MAAM;AAC/B,qBAAqB,EAAE;AACvB,gCAAgC,EAAE;AAClC,qBAAqB,EAAE;AACvB,4BAA4B,EAAE;AAC9B,4BAA4B;AAC5B,kBAAkB,EAAE;AAYpB,MAAM,sBAAsB;","names":["vi","vi","expect","vi","vi","vi"]}
1
+ {"version":3,"sources":["../../../../src/roles/test/setup/jest-parity.ts","../../../../src/roles/test/setup/constructor-semantics.ts","../../../../src/roles/test/setup/deep-mock-reset.ts","../../../../src/roles/test/setup/error-equality.ts","../../../../src/roles/test/setup/fake-timers.ts","../../../../src/roles/test/setup/jest-global.ts","../../../../src/roles/test/setup/mock-reset.ts","../../../../src/roles/test/setup/rejected-function.ts","../../../../src/roles/test/setup/worker-id.ts"],"sourcesContent":["/**\n * The setup any migrated suite runs before its tests, as ONE entry point.\n *\n * Referenced by name from a generated config, never by a relative path:\n * `setupFiles: ['@hublo/sentinel/test/setup/jest-parity']`. Measured: Vitest resolves a bare\n * package specifier there, so nothing has to know where sentinel sits relative to the module.\n *\n * ⚠️ This was exported as `test/setup/nest` until 23/09, which was wrong in the one place it is\n * read. Nothing below is Nest-specific: every line restores a `jest.*` semantic under Vitest, plus\n * the `.env` cascade. But the name is COMMITTED into each adopting module's config, so a React\n * module ended up with `setupFiles: ['@hublo/sentinel/test/setup/nest', './jest.setup.js']` sitting\n * in its repository, which reads like the bug where a module was handed the wrong family's preset.\n * A reviewer cannot tell that apart from the real thing without opening our source. The name says\n * what the file does instead: parity with jest.\n *\n * ## What it replaces, line for line\n *\n * The repo's root `jest.setup.after.env.js`, loaded by 99 of the 111 jest configs:\n *\n * require('dotenv-flow').config({ silent: true, purge_dotenv: true })\n * const { Settings } = require('luxon')\n * const { server } = require('./libs/nest/tests/src/msw/server')\n * jest.mock('dynamoose')\n * jest.mock('@opentelemetry/exporter-metrics-otlp-grpc')\n * beforeAll(() => server.listen({ onUnhandledRequest: 'error' }))\n * afterEach(() => { if (global.gc) global.gc() })\n * afterAll(() => server.close())\n * Settings.defaultZone = 'utc'\n *\n * Everything here is a transcription of that, not an improvement on it. Where the original made a\n * choice that looks questionable, the choice is carried across and reported, because a migration\n * that also changes behaviour cannot be verified against its own baseline.\n *\n * ONE line is not transcribed: `server.listen()` also runs when this file is evaluated, not only\n * inside `beforeAll`. The runners differ on when a module's exports can still be patched, so the\n * original placement silently disabled interception under Vitest and let tests reach the real\n * internet. `./msw.js` carries the measurement.\n *\n * ## Two halves, and why one of them is loaded defensively\n *\n * The msw lifecycle used to live here and now has its own file, `./msw-lifecycle.js`, added to a\n * module's `setupFiles` only when that module actually uses msw. Installing it everywhere patches\n * `http`/`https` and refuses unmatched requests for modules that never asked: measured on\n * `libs/nest/starter`, 11 of 11 became 10 of 11 with `TypeError: Invalid URL` in the interceptor,\n * on a test fetching the Fastify server the suite starts itself.\n *\n * `dotenv-flow` and luxon's zone react to the REPO, not to the runner: they would read the same\n * under jest, Vitest or `node:test`. So `./workspace.js` loads them only if they are installed and\n * skips them in silence otherwise. That defensiveness is not a precaution bolted on, it IS the\n * statement that these belong to whoever installed them. Elsewhere, sentinel installs and that half\n * does nothing.\n *\n * `dotenv-flow` cannot simply be dropped in favour of Vite's own `.env` handling, which was the\n * first thing checked. Measured on Vitest 4: it does read the cascade and sets `MODE=test`, but it\n * exposes only `VITE_`-prefixed values, and only on `import.meta.env`. `process.env` is left\n * untouched, and Nest code reads unprefixed `process.env`.\n *\n * ## What is NOT here\n *\n * The two `jest.mock` calls. A module mock is a per-suite decision that `vi.mock` must make in the\n * file that needs it; hoisting it into a shared setup is what makes a test pass for a reason nobody\n * can see. The migration reports them so the module relying on one declares it.\n *\n * And `Settings.defaultZone = 'utc'` is carried as luxon's own setting, never translated to\n * `process.env.TZ`. One configures luxon, the other the whole process, `Date` and `Intl` included.\n * Swapping them would change what the suite does while claiming to migrate it, and timezone is not\n * a detail: measured on `host-admin`, a machine's zone accounted for a large part of 345 local\n * failures that did not exist in CI.\n */\nimport { expect, vi } from 'vitest'\n\nimport { installJestConstructorSemantics } from './constructor-semantics.js'\nimport { installDeepMockReset } from './deep-mock-reset.js'\nimport { installJestErrorEquality } from './error-equality.js'\nimport { installJestFakeTimerOptions } from './fake-timers.js'\nimport { installJestGlobal } from './jest-global.js'\nimport { installJestMockReset } from './mock-reset.js'\nimport { installJestRejectedFunction } from './rejected-function.js'\nimport { installWorkerId } from './worker-id.js'\nimport { installWorkspaceSetup } from './workspace.js'\n\ninstallJestErrorEquality(expect)\ninstallJestMockReset(vi)\ninstallJestConstructorSemantics(vi)\ninstallDeepMockReset(vi)\ninstallJestFakeTimerOptions(vi)\ninstallJestRejectedFunction()\ninstallJestGlobal(vi)\ninstallWorkerId(process.env)\n\n/*\n * The `.env` cascade, unconditionally: a suite reading `process.env` needs it whatever setup its\n * jest config named, because Vitest's workers do not inherit what a `globalSetup` set in the main\n * process. Awaited at the top level, so it is loaded before the first test file is imported: a\n * module read at import time would already have captured an unset variable.\n *\n * ⚠️ What is NOT here any more is luxon's UTC zone. That was a decision ONE file at the workspace\n * root made, and only the 97 modules naming it ever had it; it lives in\n * `@hublo/sentinel/test/setup/workspace`, which the generated config adds only for those.\n */\nawait installWorkspaceSetup()\n","/**\n * `new` on a mock, the way jest answered it.\n *\n * ## The divergence, measured on the same source under both runners\n *\n * jest vitest\n * mockImplementation(() => obj), then new the obj TypeError: not a constructor\n * mockImplementation(function(){}), new works works\n * mockReturnValue(obj), then new the obj TypeError, with an explanation\n *\n * jest calls the implementation as a PLAIN function when the mock is constructed and hands back\n * what it returned. Vitest applies real `new` semantics, and an arrow function has no [[Construct]]\n * slot, so it throws.\n *\n * The pattern this breaks is the ordinary way to stand in for a class: automock the module, then\n * say what `new` should give back.\n *\n * jest.mock('@hublo/cloud/event-scheduler-sdk')\n * ;(EventSchedulerSDK as jest.MockedClass<typeof EventSchedulerSDK>)\n * .mockImplementation(() => mockEventSchedulerSDK)\n *\n * Measured across the nest and cloud campaigns: 2 modules, 15 tests.\n * `apps/nest/microservices/client-management` (9, an SDK) and `apps/nest/microservices/hublo-pool`\n * (6, a mocked `Date`).\n *\n * ## Why this is safe to do for everybody, which is the part that matters\n *\n * It only changes a case that THROWS today. An implementation without a `prototype` cannot be\n * constructed at all under Vitest, so no suite anywhere can be relying on what it does: the only\n * behaviours available are \"throws\" and \"answers like jest\". Nothing that works today changes\n * shape, and a constructable implementation is passed through untouched.\n *\n * That bound is asserted by the tests, not just claimed here.\n *\n * ## `mockReturnValue(obj)` then `new`, which this used to leave alone\n *\n * It was left out on the grounds that answering it would decide \"a return value and a constructed\n * instance are the same thing\", a claim about the suite. That reading was wrong on both halves.\n *\n * It is not a claim about the suite, because jest's answer is not ambiguous: it hands back the\n * value, exactly as it does for `mockImplementation(() => obj)`, which this file already restores.\n * Treating the two differently would be the arbitrary choice.\n *\n * And \"no module in this repo hit it\" stopped being true the moment the front family was measured.\n * `libs/front/components` mocks Google Maps the ordinary way and constructs it:\n *\n * AutocompleteService: jest.fn().mockReturnValue({ getPlacePredictions: jest.fn() })\n * // and the hook: new window.google.maps.places.AutocompleteService()\n *\n * 7 tests, all with the same TypeError. The safety bound is unchanged and it is the whole reason\n * this is allowed: Vitest THROWS on that call today, so no suite anywhere can depend on what it\n * does, and the only behaviours available are \"throws\" and \"answers like jest\".\n *\n * Expressed by routing the value through the implementation, rather than by a second mechanism:\n * `mockReturnValue(v)` IS `mockImplementation(() => v)`, so it goes through the same wrapper and\n * `new` works for the same reason.\n */\n\nimport { alreadyInstalled } from './install-once.js'\n\n/** The mocking surface this touches. Vitest's own type is not needed to say it. */\ninterface MockLike {\n mockImplementation(implementation: (...args: unknown[]) => unknown): unknown\n mockImplementationOnce(implementation: (...args: unknown[]) => unknown): unknown\n mockReturnValue(value: unknown): unknown\n mockReturnValueOnce(value: unknown): unknown\n}\n\ninterface ViLike {\n fn(implementation?: (...args: unknown[]) => unknown): MockLike\n /**\n * ⚠️ The REST, not `(target, key)`.\n *\n * Vitest's third argument is the access type, `'get'` or `'set'`, and the first version of the\n * wrapper below forwarded two arguments and dropped it. `vi.spyOn(el, 'scrollWidth', 'get')`\n * then became a spy on the VALUE of an accessor that only exists on a prototype, and jsdom\n * answered `'get scrollWidth' called on an object that is not a valid instance of Element`.\n *\n * Measured on `libs/front/components`, 2 tests, and invisible to every nest module because none\n * of them spies on a DOM accessor.\n */\n spyOn(target: object, ...rest: unknown[]): MockLike\n}\n\n/**\n * Can this function be used with `new`?\n *\n * Asked of the `prototype` property rather than of the source text: an arrow function, a shorthand\n * method and a bound function all lack it, and all three are exactly the cases that throw. A\n * class and a plain `function` have it.\n */\nfunction constructable(value: unknown): boolean {\n return (\n typeof value === 'function' && Object.getOwnPropertyDescriptor(value, 'prototype') !== undefined\n )\n}\n\n/**\n * The same implementation, reachable through `new`.\n *\n * A plain `function` that forwards the call and RETURNS the result. JavaScript's own `new` then\n * hands that object back, which is what jest did, so nothing here imitates jest by hand: it\n * restores the one property the arrow was missing and lets the language do the rest.\n */\nfunction asConstructable(\n implementation: (...args: unknown[]) => unknown,\n): (...args: unknown[]) => unknown {\n if (constructable(implementation)) return implementation\n\n return function forwarded(this: unknown, ...args: unknown[]): unknown {\n return implementation.apply(this, args)\n }\n}\n\n/**\n * Wrap `vi.fn` and `vi.spyOn` so every mock they produce accepts `new` the way jest's did.\n *\n * Wrapped at the factory, like `installJestMockReset`, because the behaviour belongs to every mock\n * a suite makes and a suite should not have to ask for it.\n */\nexport function installJestConstructorSemantics(vi: ViLike): void {\n // A setup file runs once per TEST FILE, and without isolation `vi` is the worker's\n // single object, so a second pass would wrap the first pass's wrapper.\n if (alreadyInstalled(vi, 'jest-constructor-semantics')) return\n const patch = (mock: MockLike): MockLike => {\n const { mockImplementation, mockImplementationOnce } = mock\n\n mock.mockImplementation = function (implementation) {\n return mockImplementation.call(this, asConstructable(implementation))\n }\n mock.mockImplementationOnce = function (implementation) {\n return mockImplementationOnce.call(this, asConstructable(implementation))\n }\n\n /*\n * Routed through the implementation rather than given a mechanism of its own: the two are the\n * same statement, and one of them already accepts `new`.\n */\n mock.mockReturnValue = function (value) {\n return this.mockImplementation(() => value)\n }\n mock.mockReturnValueOnce = function (value) {\n return this.mockImplementationOnce(() => value)\n }\n return mock\n }\n\n const { fn, spyOn } = vi\n\n vi.fn = function (implementation) {\n return patch(fn.call(this, implementation && asConstructable(implementation)))\n }\n vi.spyOn = function (target, ...rest) {\n return patch(spyOn.call(this, target, ...rest))\n }\n}\n","import { alreadyInstalled } from './install-once.js'\n/**\n * `vi.resetAllMocks()` reaching the deep mocks, the way jest's registry did.\n *\n * ## The divergence, and why it is invisible\n *\n * jest built `jest-mock-extended`'s mocks with `jest.fn()`, so they sat in jest's own registry and\n * `jest.resetAllMocks()` cleared them with everything else. `vitest-mock-extended` builds them its\n * own way, so `vi.resetAllMocks()` walks past them and their call history survives into the next\n * test.\n *\n * Nothing announces it. The suite still runs, and an assertion fails several tests later with a\n * count that is off by exactly what its neighbour did.\n *\n * Measured on `apps/nest/microservices/activity`, whose suite does 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 one before them. Each\n * PASSES on its own and fails as soon as its neighbour runs first, which is the signature of\n * leakage rather than of a wrong assertion.\n *\n * ## What this installs, and what it leaves alone\n *\n * `resetAllMocks` and `clearAllMocks` do what they did, then extend to the deep mocks: `reset`\n * drops implementations as well as calls, `clear` drops only calls, which is the same distinction\n * the two names already carry.\n *\n * `restoreAllMocks` is NOT extended. It restores spies to their originals, and a deep mock has no\n * original to go back to: it was invented. Extending it would mean deciding what \"restore\" means\n * for something that never existed, which is a claim, not a translation.\n */\nimport { clearDeepMocks, resetDeepMocks } from './mock-extended.js'\n\n/** The part of `vi` this touches. Vitest's own type is not needed to say it. */\ninterface ViLike {\n resetAllMocks(): unknown\n clearAllMocks(): unknown\n}\n\nexport function installDeepMockReset(vi: ViLike): void {\n // A setup file runs once per TEST FILE, and without isolation `vi` is the worker's\n // single object, so a second pass would wrap the first pass's wrapper.\n if (alreadyInstalled(vi, 'deep-mock-reset')) return\n const { resetAllMocks, clearAllMocks } = vi\n\n vi.resetAllMocks = function extended(this: unknown): unknown {\n const answer = resetAllMocks.call(this)\n resetDeepMocks()\n return answer\n }\n\n vi.clearAllMocks = function extended(this: unknown): unknown {\n const answer = clearAllMocks.call(this)\n clearDeepMocks()\n return answer\n }\n}\n","/**\n * How two `Error` values compare, which the two runners disagree about.\n *\n * A suite that asserts on a thrown or captured error usually writes the error it expects by hand:\n *\n * expect(save).toHaveBeenCalledWith({ error: new AxiosError('Request failed with status code 500'), ... })\n *\n * Under jest that passes whatever else the real error carries. Under Vitest it fails, and the\n * report is 6600 lines of an axios error's `config`, `request` and `response`, which reads like a\n * broken test rather than a runner difference.\n *\n * ## What each runner actually does, measured on the same four cases\n *\n * | two errors | jest 29 | Vitest 4 |\n * | --------------------------------- | -------- | ----------- |\n * | same message, same type | equal | equal |\n * | same message, DIFFERENT types | equal | not equal |\n * | same message, extra properties | equal | not equal |\n * | different messages | not equal| not equal |\n *\n * jest compares errors by their MESSAGE and nothing else: a `TypeError` and a `RangeError` with the\n * same text are equal to it. Vitest compares the type and the own properties too.\n *\n * ## Why the looser rule is the one restored\n *\n * Because it is the one 3481 test files were written against. Tightening it here would turn green\n * tests red during a migration whose whole promise is that the suite means the same thing\n * afterwards, and a baseline gate cannot tell that kind of loss from a real one.\n *\n * The question is reported rather than settled: comparing the type as well would be a better rule,\n * and it may cost nothing on this corpus. That is a measurement to run and a change to make on its\n * own, once the suites no longer move. Measured need so far: `libs/cloud/shared`, whose last\n * missing test was exactly this.\n */\nimport type { expect as ExpectApi } from 'vitest'\n\nimport { alreadyInstalled } from './install-once.js'\n\n/**\n * Restore jest's rule: two errors are equal when their messages are.\n *\n * Returning `undefined` for anything else hands the pair back to the default comparison, which is\n * what an equality tester is expected to do for values it has no opinion about.\n */\nexport function errorsCompareByMessage(left: unknown, right: unknown): boolean | undefined {\n if (left instanceof Error && right instanceof Error) return left.message === right.message\n return undefined\n}\n\nexport function installJestErrorEquality(expect: typeof ExpectApi): void {\n // A setup file runs once per TEST FILE, and without isolation `expect` is the worker's\n // single object, so a second pass would wrap the first pass's wrapper.\n if (alreadyInstalled(expect, 'jest-error-equality')) return\n expect.addEqualityTesters([errorsCompareByMessage])\n}\n","/**\n * `useFakeTimers({ doNotFake: [...] })`, which Vitest accepts and ignores.\n *\n * jest names what to LEAVE ALONE, Vitest names what to FAKE. The option Vitest does not know is\n * dropped in silence, so a suite that carefully kept `setTimeout` real gets it faked, and anything\n * awaiting a timer never resolves.\n *\n * Measured on both runners with the same source:\n *\n * useFakeTimers({ doNotFake: ['setTimeout'] }) jest: setTimeout real Vitest: setTimeout FAKED\n * useFakeTimers({ toFake: ['Date'] }) Vitest: setTimeout real\n *\n * Found on `libs/cloud/events-notifications`: 4 tests in one file died on `Test timed out in\n * 5000ms` with nothing else to show, because the code under test awaits a real timer. The repo has\n * 2 files using `doNotFake`, the other in `apps/nest/microservices/institution`.\n *\n * ## The translation, and what it inherits\n *\n * `doNotFake: [a, b]` becomes `toFake: <everything the runner fakes by default> minus [a, b]`. The\n * default set is Vitest's, measured rather than assumed, and NOT jest's, which is wider: jest also\n * fakes `nextTick`, `queueMicrotask` and the animation-frame pair. Subtracting from Vitest's own\n * default is what every other `useFakeTimers()` call in the corpus already gets, so this keeps one\n * behaviour for the whole migration instead of two.\n */\n\nimport { alreadyInstalled } from './install-once.js'\n\n/**\n * What `vi.useFakeTimers()` replaces when told nothing, measured on Vitest 4 by comparing each\n * global before and after the call.\n */\nconst FAKED_BY_DEFAULT = [\n 'setTimeout',\n 'clearTimeout',\n 'setInterval',\n 'clearInterval',\n 'setImmediate',\n 'clearImmediate',\n 'Date',\n 'performance',\n 'hrtime',\n] as const\n\n/** The options both runners take, plus the one only jest knows. */\ninterface TimerOptions {\n toFake?: string[]\n doNotFake?: string[]\n}\n\n/**\n * Turn \"leave these alone\" into \"fake those\", leaving anything else untouched.\n *\n * Exported for its own test: the translation is the whole rule, and asserting it directly says more\n * than asserting that a wrapper was installed.\n */\nexport function withoutJestOnlyOptions<T>(options: T): T {\n const given = options as TimerOptions | undefined\n if (given?.doNotFake === undefined) return options\n\n const { doNotFake, ...rest } = given\n const base = rest.toFake ?? [...FAKED_BY_DEFAULT]\n\n return { ...rest, toFake: base.filter((timer) => !doNotFake.includes(timer)) } as T\n}\n\n/**\n * The one function this touches, named by its shape rather than by Vitest's type.\n *\n * `Options` is the caller's own parameter type: the wrapper hands back exactly what it was given,\n * minus the option Vitest does not know, so it must not narrow what the runner accepts.\n */\ninterface FakeTimerApi<Options> {\n useFakeTimers: (options?: Options) => unknown\n}\n\n/** Wrap `vi.useFakeTimers` so a jest-shaped options object still means what it said. */\nexport function installJestFakeTimerOptions<Options>(vi: FakeTimerApi<Options>): void {\n // A setup file runs once per TEST FILE, and without isolation `vi` is the worker's\n // single object, so a second pass would wrap the first pass's wrapper.\n if (alreadyInstalled(vi, 'jest-fake-timer-options')) return\n const inherited = vi.useFakeTimers.bind(vi)\n vi.useFakeTimers = (options?: Options) => inherited(withoutJestOnlyOptions(options))\n}\n","/**\n * The `jest` global, kept alive for helpers that a migrating module is not allowed to edit.\n *\n * ## Why a module cannot solve this for itself\n *\n * The codemod rewrites a module's own test files. It does not rewrite files in OTHER projects, and\n * it must not: a shared helper is imported by modules still on jest, so migrating it would break\n * them, and leaving it breaks the migrated one. That is the constraint the whole per-module plan\n * rests on.\n *\n * But those helpers call the jest API at MODULE scope. `libs/front/tests/src/mocks/**` does\n * `jest.fn()` when it is imported, before any test runs, so a migrated module dies on\n * `ReferenceError: jest is not defined` the moment it imports one.\n *\n * Measured repo-wide, excluding documentation: **50 files use the jest API without being test\n * files**, in `jest.setup.js`, `*.mock.ts`, `*.test-helper.ts`, `*.test-wrapper.ts`. Three\n * independent hand migrations reached this same line without knowing about each other:\n * `libs/front/components` (8 shared helpers, 16 sites), `apps/nest/microservices/mission` and\n * `apps/nest/backends-for-frontends/admin`.\n *\n * ## It is `vi`, not a fake jest\n *\n * The global IS Vitest's `vi`, so anything Vitest does not have keeps failing loudly:\n * `jest.requireActual` and `jest.isolateModules` are still errors, and a module relying on them\n * still has to be migrated properly. Handing over a hand-written imitation would turn those into\n * silent wrong behaviour, which is the opposite of the point.\n *\n * ## ⚠️ What it does NOT cover, and this bound is measured\n *\n * `jest.mock()`. Vitest hoists mock registrations above the imports by scanning the source\n * STATICALLY, and that scan only recognises the receivers `vi` and `vitest` (`@vitest/mocker`,\n * `hoistMocksPlugin`). A `jest.mock()` left in place is therefore NOT hoisted: it runs after the\n * imports it was meant to intercept and does nothing at all, in silence. Measured on\n * `apps/front/front-legacy`, where 216 of 427 files call it.\n *\n * So this covers a helper that CALLS the jest API. It does not make an unmigrated test file work,\n * and the codemod's rename stays load-bearing rather than cosmetic.\n */\n\n/** The part of `vi` this installs. Vitest's own type is not needed to say it. */\ntype JestLike = object\n\n/**\n * Put `vi` on `globalThis` under the name `jest`.\n *\n * Assigned rather than defined with a getter: a helper may well write to it (`jest.fn = ...` in a\n * test double), and a getter-only property would throw where jest allowed it.\n */\nexport function installJestGlobal(vi: JestLike): void {\n ;(globalThis as Record<string, unknown>).jest = vi\n}\n","/**\n * What `mockReset()` leaves behind, which is where the two runners disagree most dangerously.\n *\n * jest REMOVES the implementation: a reset spy returns `undefined` and the real function is not\n * called. Vitest puts the ORIGINAL implementation back: a reset spy calls the real function again.\n *\n * Measured on both runners with the same source:\n *\n * after resetAllMocks() on a spy jest: undefined Vitest: the real function\n * after mockReset() on a spy jest: undefined Vitest: the real function\n * after mockReset() on fn(impl) jest: undefined Vitest: impl\n *\n * The shape this breaks is ordinary and common: a suite spies on a provider in `beforeAll` and\n * resets its mocks in `beforeEach`. Under jest the provider stayed neutralised for every test.\n * Under Vitest the first `beforeEach` hands the real provider back, and every test after it runs\n * the real code. Measured on `libs/cloud/events-notifications`, that meant real HTTP: 19 tests\n * failed on `captured a request without a matching request handler` for the hermes API and 23 more\n * timed out waiting on it. Nothing in any report named a reset.\n *\n * 240 files in this repo both spy and reset, in every family: 111 under `apps/nest`, 77 under\n * `libs/cloud`, 31 under `apps/front`.\n *\n * ## Why here and not in the 240 files\n *\n * Because a codemod would have to decide, per spy, whether the suite wanted the real function\n * back, and the answer is in the test's intent rather than in its text. The runner-level rule is\n * the one that was true for all 240 while they were written, so restoring it is the transcription\n * and rewriting them would be the guess.\n *\n * Vitest routes `vi.resetAllMocks()` through each mock's own `mockReset`, measured, so overriding\n * that method covers the bulk form as well as the direct one. `mockRestore` is untouched: it puts\n * the original back under both runners, which is what it is for.\n */\n\nimport { alreadyInstalled } from './install-once.js'\n\n/** The part of a mock this file touches. Vitest's own types are not needed to say it. */\ninterface ResettableMock {\n mockReset: () => unknown\n mockImplementation: (fn: (...args: unknown[]) => unknown) => unknown\n}\n\nfunction isResettable(value: unknown): value is ResettableMock {\n return (\n typeof value === 'function' &&\n typeof (value as Partial<ResettableMock>).mockReset === 'function' &&\n typeof (value as Partial<ResettableMock>).mockImplementation === 'function'\n )\n}\n\n/**\n * Make one mock forget its implementation on reset, as jest's did.\n *\n * The override is installed on the instance rather than on a prototype: mocks are functions with\n * their own properties, and there is no shared prototype to reach.\n */\nfunction resetLikeJest<T>(mock: T): T {\n if (!isResettable(mock)) return mock\n\n const inherited = mock.mockReset.bind(mock)\n mock.mockReset = () => {\n inherited()\n mock.mockImplementation(() => undefined)\n return mock\n }\n return mock\n}\n\n/** The two factories a suite gets its mocks from. */\ntype MockFactories = { fn: (...args: never[]) => unknown; spyOn: (...args: never[]) => unknown }\n\n/**\n * Wrap `vi.fn` and `vi.spyOn` so everything they hand out resets the way jest's did.\n *\n * Called with the `vi` a setup file imports, so nothing here reaches for a global.\n */\nexport function installJestMockReset(vi: MockFactories): void {\n // A setup file runs once per TEST FILE, and without isolation `vi` is the worker's\n // single object, so a second pass would wrap the first pass's wrapper.\n if (alreadyInstalled(vi, 'jest-mock-reset')) return\n for (const name of ['fn', 'spyOn'] as const) {\n const factory = vi[name].bind(vi) as (...args: never[]) => unknown\n vi[name] = ((...args: never[]) => resetLikeJest(factory(...args))) as MockFactories[typeof name]\n }\n}\n","/**\n * A rejected value that is a FUNCTION, which jest calls and Vitest does not.\n *\n * ## The divergence, measured rather than reasoned\n *\n * jest's `toThrow` decides what was thrown like this: under `.rejects` it uses the rejection\n * reason ONLY when that reason is an Error. Otherwise it falls through to the ordinary branch,\n * sees a function, and CALLS it, asserting on whatever that call throws.\n *\n * Probed on this repo under jest 29, with controls:\n *\n * reject(() => { throw new Error('some error') })\n * await expect(…).rejects.toThrow(new Error('some error')) -> passes\n * await expect(…).rejects.toThrow(new Error('other text')) -> fails\n * await expect(…).rejects.toThrow('other text') -> fails\n *\n * The two controls are what make the first line mean something: jest is not passing everything,\n * it really is comparing the message of the error the CALL produced.\n *\n * Vitest treats the rejection reason as the thrown value, so the assertion is made against a\n * function. A function has no `message`, and the failure reads\n * `Cannot read properties of undefined (reading 'indexOf')`, which names nothing near the cause.\n *\n * ## Where it shows, and what it is worth\n *\n * Measured across the nest campaign: 4 tests in 3 modules.\n * `apps/nest/microservices/worker` (1), `apps/nest/microservices/institution` (2) and\n * `apps/nest/microservices/mission` (1). All four write the same shape, a mock rejecting with a\n * thunk that throws, or a `throw <a function>`.\n *\n * ## What this changes, and what it cannot\n *\n * Only a case that CANNOT work today: under `.rejects`, a reason that is a function and not an\n * Error. Vitest has no useful behaviour there, so nothing that passes today changes shape. An\n * Error reason, a string, an object, a rejected value of any other kind, and every assertion\n * outside `.rejects` all reach Vitest's own matcher untouched.\n *\n * ⚠️ It is jest's behaviour, not a good one. A suite reaching it is asserting on a function it\n * never meant to hand over, and it passed by accident of the runner. Reproducing it is what keeps\n * the migration honest: the gate promises the suite means the same thing afterwards, and a test\n * that was green cannot be turned red by us and called a finding. The teams own the cleanup.\n */\nimport { chai } from 'vitest'\n\n/** The part of a chai assertion this touches. Chai's own types are not needed to say it. */\ninterface AssertionLike {\n _obj: unknown\n}\n\ntype Matcher = (this: AssertionLike, ...args: unknown[]) => unknown\n\n/**\n * What calling the function throws, or the function itself when it throws nothing.\n *\n * Returning it unchanged matters: a function that completes is not \"nothing was thrown\", and\n * handing Vitest the same value it had leaves the report exactly as it would have been.\n */\nfunction thrownByCalling(candidate: () => unknown): unknown {\n try {\n candidate()\n } catch (thrown) {\n return thrown\n }\n return candidate\n}\n\nexport function installJestRejectedFunction(): void {\n const { Assertion, util } = chai as unknown as {\n Assertion: { prototype: Record<string, unknown> }\n util: { flag(object: unknown, key: string): unknown }\n }\n\n for (const name of ['toThrow', 'toThrowError']) {\n const original = Assertion.prototype[name] as Matcher | undefined\n if (typeof original !== 'function') continue\n\n Assertion.prototype[name] = function patched(this: AssertionLike, ...args: unknown[]): unknown {\n const reason = this._obj\n const rejected = util.flag(this, 'promise') === 'rejects'\n\n if (rejected && typeof reason === 'function' && !(reason instanceof Error)) {\n this._obj = thrownByCalling(reason as () => unknown)\n }\n\n return original.apply(this, args)\n } as unknown as Matcher\n }\n}\n","/**\n * `JEST_WORKER_ID`, which jest set and Vitest does not, and which suites use to stop sharing.\n *\n * ## What breaks without it, and how quietly\n *\n * A suite that needs a resource of its own per worker derives its name from this variable. In this\n * repository:\n *\n * const workerId = process.env.JEST_WORKER_ID ?? '1'\n *\n * Under jest that is 1, 2, 3, so each worker gets `recruitment_test_1`, `_2`, `_3` and nobody\n * treads on anybody. Under Vitest the variable does not exist, every worker takes the `'1'`\n * fallback, and they all write to ONE database while truncating it under each other.\n *\n * Measured on `apps/nest/microservices/recruitment` in the whole-monorepo sweep: 143 of 1228\n * functional tests failed, and not on assertions. `Foreign key constraint violated`,\n * `Unique constraint failed`, and PostgreSQL `40P01 deadlock detected` with two processes waiting\n * on each other's locks. Every log line said `Using database: recruitment_test_1`, whatever the\n * worker. The same suite is green on its own branch, because there it is the only thing running.\n *\n * Nothing in the migration mentions this variable, which is what makes it the migration's problem:\n * a suite that did not share a database now shares one, and says so only through the failures of\n * whichever test lost the race.\n *\n * ## Why `VITEST_POOL_ID` and not `VITEST_WORKER_ID`\n *\n * Measured, because the two look interchangeable and are not. With 8 files and `maxWorkers: 2`:\n *\n * VITEST_POOL_ID 1, 2 bounded by the worker count, 1-based\n * VITEST_WORKER_ID 0, 1, 2, 3, 4, 5... one per file, 0-based\n *\n * `JEST_WORKER_ID` is bounded and 1-based, so `VITEST_POOL_ID` is its counterpart. Taking the\n * other one would turn \"one database per worker\" into one database per FILE, and a 0 would collide\n * with nothing but read as falsy in code that tests the variable rather than compares it.\n */\n\n/** The part of the environment this touches. Node's own types are not needed to say it. */\ninterface Environment {\n JEST_WORKER_ID?: string\n VITEST_POOL_ID?: string\n}\n\n/**\n * Point `JEST_WORKER_ID` at Vitest's pool id, unless something already set it.\n *\n * Set from a SETUP file, which runs before the test file's module graph is evaluated, because a\n * module reading the variable at import time would otherwise capture the fallback.\n */\nexport function installWorkerId(env: Environment): void {\n if (env.JEST_WORKER_ID !== undefined) return\n if (env.VITEST_POOL_ID === undefined) return\n\n env.JEST_WORKER_ID = env.VITEST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BAAiB,IAAI;AAC3B;;;AR4BA,yBAAyB,MAAM;AAC/B,qBAAqB,EAAE;AACvB,gCAAgC,EAAE;AAClC,qBAAqB,EAAE;AACvB,4BAA4B,EAAE;AAC9B,4BAA4B;AAC5B,kBAAkB,EAAE;AACpB,gBAAgB,QAAQ,GAAG;AAY3B,MAAM,sBAAsB;","names":["vi","vi","expect","vi","vi","vi"]}
@@ -1,7 +1,8 @@
1
1
  import {
2
2
  installMswLifecycle,
3
3
  server
4
- } from "../../../chunk-PWV3BMDA.js";
4
+ } from "../../../chunk-MMKBDO5V.js";
5
+ import "../../../chunk-H3GSGAX2.js";
5
6
 
6
7
  // src/roles/test/setup/msw-lifecycle.ts
7
8
  import { afterAll, afterEach, beforeAll } from "vitest";
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/roles/test/setup/msw-lifecycle.ts"],"sourcesContent":["/**\n * The msw lifecycle, as its OWN setup file, loaded only by a module that uses msw.\n *\n * ## Why it moved out of the shared setup\n *\n * It used to run for every adopted module, and that was wrong in a way only a real module could\n * show. Installing msw means patching `http` and `https` and refusing any request that matches no\n * handler. A module that never asked for msw gets that refusal anyway, and its own traffic is what\n * pays.\n *\n * Measured on `libs/nest/starter`, whose suite talks to a Fastify server it starts itself:\n *\n * its own config 11 of 11\n * the same config plus the shared setup 10 of 11, `TypeError: Invalid URL`\n * inside @mswjs/interceptors' fetch interceptor\n *\n * That module has no msw handler anywhere. The failing test does\n * `new URL(`${prefix}/events`, await app.getUrl())` and fetches its own server, and the\n * interceptor cannot read that URL.\n *\n * So the rule is the one asked for at the start: intelligent per module, decided from what the\n * module's files actually contain, not applied to everybody because it is convenient.\n *\n * ## What it does NOT change\n *\n * The lifecycle itself is untouched: `listen` at evaluation time AND in `beforeAll`,\n * `onUnhandledRequest: 'error'` carried across, no `resetHandlers`. `./msw.js` carries the\n * measurement for each of those.\n */\nimport { afterAll, afterEach, beforeAll } from 'vitest'\n\nimport { installMswLifecycle, server } from './msw.js'\n\ninstallMswLifecycle({ beforeAll, afterEach, afterAll })\n\n/**\n * Re-exported so a suite can add its own handlers, which is how all 600 files that touch msw here\n * already work: `server.use(...)` inside a test.\n */\nexport { server }\n"],"mappings":";;;;;;AA6BA,SAAS,UAAU,WAAW,iBAAiB;AAI/C,oBAAoB,EAAE,WAAW,WAAW,SAAS,CAAC;","names":[]}
1
+ {"version":3,"sources":["../../../../src/roles/test/setup/msw-lifecycle.ts"],"sourcesContent":["/**\n * The msw lifecycle, as its OWN setup file, loaded only by a module that uses msw.\n *\n * ## Why it moved out of the shared setup\n *\n * It used to run for every adopted module, and that was wrong in a way only a real module could\n * show. Installing msw means patching `http` and `https` and refusing any request that matches no\n * handler. A module that never asked for msw gets that refusal anyway, and its own traffic is what\n * pays.\n *\n * Measured on `libs/nest/starter`, whose suite talks to a Fastify server it starts itself:\n *\n * its own config 11 of 11\n * the same config plus the shared setup 10 of 11, `TypeError: Invalid URL`\n * inside @mswjs/interceptors' fetch interceptor\n *\n * That module has no msw handler anywhere. The failing test does\n * `new URL(`${prefix}/events`, await app.getUrl())` and fetches its own server, and the\n * interceptor cannot read that URL.\n *\n * So the rule is the one asked for at the start: intelligent per module, decided from what the\n * module's files actually contain, not applied to everybody because it is convenient.\n *\n * ## What it does NOT change\n *\n * The lifecycle itself is untouched: `listen` at evaluation time AND in `beforeAll`,\n * `onUnhandledRequest: 'error'` carried across, no `resetHandlers`. `./msw.js` carries the\n * measurement for each of those.\n */\nimport { afterAll, afterEach, beforeAll } from 'vitest'\n\nimport { installMswLifecycle, server } from './msw.js'\n\ninstallMswLifecycle({ beforeAll, afterEach, afterAll })\n\n/**\n * Re-exported so a suite can add its own handlers, which is how all 600 files that touch msw here\n * already work: `server.use(...)` inside a test.\n */\nexport { server }\n"],"mappings":";;;;;;;AA6BA,SAAS,UAAU,WAAW,iBAAiB;AAI/C,oBAAoB,EAAE,WAAW,WAAW,SAAS,CAAC;","names":[]}
@@ -1,6 +1,7 @@
1
1
  import {
2
2
  server
3
- } from "../../../chunk-PWV3BMDA.js";
3
+ } from "../../../chunk-MMKBDO5V.js";
4
+ import "../../../chunk-H3GSGAX2.js";
4
5
 
5
6
  // src/roles/test/setup/msw-server.ts
6
7
  export * from "msw";
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/roles/test/setup/msw-server.ts"],"sourcesContent":["/**\n * The msw server a migrated suite shares with its setup.\n *\n * ## Why this entry exists at all\n *\n * The setup beside it starts a server and the tests add handlers to one. If those are two different\n * instances, the one that listens has no handlers and every request is unhandled, which under\n * `onUnhandledRequest: 'error'` fails every test that touches HTTP.\n *\n * That is not hypothetical. Migrating `apps/cloud/agency` and running its suite produced exactly\n * it: 22 green tests under jest became 10 failures, with `[MSW] Cannot bypass a request when using\n * the \"error\" strategy`. The setup had been absorbed into sentinel while the 599 files that import\n * the server still pointed at the workspace's own instance.\n *\n * So the server is exported under its own name, and the codemod repoints those imports here. One\n * instance, listened to by the setup and used by the tests.\n */\nexport { server } from './msw.js'\n\n/**\n * msw's own API, re-exported, so a module gets its handlers from the SAME physical copy that\n * intercepts.\n *\n * sentinel ships msw as a dependency on purpose: a module must stand alone, and the workspace root\n * that used to provide it is going away. But a test that keeps `import { rest } from 'msw'` builds\n * its handlers with the WORKSPACE's copy while the server that listens is built with sentinel's.\n * Same version, two physical instances, one interceptor: the handler is never matched.\n *\n * Measured on `libs/cloud/shared`: the msw handler is never called and the test fails on\n * `expected \"vi.fn()\" to be called 1 times, but got 0 times`. Same family as the axios duplicate,\n * where `resolve.dedupe` changed nothing and only pointing at one physical path did.\n *\n * `export *` rather than a list: `rest` covers 669 of the 671 importing files here, but the\n * surface a test may need (`graphql`, `ctx`, the handler types) belongs to msw, not to a list\n * sentinel would have to keep in step. `setupServer` is not part of it: it lives in `msw/node`,\n * and the server is sentinel's to create.\n */\nexport * from 'msw'\n"],"mappings":";;;;;AAqCA,cAAc;","names":[]}
1
+ {"version":3,"sources":["../../../../src/roles/test/setup/msw-server.ts"],"sourcesContent":["/**\n * The msw server a migrated suite shares with its setup.\n *\n * ## Why this entry exists at all\n *\n * The setup beside it starts a server and the tests add handlers to one. If those are two different\n * instances, the one that listens has no handlers and every request is unhandled, which under\n * `onUnhandledRequest: 'error'` fails every test that touches HTTP.\n *\n * That is not hypothetical. Migrating `apps/cloud/agency` and running its suite produced exactly\n * it: 22 green tests under jest became 10 failures, with `[MSW] Cannot bypass a request when using\n * the \"error\" strategy`. The setup had been absorbed into sentinel while the 599 files that import\n * the server still pointed at the workspace's own instance.\n *\n * So the server is exported under its own name, and the codemod repoints those imports here. One\n * instance, listened to by the setup and used by the tests.\n */\nexport { server } from './msw.js'\n\n/**\n * msw's own API, re-exported, so a module gets its handlers from the SAME physical copy that\n * intercepts.\n *\n * sentinel ships msw as a dependency on purpose: a module must stand alone, and the workspace root\n * that used to provide it is going away. But a test that keeps `import { rest } from 'msw'` builds\n * its handlers with the WORKSPACE's copy while the server that listens is built with sentinel's.\n * Same version, two physical instances, one interceptor: the handler is never matched.\n *\n * Measured on `libs/cloud/shared`: the msw handler is never called and the test fails on\n * `expected \"vi.fn()\" to be called 1 times, but got 0 times`. Same family as the axios duplicate,\n * where `resolve.dedupe` changed nothing and only pointing at one physical path did.\n *\n * `export *` rather than a list: `rest` covers 669 of the 671 importing files here, but the\n * surface a test may need (`graphql`, `ctx`, the handler types) belongs to msw, not to a list\n * sentinel would have to keep in step. `setupServer` is not part of it: it lives in `msw/node`,\n * and the server is sentinel's to create.\n */\nexport * from 'msw'\n"],"mappings":";;;;;;AAqCA,cAAc;","names":[]}
@@ -0,0 +1,75 @@
1
+ import { ConfigData } from 'html-validate';
2
+
3
+ /**
4
+ * `expect(element).toBeValidHtml()`, run by html-validate.
5
+ *
6
+ * Opt in from a module's config:
7
+ *
8
+ * setupFiles: ['@hublo/sentinel/test/setup/w3c']
9
+ *
10
+ * ## Why html-validate and not vnu
11
+ *
12
+ * vnu is the W3C's own checker and the W3C's own documentation advises against running it as a
13
+ * service in a loop, which is what a test suite does. It also needs a JVM, but that was never the
14
+ * deciding argument: measured on the same markup, the two agree on almost everything that matters
15
+ * to a component test. What differs is the configuration, and configuration is the thing worth
16
+ * owning.
17
+ *
18
+ * ## The fragment is WRAPPED in a page before it is validated
19
+ *
20
+ * A component renders a fragment, and a fragment cannot be held to document-level rules: it has no
21
+ * doctype, no `<html lang>`, no `<title>`. The obvious answer is to switch those rules off, and it
22
+ * is the wrong one, because they are the rules that catch what a component silently breaks inside
23
+ * a real page.
24
+ *
25
+ * So the fragment is put INTO a minimal valid page and the page is validated. Héla brought this
26
+ * from an OVH project that did the same with vnu, and measured here it is strictly better:
27
+ *
28
+ * case standard + 3 rules wrapped, standard + document + 3
29
+ * <img src="a.png"> wcag/h37 wcag/h37
30
+ * <div><p>x</div> no-implicit-close no-implicit-close
31
+ * <input type="text"> input-missing-label input-missing-label
32
+ * <div id="a" id="b"> no-dup-attr no-dup-attr
33
+ * <div id="a"> x2 no-dup-id no-dup-id
34
+ * <h1>a</h1><h3>b</h3> nothing heading-level
35
+ * correct markup nothing nothing
36
+ *
37
+ * The last two lines are the point: wrapping buys `heading-level`, a skipped heading rank, which
38
+ * no fragment-level check can see, and it costs no false positive.
39
+ *
40
+ * ⚠️ `html-validate:document` is NOT a superset of `standard`, which is easy to assume and wrong:
41
+ * measured on its own it caught `input-missing-label` and missed the other four. Both are extended,
42
+ * plus the three rules neither of them carries.
43
+ *
44
+ * The wrapper is written on ONE line and its width is subtracted from every reported column, so a
45
+ * position still points into the component's own markup rather than into our envelope.
46
+ *
47
+ * ## What a pass means
48
+ *
49
+ * That the markup this component rendered is well formed and carries the attributes those rules
50
+ * require. It says nothing about the rest of the page it will live in, and nothing about anything
51
+ * only a browser can decide. `toBeAccessible()` is the other half, and the two overlap on purpose:
52
+ * `wcag/h37` and axe's `image-alt` are the same requirement seen by a parser and by a DOM.
53
+ */
54
+
55
+ /**
56
+ * The configuration, which is the thing that decides the outcome.
57
+ *
58
+ * Exported so a module can read what it is being held to, and so a test can assert on it rather
59
+ * than on a behaviour that happens to follow from it.
60
+ */
61
+ declare const W3C_CONFIG: ConfigData;
62
+ declare module 'vitest' {
63
+ interface Matchers<T = any> {
64
+ /**
65
+ * Validate this element's markup with html-validate.
66
+ *
67
+ * ⚠️ The fragment is put INTO a minimal page before it is validated, so the document-level
68
+ * rules apply to what the component will actually sit in, without holding the component
69
+ * itself to a doctype it does not own.
70
+ */
71
+ toBeValidHtml: (config?: ConfigData) => Promise<T>;
72
+ }
73
+ }
74
+
75
+ export { W3C_CONFIG };
@@ -0,0 +1,49 @@
1
+ // src/roles/test/setup/w3c.ts
2
+ import { expect } from "vitest";
3
+ var W3C_CONFIG = {
4
+ extends: ["html-validate:standard", "html-validate:document"],
5
+ rules: {
6
+ "wcag/h37": "error",
7
+ "no-implicit-close": "error",
8
+ "input-missing-label": "error"
9
+ }
10
+ };
11
+ var PREFIX = '<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><title>component under test</title></head><body>';
12
+ var SUFFIX = "</body></html>";
13
+ function asDocument(html) {
14
+ const looksLikeADocument = /<!doctype\s+html/i.test(html) || /<html[\s>]/i.test(html);
15
+ return looksLikeADocument ? { html, wrapped: false } : { html: `${PREFIX}${html}${SUFFIX}`, wrapped: true };
16
+ }
17
+ var engine;
18
+ function describe(message, wrapped) {
19
+ const shift = wrapped && message.line === 1 ? PREFIX.length : 0;
20
+ const column = Math.max(message.column - shift, 1);
21
+ return ` ${message.line}:${column} ${message.message} (${message.ruleId})`;
22
+ }
23
+ expect.extend({
24
+ async toBeValidHtml(received, config) {
25
+ const html = typeof received === "string" ? received : received instanceof Element ? received.innerHTML : void 0;
26
+ if (html === void 0) {
27
+ return {
28
+ pass: false,
29
+ message: () => `toBeValidHtml() needs an Element or an HTML string, and received ${typeof received}. From Testing Library, pass the container: expect(render(<X />).container).toBeValidHtml().`
30
+ };
31
+ }
32
+ engine ??= import("html-validate");
33
+ const { HtmlValidate } = await engine;
34
+ const validator = new HtmlValidate(config ?? W3C_CONFIG);
35
+ const document = asDocument(html);
36
+ const report = await validator.validateString(document.html);
37
+ const messages = report.results[0]?.messages ?? [];
38
+ return {
39
+ pass: messages.length === 0,
40
+ message: () => messages.length === 0 ? `expected invalid HTML, and html-validate found nothing to report.` : `${messages.length} HTML problem(s):
41
+
42
+ ${messages.map((message) => describe(message, document.wrapped)).join("\n")}`
43
+ };
44
+ }
45
+ });
46
+ export {
47
+ W3C_CONFIG
48
+ };
49
+ //# sourceMappingURL=w3c.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../src/roles/test/setup/w3c.ts"],"sourcesContent":["/**\n * `expect(element).toBeValidHtml()`, run by html-validate.\n *\n * Opt in from a module's config:\n *\n * setupFiles: ['@hublo/sentinel/test/setup/w3c']\n *\n * ## Why html-validate and not vnu\n *\n * vnu is the W3C's own checker and the W3C's own documentation advises against running it as a\n * service in a loop, which is what a test suite does. It also needs a JVM, but that was never the\n * deciding argument: measured on the same markup, the two agree on almost everything that matters\n * to a component test. What differs is the configuration, and configuration is the thing worth\n * owning.\n *\n * ## The fragment is WRAPPED in a page before it is validated\n *\n * A component renders a fragment, and a fragment cannot be held to document-level rules: it has no\n * doctype, no `<html lang>`, no `<title>`. The obvious answer is to switch those rules off, and it\n * is the wrong one, because they are the rules that catch what a component silently breaks inside\n * a real page.\n *\n * So the fragment is put INTO a minimal valid page and the page is validated. Héla brought this\n * from an OVH project that did the same with vnu, and measured here it is strictly better:\n *\n * case standard + 3 rules wrapped, standard + document + 3\n * <img src=\"a.png\"> wcag/h37 wcag/h37\n * <div><p>x</div> no-implicit-close no-implicit-close\n * <input type=\"text\"> input-missing-label input-missing-label\n * <div id=\"a\" id=\"b\"> no-dup-attr no-dup-attr\n * <div id=\"a\"> x2 no-dup-id no-dup-id\n * <h1>a</h1><h3>b</h3> nothing heading-level\n * correct markup nothing nothing\n *\n * The last two lines are the point: wrapping buys `heading-level`, a skipped heading rank, which\n * no fragment-level check can see, and it costs no false positive.\n *\n * ⚠️ `html-validate:document` is NOT a superset of `standard`, which is easy to assume and wrong:\n * measured on its own it caught `input-missing-label` and missed the other four. Both are extended,\n * plus the three rules neither of them carries.\n *\n * The wrapper is written on ONE line and its width is subtracted from every reported column, so a\n * position still points into the component's own markup rather than into our envelope.\n *\n * ## What a pass means\n *\n * That the markup this component rendered is well formed and carries the attributes those rules\n * require. It says nothing about the rest of the page it will live in, and nothing about anything\n * only a browser can decide. `toBeAccessible()` is the other half, and the two overlap on purpose:\n * `wcag/h37` and axe's `image-alt` are the same requirement seen by a parser and by a DOM.\n */\n/// <reference lib=\"dom\" />\nimport type { ConfigData, Message } from 'html-validate'\nimport { expect } from 'vitest'\n\n/**\n * The configuration, which is the thing that decides the outcome.\n *\n * Exported so a module can read what it is being held to, and so a test can assert on it rather\n * than on a behaviour that happens to follow from it.\n */\nexport const W3C_CONFIG: ConfigData = {\n extends: ['html-validate:standard', 'html-validate:document'],\n rules: {\n 'wcag/h37': 'error',\n 'no-implicit-close': 'error',\n 'input-missing-label': 'error',\n },\n}\n\n/**\n * The page a fragment is put into, on ONE line so a reported position stays readable.\n *\n * `lang` and `<title>` are there because the document rules require them, and requiring them of\n * the COMPONENT would be wrong: it does not own the page it renders into.\n */\nconst PREFIX =\n '<!DOCTYPE html><html lang=\"en\"><head><meta charset=\"utf-8\"><title>component under test</title></head><body>'\nconst SUFFIX = '</body></html>'\n\n/**\n * The fragment, inside a page, unless it already IS one.\n *\n * ⚠️ Conditional, taken from the OVH manager kit: a test that hands over a whole document, which\n * happens as soon as someone validates a server-rendered page, would otherwise get a second\n * doctype and a nested `<html>`, and every message after that would be about our wrapper.\n */\nfunction asDocument(html: string): { html: string; wrapped: boolean } {\n const looksLikeADocument = /<!doctype\\s+html/i.test(html) || /<html[\\s>]/i.test(html)\n return looksLikeADocument\n ? { html, wrapped: false }\n : { html: `${PREFIX}${html}${SUFFIX}`, wrapped: true }\n}\n\n/** The engine, kept once a suite has actually needed it. See the note at its first use. */\nlet engine: Promise<typeof import('html-validate')> | undefined\n\n/**\n * One message, with a position that points into the COMPONENT's markup.\n *\n * Everything the component rendered sits on the wrapper's single first line, so only a message on\n * line 1 needs its column moved back; a message on a later line is already at the component's own\n * coordinates.\n */\nfunction describe(message: Message, wrapped: boolean): string {\n const shift = wrapped && message.line === 1 ? PREFIX.length : 0\n const column = Math.max(message.column - shift, 1)\n return ` ${message.line}:${column} ${message.message} (${message.ruleId})`\n}\n\nexpect.extend({\n async toBeValidHtml(received: unknown, config?: ConfigData) {\n const html =\n typeof received === 'string'\n ? received\n : received instanceof Element\n ? received.innerHTML\n : undefined\n\n if (html === undefined) {\n return {\n pass: false,\n message: () =>\n `toBeValidHtml() needs an Element or an HTML string, and received ${typeof received}. ` +\n `From Testing Library, pass the container: expect(render(<X />).container).toBeValidHtml().`,\n }\n }\n\n /*\n * ⚠️ Loaded on FIRST USE. `setupFiles` runs per test FILE under Vitest's isolation, and\n * html-validate costs 75 ms to import: on `host-admin`, 1460 files, that is 110 seconds added\n * to every run for a matcher almost no file calls.\n */\n engine ??= import('html-validate')\n const { HtmlValidate } = await engine\n const validator = new HtmlValidate(config ?? W3C_CONFIG)\n const document = asDocument(html)\n const report = await validator.validateString(document.html)\n const messages = report.results[0]?.messages ?? []\n\n return {\n pass: messages.length === 0,\n message: () =>\n messages.length === 0\n ? `expected invalid HTML, and html-validate found nothing to report.`\n : `${messages.length} HTML problem(s):\\n\\n` +\n `${messages.map((message) => describe(message, document.wrapped)).join('\\n')}`,\n }\n },\n})\n\ndeclare module 'vitest' {\n // `T = any` to match Vitest's own declaration; see the same note in `a11y.ts`.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n interface Matchers<T = any> {\n /**\n * Validate this element's markup with html-validate.\n *\n * ⚠️ The fragment is put INTO a minimal page before it is validated, so the document-level\n * rules apply to what the component will actually sit in, without holding the component\n * itself to a doctype it does not own.\n */\n toBeValidHtml: (config?: ConfigData) => Promise<T>\n }\n}\n"],"mappings":";AAqDA,SAAS,cAAc;AAQhB,IAAM,aAAyB;AAAA,EAC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AAI,CAAC,YAAY,SAAS,SAAS,SAAS,OAAO,CAAC,EAAE,KAAK,IAAI,CAAC;AAAA,IACpF;AAAA,EACF;AACF,CAAC;","names":[]}
@@ -1,7 +1,8 @@
1
1
  import {
2
2
  pinWorkspaceTimezone
3
- } from "../../../chunk-CPCUPK4J.js";
4
- import "../../../chunk-WLFE5RUU.js";
3
+ } from "../../../chunk-Z7L4FGKP.js";
4
+ import "../../../chunk-ELZHIN6E.js";
5
+ import "../../../chunk-KMKQDGI6.js";
5
6
 
6
7
  // src/roles/test/setup/workspace-entry.ts
7
8
  await pinWorkspaceTimezone();
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/roles/test/setup/workspace-entry.ts"],"sourcesContent":["/**\n * What the WORKSPACE's shared jest setup did, for the modules that actually loaded it.\n *\n * Separate from `setup/jest-parity` on purpose, and the split is the whole point. `setup/jest-parity` carries the\n * runner shims: `jest.*` semantics restored under Vitest, which every migrated module needs whatever\n * its config said. This entry carries the ZONE that `jest.setup.after.env.js` pinned at the workspace root, which\n * only a module whose jest config NAMED that file ever had:\n *\n * require('dotenv-flow').config(...) the .env cascade\n * Settings.defaultZone = 'utc' luxon's default zone\n *\n * Measured on this repo: 97 modules name the root setup, 7 name a setup of their own instead. For\n * those 7 the pin was never applied, and applying it in the migration changes what the suite does\n * while claiming to move it.\n *\n * `libs/front/logic` is the one that said so out loud. It has its own setup, uses luxon, and its\n * test is literally called \"formats them in the local zone\":\n *\n * expect(formatTimeOfDay(new Date(2024, 2, 1, 8, 5))).toBe('08:05')\n * // pinned to utc: '07:05'\n *\n * One test, and it would have been one silent hour of offset in any suite that did not assert it.\n */\nimport { pinWorkspaceTimezone } from './workspace.js'\n\n/*\n * Awaited at the top level, so the environment is loaded before the first test file is imported.\n * Deferring it to a `beforeAll` would be too late: a module read at import time would already have\n * captured an unset variable.\n */\nawait pinWorkspaceTimezone()\n"],"mappings":";;;;;;AA8BA,MAAM,qBAAqB;","names":[]}
1
+ {"version":3,"sources":["../../../../src/roles/test/setup/workspace-entry.ts"],"sourcesContent":["/**\n * What the WORKSPACE's shared jest setup did, for the modules that actually loaded it.\n *\n * Separate from `setup/jest-parity` on purpose, and the split is the whole point. `setup/jest-parity` carries the\n * runner shims: `jest.*` semantics restored under Vitest, which every migrated module needs whatever\n * its config said. This entry carries the ZONE that `jest.setup.after.env.js` pinned at the workspace root, which\n * only a module whose jest config NAMED that file ever had:\n *\n * require('dotenv-flow').config(...) the .env cascade\n * Settings.defaultZone = 'utc' luxon's default zone\n *\n * Measured on this repo: 97 modules name the root setup, 7 name a setup of their own instead. For\n * those 7 the pin was never applied, and applying it in the migration changes what the suite does\n * while claiming to move it.\n *\n * `libs/front/logic` is the one that said so out loud. It has its own setup, uses luxon, and its\n * test is literally called \"formats them in the local zone\":\n *\n * expect(formatTimeOfDay(new Date(2024, 2, 1, 8, 5))).toBe('08:05')\n * // pinned to utc: '07:05'\n *\n * One test, and it would have been one silent hour of offset in any suite that did not assert it.\n */\nimport { pinWorkspaceTimezone } from './workspace.js'\n\n/*\n * Awaited at the top level, so the environment is loaded before the first test file is imported.\n * Deferring it to a `beforeAll` would be too late: a module read at import time would already have\n * captured an unset variable.\n */\nawait pinWorkspaceTimezone()\n"],"mappings":";;;;;;;AA8BA,MAAM,qBAAqB;","names":[]}
@@ -21,6 +21,19 @@ interface SharedTestOptions {
21
21
  * plugin for all of them took the suite from 98s to 249s.
22
22
  */
23
23
  lowerDecoratorsWithTypeScript?: boolean;
24
+ /**
25
+ * Let the files of this suite share a worker instead of each getting its own registry.
26
+ *
27
+ * Off by default, which is Vitest's own default and jest's semantics. Turning it off buys the
28
+ * whole of `./setup/file-boundary.js` and `./isolation-split.js`: measured on
29
+ * `front-components`, 44.6s isolated against 11.0s split, with all 1418 tests green and the
30
+ * same result across ten shuffled file orders.
31
+ *
32
+ * A module takes it deliberately, and proves it with `--validate`, because the switch is the one
33
+ * thing in this preset that changes what a suite MEANS: a file can see what an earlier file left
34
+ * behind, and only running the suite can say whether any of them does.
35
+ */
36
+ isolate?: boolean;
24
37
  /** Merged over the base. For what a module genuinely needs to differ on, nothing else. */
25
38
  overrides?: ViteUserConfig;
26
39
  }
@@ -1,7 +1,8 @@
1
1
  import {
2
2
  sharedTestConfig
3
- } from "../../chunk-7PUVK4YM.js";
4
- import "../../chunk-3TDUIKVQ.js";
3
+ } from "../../chunk-5VNYQIFD.js";
4
+ import "../../chunk-SWWQ7X7B.js";
5
+ import "../../chunk-QXFCZON7.js";
5
6
  export {
6
7
  sharedTestConfig
7
8
  };
@@ -0,0 +1,170 @@
1
+ import {
2
+ captureReference,
3
+ compareAgainstReference,
4
+ fromWorkspaceRoot,
5
+ hasReference,
6
+ moduleEnvironment,
7
+ readTestAdoption,
8
+ resolveVitest,
9
+ suiteOf
10
+ } from "./chunk-DYJ6J43A.js";
11
+ import "./chunk-O7REVMOC.js";
12
+ import "./chunk-QXFCZON7.js";
13
+ import "./chunk-KMKQDGI6.js";
14
+
15
+ // src/roles/test/validate.ts
16
+ import { execFileSync } from "node:child_process";
17
+ import { existsSync, mkdtempSync, readFileSync } from "node:fs";
18
+ import { tmpdir } from "node:os";
19
+ import { join } from "node:path";
20
+ function runVitest(cwd, config, extra = []) {
21
+ const { bin } = resolveVitest(cwd);
22
+ if (bin === void 0) return void 0;
23
+ const relocated = fromWorkspaceRoot(cwd, ["--config", config], []);
24
+ const out = join(mkdtempSync(join(tmpdir(), "sentinel-validate-")), "vitest.json");
25
+ try {
26
+ execFileSync(
27
+ bin,
28
+ ["run", ...relocated.options, ...extra, "--reporter=json", `--outputFile=${out}`],
29
+ {
30
+ cwd: relocated.cwd,
31
+ // The SAME environment the reference was taken in, or the two sides are two programs.
32
+ // `relocated.env` last: moving the process is part of the run, not part of the module.
33
+ env: { ...moduleEnvironment(cwd).env, ...relocated.env },
34
+ stdio: ["ignore", "ignore", "ignore"],
35
+ maxBuffer: 1 << 28
36
+ }
37
+ );
38
+ } catch {
39
+ }
40
+ if (!existsSync(out)) return void 0;
41
+ try {
42
+ return JSON.parse(readFileSync(out, "utf8"));
43
+ } catch {
44
+ return void 0;
45
+ }
46
+ }
47
+ function vitestConfigFor(cwd, suite) {
48
+ const stems = suite === "main" ? ["vitest.config"] : [`vitest.${suite}.config`, `vitest.${suite}-config`];
49
+ for (const stem of stems) {
50
+ for (const extension of [".mts", ".ts", ".mjs", ".js"]) {
51
+ if (existsSync(join(cwd, `${stem}${extension}`))) return `${stem}${extension}`;
52
+ }
53
+ }
54
+ return void 0;
55
+ }
56
+ function sharesAWorker(cwd, config) {
57
+ try {
58
+ return /\bisolate\s*:\s*false\b/.test(readFileSync(join(cwd, config), "utf8"));
59
+ } catch {
60
+ return false;
61
+ }
62
+ }
63
+ function shuffledPassMatches(root, suite, config) {
64
+ const seed = Math.floor(Math.random() * 1e6);
65
+ const report = runVitest(root, config, ["--sequence.shuffle.files", `--sequence.seed=${seed}`]);
66
+ if (report === void 0) {
67
+ return {
68
+ ok: false,
69
+ message: `the shuffled pass (seed ${seed}) produced no report, so order independence is unproven.`
70
+ };
71
+ }
72
+ const comparison = compareAgainstReference(root, suite, report);
73
+ if (comparison.ok) {
74
+ return { ok: true, message: `and again in a random file order (seed ${seed}).` };
75
+ }
76
+ return {
77
+ ok: false,
78
+ message: `this suite shares a worker, and it depends on the ORDER of its files: in a random order (seed ${seed}) it no longer matches. ${comparison.message} Reproduce with \`--sequence.shuffle.files --sequence.seed=${seed}\`. Something a file does outlives it; until that is found, the suite is not safe without isolation.`
79
+ };
80
+ }
81
+ var KNOWN_SUITES = ["main", "prisma", "integration", "functional"];
82
+ function suitesOf(cwd, adoption) {
83
+ const declared = adoption.state === "jest" ? adoption.jestConfigs.map(suiteOf) : KNOWN_SUITES.filter((suite) => vitestConfigFor(cwd, suite) !== void 0);
84
+ const recorded = KNOWN_SUITES.filter((suite) => hasReference(cwd, suite));
85
+ return [.../* @__PURE__ */ new Set([...declared, ...recorded])];
86
+ }
87
+ function validateModuleTests(name, root) {
88
+ const adoption = readTestAdoption(root);
89
+ if (adoption.state === "no-tests") {
90
+ return [
91
+ { module: name, suite: "main", ok: true, message: `no tests, so there is nothing to prove.` }
92
+ ];
93
+ }
94
+ const suites = suitesOf(root, adoption);
95
+ if (suites.length === 0) {
96
+ return [
97
+ {
98
+ module: name,
99
+ suite: "main",
100
+ ok: false,
101
+ message: `no test config could be read, so there is no suite to prove.`
102
+ }
103
+ ];
104
+ }
105
+ return suites.map((suite) => validateSuite(name, root, adoption, suite));
106
+ }
107
+ function validateSuite(name, root, adoption, suite) {
108
+ if (hasReference(root, suite)) {
109
+ if (adoption.state === "jest") {
110
+ return {
111
+ module: name,
112
+ suite,
113
+ ok: false,
114
+ message: `a reference is recorded, but this module still tests with jest (${adoption.jestConfigs.join(", ")}). Migrate it with \`sentinel --init --test\`, then run this again to compare.`
115
+ };
116
+ }
117
+ const config2 = vitestConfigFor(root, suite);
118
+ if (config2 === void 0) {
119
+ return {
120
+ module: name,
121
+ suite,
122
+ ok: false,
123
+ message: `a reference is recorded for the \`${suite}\` suite, and this module has no Vitest config for it. The migration wrote one config where the jest side had two, so one suite is not running at all.`
124
+ };
125
+ }
126
+ const report = runVitest(root, config2);
127
+ if (report === void 0) {
128
+ return {
129
+ module: name,
130
+ suite,
131
+ ok: false,
132
+ message: `the Vitest run produced no report, so nothing could be compared. Check that the suite starts at all: \`sentinel --run --test\`.`
133
+ };
134
+ }
135
+ const comparison = compareAgainstReference(root, suite, report);
136
+ if (!comparison.ok || !sharesAWorker(root, config2)) {
137
+ return { module: name, suite, ok: comparison.ok, message: comparison.message };
138
+ }
139
+ const shuffled = shuffledPassMatches(root, suite, config2);
140
+ return {
141
+ module: name,
142
+ suite,
143
+ ok: shuffled.ok,
144
+ message: shuffled.ok ? `${comparison.message} ${shuffled.message}` : shuffled.message
145
+ };
146
+ }
147
+ if (adoption.state !== "jest") {
148
+ return {
149
+ module: name,
150
+ suite,
151
+ ok: false,
152
+ message: `already migrated, and no reference was recorded before it was, so there is nothing to compare against. A proof has to be started BEFORE the migration: \`sentinel --validate --test\` on the jest state, then \`--init --test\`, then this again.`
153
+ };
154
+ }
155
+ const config = adoption.jestConfigs.find((candidate) => suiteOf(candidate) === suite);
156
+ if (config === void 0) {
157
+ return {
158
+ module: name,
159
+ suite,
160
+ ok: false,
161
+ message: `this module reads as jest but names no config for the \`${suite}\` suite.`
162
+ };
163
+ }
164
+ const capture = captureReference(root, config);
165
+ return { module: name, suite, ok: capture.captured, message: capture.message };
166
+ }
167
+ export {
168
+ sharesAWorker,
169
+ validateModuleTests
170
+ };