@venizia/dev-configs 0.5.0-1 → 0.5.0-10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +18 -13
- package/dist/checks/purity/manifest.js +11 -3
- package/dist/checks/purity/manifest.js.map +1 -1
- package/dist/checks/purity/probe.js +19 -2
- package/dist/checks/purity/probe.js.map +1 -1
- package/dist/checks/split-report.js +2 -1
- package/dist/checks/split-report.js.map +1 -1
- package/dist/checks/test-controls.d.ts +9 -1
- package/dist/checks/test-controls.js +9 -3
- package/dist/checks/test-controls.js.map +1 -1
- package/dist/checks/test-dead-code.d.ts +9 -1
- package/dist/checks/test-dead-code.js +13 -2
- package/dist/checks/test-dead-code.js.map +1 -1
- package/dist/checks/test-mutate.d.ts +9 -1
- package/dist/checks/test-mutate.js +12 -6
- package/dist/checks/test-mutate.js.map +1 -1
- package/dist/cli/check.js +42 -38
- package/dist/cli/check.js.map +1 -1
- package/dist/cli/clean.js +3 -2
- package/dist/cli/clean.js.map +1 -1
- package/dist/cli/codemod/any-aliases.d.ts +1 -1
- package/dist/cli/codemod/any-aliases.js +14 -13
- package/dist/cli/codemod/any-aliases.js.map +1 -1
- package/dist/cli/codemod/async-style.d.ts +1 -1
- package/dist/cli/codemod/async-style.js +18 -17
- package/dist/cli/codemod/async-style.js.map +1 -1
- package/dist/cli/codemod/binding-keys.d.ts +32 -1
- package/dist/cli/codemod/binding-keys.js +238 -58
- package/dist/cli/codemod/binding-keys.js.map +1 -1
- package/dist/cli/codemod/class-renames.d.ts +39 -0
- package/dist/cli/codemod/class-renames.js +297 -0
- package/dist/cli/codemod/class-renames.js.map +1 -0
- package/dist/cli/codemod/connector-imports.d.ts +1 -1
- package/dist/cli/codemod/connector-imports.js +13 -12
- package/dist/cli/codemod/connector-imports.js.map +1 -1
- package/dist/cli/codemod/const-class-sets.d.ts +55 -0
- package/dist/cli/codemod/const-class-sets.js +219 -0
- package/dist/cli/codemod/const-class-sets.js.map +1 -0
- package/dist/cli/codemod/const-classes.d.ts +21 -3
- package/dist/cli/codemod/const-classes.js +151 -36
- package/dist/cli/codemod/const-classes.js.map +1 -1
- package/dist/cli/codemod/drop-redundant-casts.d.ts +6 -1
- package/dist/cli/codemod/drop-redundant-casts.js +27 -19
- package/dist/cli/codemod/drop-redundant-casts.js.map +1 -1
- package/dist/cli/codemod/env-get.d.ts +3 -3
- package/dist/cli/codemod/env-get.js +19 -18
- package/dist/cli/codemod/env-get.js.map +1 -1
- package/dist/cli/codemod/files.d.ts +4 -2
- package/dist/cli/codemod/files.js +7 -8
- package/dist/cli/codemod/files.js.map +1 -1
- package/dist/cli/codemod/function-to-arrow.d.ts +76 -0
- package/dist/cli/codemod/function-to-arrow.js +357 -0
- package/dist/cli/codemod/function-to-arrow.js.map +1 -0
- package/dist/cli/codemod/index.js +25 -4
- package/dist/cli/codemod/index.js.map +1 -1
- package/dist/cli/codemod/namespace-functions/index.d.ts +1 -1
- package/dist/cli/codemod/namespace-functions/index.js +14 -13
- package/dist/cli/codemod/namespace-functions/index.js.map +1 -1
- package/dist/cli/codemod/namespace-functions/mappings/dev-configs.js +3 -3
- package/dist/cli/codemod/namespace-functions/mappings/dev-configs.js.map +1 -1
- package/dist/cli/codemod/namespace-functions/mappings/helpers.js +1 -1
- package/dist/cli/codemod/namespace-functions/mappings/helpers.js.map +1 -1
- package/dist/cli/codemod/typed-route-context.d.ts +58 -0
- package/dist/cli/codemod/typed-route-context.js +918 -0
- package/dist/cli/codemod/typed-route-context.js.map +1 -0
- package/dist/cli/index.js +5 -4
- package/dist/cli/index.js.map +1 -1
- package/dist/common/cli-output.d.ts +16 -0
- package/dist/common/cli-output.js +49 -0
- package/dist/common/cli-output.js.map +1 -0
- package/dist/compilers/bun.js +1 -1
- package/dist/compilers/bun.js.map +1 -1
- package/dist/linters/eslint.js +1 -1
- package/dist/linters/eslint.js.map +1 -1
- package/dist/linters/house/browser-api-patterns.d.ts +43 -0
- package/dist/linters/house/browser-api-patterns.js +87 -0
- package/dist/linters/house/browser-api-patterns.js.map +1 -0
- package/dist/linters/house/common.d.ts +17 -2
- package/dist/linters/house/common.js +18 -2
- package/dist/linters/house/common.js.map +1 -1
- package/dist/linters/house/configs.js +25 -0
- package/dist/linters/house/configs.js.map +1 -1
- package/dist/linters/house/const-class-values.rule.d.ts +2 -2
- package/dist/linters/house/const-class-values.rule.js +14 -5
- package/dist/linters/house/const-class-values.rule.js.map +1 -1
- package/dist/linters/house/effect-cleanup-consistency.rule.d.ts +2 -2
- package/dist/linters/house/effect-cleanup-consistency.rule.js +1 -1
- package/dist/linters/house/effect-cleanup-consistency.rule.js.map +1 -1
- package/dist/linters/house/framework-api-patterns.d.ts +54 -0
- package/dist/linters/house/framework-api-patterns.js +62 -0
- package/dist/linters/house/framework-api-patterns.js.map +1 -0
- package/dist/linters/house/framework-exports.d.ts +62 -0
- package/dist/linters/house/framework-exports.js +325 -0
- package/dist/linters/house/framework-exports.js.map +1 -0
- package/dist/linters/house/import-support.d.ts +56 -0
- package/dist/linters/house/import-support.js +179 -0
- package/dist/linters/house/import-support.js.map +1 -0
- package/dist/linters/house/index.d.ts +12 -0
- package/dist/linters/house/index.js +15 -1
- package/dist/linters/house/index.js.map +1 -1
- package/dist/linters/house/max-params-own.rule.d.ts +2 -2
- package/dist/linters/house/max-params-own.rule.js +1 -1
- package/dist/linters/house/max-params-own.rule.js.map +1 -1
- package/dist/linters/house/no-async-hook-callback.rule.d.ts +2 -2
- package/dist/linters/house/no-async-hook-callback.rule.js +1 -1
- package/dist/linters/house/no-async-hook-callback.rule.js.map +1 -1
- package/dist/linters/house/no-await-new-chain.rule.d.ts +2 -2
- package/dist/linters/house/no-await-new-chain.rule.js +1 -1
- package/dist/linters/house/no-await-new-chain.rule.js.map +1 -1
- package/dist/linters/house/no-await-promise-chain.rule.d.ts +2 -2
- package/dist/linters/house/no-await-promise-chain.rule.js +5 -5
- package/dist/linters/house/no-await-promise-chain.rule.js.map +1 -1
- package/dist/linters/house/no-inline-await.rule.d.ts +2 -2
- package/dist/linters/house/no-inline-await.rule.js +1 -1
- package/dist/linters/house/no-inline-await.rule.js.map +1 -1
- package/dist/linters/house/no-leaked-render.rule.d.ts +2 -2
- package/dist/linters/house/no-leaked-render.rule.js +1 -1
- package/dist/linters/house/no-leaked-render.rule.js.map +1 -1
- package/dist/linters/house/no-new-error.rule.d.ts +2 -2
- package/dist/linters/house/no-new-error.rule.js +2 -2
- package/dist/linters/house/no-new-error.rule.js.map +1 -1
- package/dist/linters/house/no-parent-import.rule.d.ts +45 -0
- package/dist/linters/house/no-parent-import.rule.js +176 -0
- package/dist/linters/house/no-parent-import.rule.js.map +1 -0
- package/dist/linters/house/no-return-await.rule.d.ts +2 -2
- package/dist/linters/house/no-return-await.rule.js +1 -1
- package/dist/linters/house/no-return-await.rule.js.map +1 -1
- package/dist/linters/house/no-shadow-framework-type.rule.d.ts +24 -0
- package/dist/linters/house/no-shadow-framework-type.rule.js +100 -0
- package/dist/linters/house/no-shadow-framework-type.rule.js.map +1 -0
- package/dist/linters/house/no-silent-catch.rule.d.ts +2 -2
- package/dist/linters/house/no-silent-catch.rule.js +3 -3
- package/dist/linters/house/no-silent-catch.rule.js.map +1 -1
- package/dist/linters/house/no-unbraced-case.rule.d.ts +2 -2
- package/dist/linters/house/no-unbraced-case.rule.js +1 -1
- package/dist/linters/house/no-unbraced-case.rule.js.map +1 -1
- package/dist/linters/house/plugin.d.ts +1 -1
- package/dist/linters/house/plugin.js +18 -2
- package/dist/linters/house/plugin.js.map +1 -1
- package/dist/linters/house/prefer-framework-api.rule.d.ts +83 -0
- package/dist/linters/house/prefer-framework-api.rule.js +562 -0
- package/dist/linters/house/prefer-framework-api.rule.js.map +1 -0
- package/dist/linters/house/prefer-http-method.rule.d.ts +22 -0
- package/dist/linters/house/prefer-http-method.rule.js +182 -0
- package/dist/linters/house/prefer-http-method.rule.js.map +1 -0
- package/dist/linters/house/prefer-promise-sleep.rule.d.ts +26 -0
- package/dist/linters/house/prefer-promise-sleep.rule.js +155 -0
- package/dist/linters/house/prefer-promise-sleep.rule.js.map +1 -0
- package/dist/linters/house/prefer-tnullable.rule.d.ts +25 -0
- package/dist/linters/house/prefer-tnullable.rule.js +124 -0
- package/dist/linters/house/prefer-tnullable.rule.js.map +1 -0
- package/dist/linters/house/typed-route-context.rule.d.ts +19 -0
- package/dist/linters/house/typed-route-context.rule.js +334 -0
- package/dist/linters/house/typed-route-context.rule.js.map +1 -0
- package/dist/linters/house/zod-schema-convention.rule.d.ts +82 -0
- package/dist/linters/house/zod-schema-convention.rule.js +477 -0
- package/dist/linters/house/zod-schema-convention.rule.js.map +1 -0
- package/dist/linters/oxlint.js +11 -1
- package/dist/linters/oxlint.js.map +1 -1
- package/dist/linters/react-eslint.js.map +1 -1
- package/dist/linters/rules/naming-convention.rule.d.ts +4 -1
- package/dist/linters/rules/naming-convention.rule.js +30 -1
- package/dist/linters/rules/naming-convention.rule.js.map +1 -1
- package/dist/linters/rules/no-restricted-properties.rule.js +1 -1
- package/dist/linters/rules/no-restricted-properties.rule.js.map +1 -1
- package/dist/testing/index.d.ts +2 -2
- package/dist/testing/index.js +2 -2
- package/dist/testing/index.js.map +1 -1
- package/dist/testing/{rejection.helper.d.ts → rejection.utility.d.ts} +4 -4
- package/dist/testing/{rejection.helper.js → rejection.utility.js} +7 -7
- package/dist/testing/rejection.utility.js.map +1 -0
- package/dist/testing/{spawn.helper.d.ts → spawn.utility.d.ts} +2 -2
- package/dist/testing/{spawn.helper.js → spawn.utility.js} +6 -6
- package/dist/testing/spawn.utility.js.map +1 -0
- package/package.json +7 -7
- package/dist/testing/rejection.helper.js.map +0 -1
- package/dist/testing/spawn.helper.js.map +0 -1
package/README.md
CHANGED
|
@@ -10,7 +10,7 @@ bun add -d @venizia/dev-configs oxlint oxlint-tsgolint eslint typescript
|
|
|
10
10
|
```
|
|
11
11
|
|
|
12
12
|
`oxlint` (>=1.89.0), `oxlint-tsgolint` (>=7.0.2004), `eslint` (9 or 10),
|
|
13
|
-
`typescript` (5 or 6) are optional peers. Install only the tools you use. Formatting is `bun fmt` (Bun 1.4
|
|
13
|
+
`typescript` (5 or 6) are optional peers. Install only the tools you use. Formatting is `bun fmt` (Bun 1.4 or newer), set in `bunfig.toml`: see [Formatting](#formatting). Keep the
|
|
14
14
|
ESLint config `.mjs`: a TypeScript one (`.mts`) makes ESLint require `jiti`, one more dependency. A
|
|
15
15
|
project that only wants the full ESLint preset installs `eslint` and skips the oxc tools.
|
|
16
16
|
|
|
@@ -104,7 +104,7 @@ Every IGNIS package and example does.
|
|
|
104
104
|
| :--- | :--- |
|
|
105
105
|
| `@venizia/dev-configs` | `/compilers` and `/linters`, re-exported. Not `/checks` or `/testing` |
|
|
106
106
|
| `@venizia/dev-configs/compilers` | `BunCompiler` |
|
|
107
|
-
| `@venizia/dev-configs/testing` | `
|
|
107
|
+
| `@venizia/dev-configs/testing` | `RejectionUtility` (`rejectionOf`, `expectRejection`), `SpawnUtility` (`spawnSyncBounded`), `RepoTmp` (`findRoot`, `apply`) - test helpers (imports `bun:test`; tests only) |
|
|
108
108
|
| `@venizia/dev-configs/testing/tmpdir-preload` | A bunfig test preload: a bare `bun test` keeps its temp folders in the repository (calls `RepoTmp.apply()`) |
|
|
109
109
|
| `@venizia/dev-configs/checks` | The engines behind `devz check <name>`: catalog, module cycles, purity, split report and the test-trimming checks. Bun-only tooling, never import it from browser code |
|
|
110
110
|
| `@venizia/dev-configs/linters` | `oxlintConfigs`, `OxlintConfigs`, `BrowserOxlintConfigs`, `ReactOxlintConfigs`, `LintIgnore`, `namingConventionConfigs`, `reactNamingConventionConfigs`, `houseConfigs`, `reactHouseConfigs`, `eslintConfigs`, `paddingConfigs`, the rule classes and their types |
|
|
@@ -166,19 +166,24 @@ booleans. `BrowserOxlintConfigs.create()` and `ReactOxlintConfigs.create()` take
|
|
|
166
166
|
`houseConfigs` is `namingConventionConfigs` plus the house rules oxlint cannot express, the four async style rules
|
|
167
167
|
and the blank-line padding rules (`paddingConfigs`, below); `reactHouseConfigs` is the same over
|
|
168
168
|
`reactNamingConventionConfigs`, plus the React rules. The house rules ship as the ESLint plugin
|
|
169
|
-
`houseEslintPlugin`, registered as
|
|
169
|
+
`houseEslintPlugin`, registered as `@venizia`:
|
|
170
170
|
|
|
171
171
|
| Class | Rule | Default | What it enforces |
|
|
172
172
|
| :--- | :--- | :--- | :--- |
|
|
173
|
-
| `MaxParamsOwnRule` |
|
|
174
|
-
| `NoNewErrorRule` |
|
|
175
|
-
| `
|
|
176
|
-
| `
|
|
173
|
+
| `MaxParamsOwnRule` | `@venizia/max-params-own` | `build({ max: 5 })` | A function we write takes at most `max` positional parameters. Not counted: an inline callback passed to a call or a JSX prop, a signature a declared type fixes, a constructor whose parameters are all `@inject`. A hook callback counts. |
|
|
174
|
+
| `NoNewErrorRule` | `@venizia/no-new-error` | `error` | Throw through `getError` (or an `ApplicationError`), never `new Error(...)` / `Error(...)`. Off in tests. |
|
|
175
|
+
| `PreferFrameworkApiRule` | `@venizia/prefer-framework-api` | `build({ hooks: false })` in `houseConfigs`, `hooks: true` in `reactHouseConfigs` | A form the framework replaces, one row each. Anywhere in a file: `instanceof ApplicationError`, an `APP_ENV_` read of `process.env` and a comparison of `AppEnvs.get(...)` with `'true'` or `'false'` (in a package that depends on `@venizia/ignis*`), a member of `localStorage` / `sessionStorage` (`@venizia/ardor*`), a `localhost` URL used as a fallback. An assignment to a name of `process.env` and a `delete` of it pass. With `hooks`, in a component or a hook: the browser APIs `@venizia/ardor-react` wraps. Options `hooks`, `ignore` (row ids), `extra` (your rows: `{ id, match, message, dependsOn?, owner? }`, match `path`, `member`, `selector`, `literal` or `import`). Message only. Off in tests. An entry that sets options replaces the earlier ones, so state `hooks` again.. `localhost-url` skips `vite.config.*` and `.configs/builders/**`, a dev tool's own configuration |
|
|
176
|
+
| `NamingConventionRule` (type names) | `@typescript-eslint/naming-convention` | `error` | Also: a type alias starts with `T` or ends with `Type`, and an interface starts with `I`; `ValueOf`, `ValueOptional`, `ValueOptionalExcept`, `ValueOrPromise` and `PGliteCRUDRepository` (a type that shares its name with a class value) keep their names, and so do the interfaces `declare module` adds to (`ContextRenderer`, `ContextVariableMap`, `ImportMeta`, `ImportMetaEnv`, `Matchers`, `ProcessEnv`, `Register`, `Window`), listed by name because the rule cannot see where an interface is declared. Another name passes through an `extraSelectors` entry with a `filter` and `format: null`. |
|
|
177
|
+
| `TypedRouteContextRule` | `@venizia/typed-route-context` | `error` | A route handler left unchecked: a config declared as `IAuthRouteConfig` instead of `satisfies`, `valid<T>()` on a context typed from its route, a `TContextOf` that names another route than the decorator or the handler that forwards to it. Syntax only |
|
|
178
|
+
| `PreferHttpMethodRule` | `@venizia/prefer-http-method` | `error` | A method written by hand (`'get'`) in a route config, a request or a `method` / `verb` variable is `HTTP.Methods.GET`; autofix for the exact lowercase value; only in a project depending on an IGNIS package; off in tests; option `source` |
|
|
179
|
+
| `ZodSchemaConventionRule` | `@venizia/zod-schema-convention` | `error` | A zod schema const is PascalCase ending in `Schema`; a type inferred from `XSchema` is `TX` or `XType` (`TXInput` / `TXOutput` for two). In every file, `z.object().strict()` is `z.strictObject()` (fixed when the call has no argument and no comment) and `.passthrough()` is refused. `.passthrough()` is reported only where the file proves the schema is zod's (a chain or a local const that starts at an import of zod), so one on an imported schema passes. In `strictPaths`, an object is `z.strictObject`; in `noAnyPaths`, no `z.any()`; in `noCoercePaths`, no `z.coerce`. Options `schemaName`, `typeName`, `strictCall`, `noPassthrough`, `strictPaths`, `noAnyPaths`, `noCoercePaths` (globs from the working directory), `ignoreTests`, `ignore` (names the two name checks leave alone). Schemas are recognised file by file, without types: an imported schema under a name that does not end in `Schema`, `this.x.extend`, a factory's result and a schema held in an object are not followed. A schema of another library imported under a name ending in `Schema` (yup, mongoose) and derived with a method of the same name (`.pick`, `.omit`, ...) is reported: list it in `ignore`. |
|
|
180
|
+
| `NoLeakedRenderRule` | `@venizia/no-leaked-render` | `error`, in `reactHouseConfigs` only | A JSX child is drawn with `cond ? <X /> : null`, never `cond && <X />`, which draws `0` when `cond` is `0`. `--fix` rewrites it. `disabled={a && b}` is a value, not a child, and passes. |
|
|
181
|
+
| `ConstClassValuesRule` | `@venizia/const-class-values` | `warn` in both presets; `build({ severity, namePattern })` | V-C-08. A union of string literals in an exported declaration (a type alias, an interface member, a generic constraint, a parameter or return type) is a const class plus `TConstValue<typeof X>`. Not counted: `Pick`, `Omit`, `Extract`, `Exclude`, `Record` arguments and mapped-type keys, and a union with a non-string member. `namePattern` narrows it to exported type aliases whose name matches. Off in tests. |
|
|
177
182
|
| `@typescript-eslint/consistent-type-assertions` | `assertionStyle: never` | `warn` in both presets | V-C-10. `as X`, `as any` and `as unknown as X` warn; `as const` and `satisfies` do not. Off in tests. |
|
|
178
183
|
|
|
179
184
|
`const-class-values` and the cast rule only warn, so adopting them never fails a lint. Raise one to an error
|
|
180
185
|
with `[ConstClassValuesRule.NAME]: ConstClassValuesRule.build({ severity: 'error' })`. The 5-parameter
|
|
181
|
-
limit (V-C-02) is
|
|
186
|
+
limit (V-C-02) is `@venizia/max-params-own`, an error.
|
|
182
187
|
|
|
183
188
|
#### Blank-line padding
|
|
184
189
|
|
|
@@ -266,7 +271,7 @@ conventions, `curly`, the padding rules, plus these IGNIS rules (the node-protoc
|
|
|
266
271
|
| `@typescript-eslint/no-explicit-any` | `off` |
|
|
267
272
|
| `@typescript-eslint/ban-ts-comment` | `error` - `@ts-expect-error` with a description is still allowed |
|
|
268
273
|
| `@typescript-eslint/no-namespace` | `error` |
|
|
269
|
-
|
|
|
274
|
+
| `@venizia/no-unbraced-case` | `error` - the ESLint twin of `unicorn/switch-case-braces` (`always`); the fix wraps the statements in `{ }` |
|
|
270
275
|
|
|
271
276
|
### BrowserOxlintConfigs
|
|
272
277
|
|
|
@@ -311,9 +316,9 @@ decision (`click-events-have-key-events`, `no-static-element-interactions`,
|
|
|
311
316
|
|
|
312
317
|
| Rule | What it enforces |
|
|
313
318
|
| :--- | :--- |
|
|
314
|
-
|
|
|
315
|
-
|
|
|
316
|
-
|
|
|
319
|
+
| `@venizia/no-leaked-render` | See the table above. On JSX files |
|
|
320
|
+
| `@venizia/no-async-hook-callback` | A hook never gets an async function. On all source files |
|
|
321
|
+
| `@venizia/effect-cleanup-consistency` | An effect callback returns a cleanup on every path or on none. On all source files |
|
|
317
322
|
|
|
318
323
|
The presets start strict. An application that wants less overrides the rule after the preset:
|
|
319
324
|
|
|
@@ -406,7 +411,7 @@ The codemods are `drop-redundant-casts` (removes `as X` casts the compiler no lo
|
|
|
406
411
|
`const-classes` (turns a string-literal union into a const class), `async-style` (applies the async style
|
|
407
412
|
fixers and lists the rest), `namespace-functions` (moves calls of a function that moved into a class to the
|
|
408
413
|
class form), `connector-imports` (moves `@venizia/ignis/<connector sub-path>` imports to
|
|
409
|
-
`@venizia/ignis-connectors`) and `env-get` (strips the type arguments of `
|
|
414
|
+
`@venizia/ignis-connectors`), `class-renames` (renames the classes IGNIS renamed, such as `RejectionHelper` to `RejectionUtility`, at the import and every use), `typed-route-context` (types a route handler's context from its route config with `TContextOf`, and drops the `valid()` type arguments there) and `env-get` (strips the type arguments of `AppEnvs.get()`
|
|
410
415
|
for the string-reading `get()`; the receiver is a name the call's scope resolves to an import of `applicationEnvironment` or `AppEnvs` from the store module, or a const initialised from one; every other `get<...>(key)` call is listed as skipped, and a call it cannot place as manual, with its file and line) and `any-aliases` (replaces the removed `AnyType` and `AnyObject` aliases by what they stood for, `any` and `Record<string | symbol | number, any>`, so no type changes, and drops them from the imports; `--strict` writes `unknown` and `Record<string, unknown>` instead; it reads imports from `@venizia/ignis`, `-helpers`, `-inversion`, and from `@venizia/ardor` and `-kernel`, which re-exported them).
|
|
411
416
|
|
|
412
417
|
## Where it sits
|
|
@@ -5,19 +5,27 @@ const node_fs_1 = require("node:fs");
|
|
|
5
5
|
const node_path_1 = require("node:path");
|
|
6
6
|
const DEFAULT_WORKSPACE_SCOPE = '@venizia/';
|
|
7
7
|
/** The one place this engine builds an `Error`: `getError` would make dev-configs depend on inversion, which depends on dev-configs. */
|
|
8
|
-
// eslint-disable-next-line venizia/no-new-error -- getError would be a dev-configs -> inversion cycle
|
|
8
|
+
// eslint-disable-next-line @venizia/no-new-error -- getError would be a dev-configs -> inversion cycle
|
|
9
9
|
const purityError = (message) => new Error(message);
|
|
10
10
|
/** `types` describes the entry, it is not a runtime target; `./package.json` is not code. */
|
|
11
11
|
const NON_RUNTIME_CONDITION = 'types';
|
|
12
12
|
const NON_CODE_SUBPATH = './package.json';
|
|
13
|
+
const isObject = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
14
|
+
const isExportsTarget = (value) => typeof value === 'string' ||
|
|
15
|
+
(isObject(value) && Object.values(value).every((file) => typeof file === 'string'));
|
|
16
|
+
const isExportsMap = (value) => isObject(value) && Object.values(value).every((target) => isExportsTarget(target));
|
|
13
17
|
const readExportsMap = (opts) => {
|
|
14
18
|
const manifestPath = (0, node_path_1.join)(opts.root, 'packages', opts.package, 'package.json');
|
|
15
19
|
const manifest = JSON.parse((0, node_fs_1.readFileSync)(manifestPath, 'utf8'));
|
|
16
|
-
|
|
20
|
+
const exportsMap = isObject(manifest) ? manifest.exports : undefined;
|
|
21
|
+
if (!exportsMap) {
|
|
17
22
|
throw purityError(`[purity][manifest] '${opts.package}' claims browser purity but publishes no \`exports\` map ` +
|
|
18
23
|
`| There is nothing to derive rows from - remove the claim or add the map`);
|
|
19
24
|
}
|
|
20
|
-
|
|
25
|
+
if (!isExportsMap(exportsMap)) {
|
|
26
|
+
throw purityError(`[purity][manifest] '${opts.package}' has an \`exports\` map this check cannot read | Expected each sub-path to name a file, or an object of condition names to files`);
|
|
27
|
+
}
|
|
28
|
+
return exportsMap;
|
|
21
29
|
};
|
|
22
30
|
/**
|
|
23
31
|
* `exports` may spell one sub-path as several conditions pointing at different builds - the dual
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"manifest.js","sourceRoot":"","sources":["../../../src/checks/purity/manifest.ts"],"names":[],"mappings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AAC,CAAC;IACL,CAAC;CACF;AA9LD,wCA8LC","sourcesContent":["import { readFileSync } from 'node:fs';\nimport { join } from 'node:path';\n\n/** One built entry file that the browser-purity gate probes; rows are derived from the package `exports` map, not written by hand. */\nexport interface IPurityEntry {\n label: string;\n package: string;\n /** Repository-relative path to the built file the `exports` map points at. */\n entry: string;\n /**\n * Specifiers to pass through as `bun build --external`. Only for a third-party dependency whose\n * OWN packaging is out of this gate's remit - e.g. one that relies on its `package.json` `browser`\n * field remap, which the downstream app's bundler (Vite, ...) honours and `bun build` does not.\n * Never for the repository's own source: an external hides that file from the module graph\n * entirely, so using it on our own code would let a real leak through unseen rather than prove\n * anything pure. Enforced by {@link PurityManifest.assertNoWorkspaceExternal}, not left to this comment alone.\n */\n external?: string[];\n /**\n * This row is EXPECTED to be impure, so failing is its passing state. Derived from\n * {@link IPurityClaim.impure} - never authored on a row directly.\n */\n expectImpure?: boolean;\n}\n\n/**\n * A package whose published entry points carry a browser-purity claim.\n *\n * The ROW SET IS NEVER AUTHORED. It is read from the package's own `exports` map, so a sub-path\n * added to a manifest is probed the moment it is published.\n */\nexport interface IPurityClaim {\n /** Directory under `packages/`, and the token `devz check purity <token>` filters on. */\n package: string;\n /**\n * Sub-paths (as spelled in `exports`) when the claim covers only PART of the published surface.\n * Omit it and the whole surface is claimed. Every sub-path named here must still exist in\n * `exports`; a rename fails the derivation loudly rather than quietly dropping a row.\n */\n subpaths?: string[];\n /** `external` for one sub-path - see {@link IPurityEntry.external}. Keyed as spelled in `exports`. */\n external?: Record<string, string[]>;\n /**\n * Entries that CANNOT be browser-pure, keyed as spelled in `exports`, valued by the conditions\n * that are impure. The waiver is exact in BOTH directions: a listed entry that turns out to be\n * pure fails as loudly as an unlisted one that is not. Deriving still owns the ROW SET, so a\n * sub-path added later is claimed pure by default and has to earn its line here.\n */\n impure?: Record<string, string[]>;\n}\n\n/** What a repository may tune about the engine; everything else is the engine's contract. */\nexport interface IPurityOptions {\n /**\n * When set, every claimed sub-path must publish its runtime entries below this prefix (for\n * example `./dist/esm/`): a browser bundler needs an ES module, so a CommonJS-only entry makes\n * the claim unconsumable. Omit it for a repository that publishes a single build.\n */\n esmEntryPrefix?: string;\n\n /**\n * Package-name prefix of this repository's own packages; an `external` may never start with it.\n *\n * @default '@venizia/'\n */\n workspaceScope?: string;\n}\n\nconst DEFAULT_WORKSPACE_SCOPE = '@venizia/';\n\n/** The one place this engine builds an `Error`: `getError` would make dev-configs depend on inversion, which depends on dev-configs. */\n// eslint-disable-next-line venizia/no-new-error -- getError would be a dev-configs -> inversion cycle\nconst purityError = (message: string): Error => new Error(message);\n\n/** `types` describes the entry, it is not a runtime target; `./package.json` is not code. */\nconst NON_RUNTIME_CONDITION = 'types';\nconst NON_CODE_SUBPATH = './package.json';\n\ntype TExportsTarget = string | Record<string, string>;\n\nconst readExportsMap = (opts: {\n root: string;\n package: string;\n}): Record<string, TExportsTarget> => {\n const manifestPath = join(opts.root, 'packages', opts.package, 'package.json');\n const manifest = JSON.parse(readFileSync(manifestPath, 'utf8')) as {\n exports?: Record<string, TExportsTarget>;\n };\n\n if (!manifest.exports) {\n throw purityError(\n `[purity][manifest] '${opts.package}' claims browser purity but publishes no \\`exports\\` map ` +\n `| There is nothing to derive rows from - remove the claim or add the map`,\n );\n }\n\n return manifest.exports;\n};\n\n/**\n * `exports` may spell one sub-path as several conditions pointing at different builds - the dual\n * CJS/ESM packages do exactly that - and each is a separately resolvable file that a consumer can\n * end up importing, so each is probed. `default` normally repeats `require`, so files are deduped\n * and the FIRST condition naming a file is the one that labels it.\n */\nconst listConditionTargets = (\n target: TExportsTarget,\n): Array<{ condition: string; file: string }> => {\n if (typeof target === 'string') {\n return [{ condition: 'default', file: target }];\n }\n\n const seen = new Set<string>();\n const targets: Array<{ condition: string; file: string }> = [];\n\n const targetEntries = Object.entries(target);\n\n for (const [condition, file] of targetEntries) {\n if (condition === NON_RUNTIME_CONDITION || seen.has(file)) {\n continue;\n }\n\n seen.add(file);\n targets.push({ condition, file });\n }\n\n return targets;\n};\n\nconst buildLabel = (opts: {\n package: string;\n subpath: string;\n condition: string;\n isSoleTarget: boolean;\n}): string => {\n const { package: packageName, subpath, condition, isSoleTarget } = opts;\n const suffix = subpath === '.' ? '' : subpath.slice(1);\n const base = `${packageName}${suffix}`;\n\n return isSoleTarget ? base : `${base} [${condition}]`;\n};\n\n/** Derives the rows of the purity gate from the `exports` map of each claimed package, then runs the guards on them. */\nexport class PurityManifest {\n /**\n * A code-level guard, not just the JSDoc on `external`: it is an escape hatch from this gate, and a\n * hatch with no lock is one bad edit away from hiding a real leak - `external: ['@venizia/ignis-helpers']`\n * on a red entry would silently turn it green by removing the exact root-barrel import this gate\n * exists to catch from the module graph, rather than proving it absent.\n *\n * A plain `Error`, not `getError`: the engine runs from the repository root through `devz`, outside\n * every workspace package, and has no logger to resolve.\n */\n static assertNoWorkspaceExternal(opts: {\n manifest: IPurityEntry[];\n workspaceScope?: string;\n }): IPurityEntry[] {\n const { manifest, workspaceScope = DEFAULT_WORKSPACE_SCOPE } = opts;\n\n for (const row of manifest) {\n const specifiers = row.external ?? [];\n\n for (const specifier of specifiers) {\n if (!specifier.startsWith(workspaceScope)) {\n continue;\n }\n\n throw purityError(\n `[purity][manifest] Entry '${row.label}' externalises '${specifier}', a workspace package ` +\n `| \\`external\\` may only exempt THIRD-PARTY packaging, never the repository's own code - doing so ` +\n `would hide the exact leak this gate exists to catch`,\n );\n }\n }\n\n return manifest;\n }\n\n /**\n * Public for the tests, which have to drive a claim that no longer matches its package's\n * `exports` map - the staleness guard is the whole point of deriving, and it cannot be asserted\n * through a built manifest, which by construction is never stale.\n */\n static deriveEntries(opts: { claim: IPurityClaim; root: string }): IPurityEntry[] {\n const { claim, root } = opts;\n const exportsMap = readExportsMap({ root, package: claim.package });\n const published = Object.keys(exportsMap).filter((subpath) => subpath !== NON_CODE_SUBPATH);\n\n const subpathsList = claim.subpaths ?? [];\n\n for (const subpath of subpathsList) {\n if (published.includes(subpath)) {\n continue;\n }\n\n throw purityError(\n `[purity][manifest] '${claim.package}' claims '${subpath}', which its \\`exports\\` map no longer ` +\n `publishes | Published: ${published.join(', ')} - a renamed sub-path must not silently drop its row`,\n );\n }\n\n const claimExternalKeys = Object.keys(claim.external ?? {});\n\n for (const subpath of claimExternalKeys) {\n if (published.includes(subpath)) {\n continue;\n }\n\n throw purityError(\n `[purity][manifest] '${claim.package}' declares \\`external\\` for '${subpath}', which its ` +\n `\\`exports\\` map no longer publishes | An external that outlives its entry is a waiver ` +\n `nobody is reading`,\n );\n }\n\n const claimed = claim.subpaths ?? published;\n\n const claimImpureKeys = Object.keys(claim.impure ?? {});\n\n for (const subpath of claimImpureKeys) {\n if (claimed.includes(subpath)) {\n continue;\n }\n\n throw purityError(\n `[purity][manifest] '${claim.package}' waives '${subpath}' as impure, but that sub-path is not ` +\n `claimed | Claimed: ${claimed.join(', ')} - a waiver against nothing is one nobody is reading`,\n );\n }\n\n const entries: IPurityEntry[] = [];\n\n for (const subpath of claimed) {\n const targets = listConditionTargets(exportsMap[subpath]!);\n\n const conditions = claim.impure?.[subpath] ?? [];\n\n for (const condition of conditions) {\n if (targets.some((target) => target.condition === condition)) {\n continue;\n }\n\n throw purityError(\n `[purity][manifest] '${claim.package}' waives '${subpath}' under condition '${condition}', ` +\n `which its \\`exports\\` map does not publish | Published: ${targets.map((t) => t.condition).join(', ')}`,\n );\n }\n\n for (const { condition, file } of targets) {\n entries.push({\n label: buildLabel({\n package: claim.package,\n subpath,\n condition,\n isSoleTarget: targets.length === 1,\n }),\n package: claim.package,\n entry: join('packages', claim.package, file),\n ...(claim.external?.[subpath] ? { external: claim.external[subpath] } : {}),\n ...(claim.impure?.[subpath]?.includes(condition) ? { expectImpure: true } : {}),\n });\n }\n }\n\n return entries;\n }\n\n /**\n * A browser claim is only honest if a browser bundler can actually consume the entry. A CommonJS\n * entry forces every consumer into a workaround, so the claim carries the obligation: every claimed\n * sub-path must publish its runtime entries below `esmEntryPrefix`. Checked here rather than trusted\n * to a comment, for the same reason as {@link PurityManifest.assertNoWorkspaceExternal} - the failure is otherwise\n * invisible until someone tries to bundle the package downstream.\n */\n static assertBrowserEsmEntry(opts: {\n claims: IPurityClaim[];\n root: string;\n esmEntryPrefix: string;\n }): IPurityClaim[] {\n const { claims, root, esmEntryPrefix } = opts;\n\n for (const claim of claims) {\n const exportsMap = readExportsMap({ root, package: claim.package });\n const claimed =\n claim.subpaths ?? Object.keys(exportsMap).filter((s) => s !== NON_CODE_SUBPATH);\n\n for (const subpath of claimed) {\n const target = exportsMap[subpath];\n\n const runtimeTargets =\n typeof target === 'object' && target !== null\n ? Object.entries(target)\n .filter(([condition]) => condition !== NON_RUNTIME_CONDITION)\n .map(([, file]) => file)\n : [];\n\n if (\n runtimeTargets.length > 0 &&\n runtimeTargets.every((file) => file.startsWith(esmEntryPrefix))\n ) {\n continue;\n }\n\n throw purityError(\n `[purity][manifest] '${claim.package}' claims browser purity for '${subpath}' but its runtime ` +\n `entry is not in ${esmEntryPrefix.replace(/^\\.\\//, '')} | A browser bundler needs an ES module, so the claim ` +\n `cannot be consumed - build the package as ES modules`,\n );\n }\n }\n\n return claims;\n }\n\n /** The rows of a whole repository: every claim derived from its package's `exports`, then the guards. */\n static build(opts: {\n claims: IPurityClaim[];\n root: string;\n options?: IPurityOptions;\n }): IPurityEntry[] {\n const { claims, root, options = {} } = opts;\n const { esmEntryPrefix, workspaceScope = DEFAULT_WORKSPACE_SCOPE } = options;\n\n const checked =\n esmEntryPrefix === undefined\n ? claims\n : PurityManifest.assertBrowserEsmEntry({ claims, root, esmEntryPrefix });\n\n return PurityManifest.assertNoWorkspaceExternal({\n manifest: checked.flatMap((claim) => PurityManifest.deriveEntries({ claim, root })),\n workspaceScope,\n });\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"manifest.js","sourceRoot":"","sources":["../../../src/checks/purity/manifest.ts"],"names":[],"mappings":";;;AAAA,qCAAuC;AACvC,yCAAiC;AAmEjC,MAAM,uBAAuB,GAAG,W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,uBAAuB,KAAK,CAAC,OAAO,gCAAgC,OAAO,oBAAoB;oBAC7F,mBAAmB,cAAc,CAAC,OAAO,CAAC,OAAO,EAAE,EAAE,CAAC,wDAAwD;oBAC9G,sDAAsD,CACzD,CAAC;YACJ,CAAC;QACH,CAAC;QAED,OAAO,MAAM,CAAC;IAChB,CAAC;IAED,yGAAyG;IACzG,MAAM,CAAC,KAAK,CAAC,IAIZ;QACC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,GAAG,EAAE,EAAE,GAAG,IAAI,CAAC;QAC5C,MAAM,EAAE,cAAc,EAAE,cAAc,GAAG,uBAAuB,EAAE,GAAG,OAAO,CAAC;QAE7E,MAAM,OAAO,GACX,cAAc,KAAK,SAAS;YAC1B,CAAC,CAAC,MAAM;YACR,CAAC,CAAC,cAAc,CAAC,qBAAqB,CAAC,EAAE,MAAM,EAAE,IAAI,EAAE,cAAc,EAAE,CAAC,CAAC;QAE7E,OAAO,cAAc,CAAC,yBAAyB,CAAC;YAC9C,QAAQ,EAAE,OAAO,CAAC,OAAO,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,cAAc,CAAC,aAAa,CAAC,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;YACnF,cAAc;SACf,CAAC,CAAC;IACL,CAAC;CACF;AA9LD,wCA8LC","sourcesContent":["import { readFileSync } from 'node:fs';\nimport { join } from 'node:path';\n\n/** One built entry file that the browser-purity gate probes; rows are derived from the package `exports` map, not written by hand. */\nexport interface IPurityEntry {\n label: string;\n package: string;\n /** Repository-relative path to the built file the `exports` map points at. */\n entry: string;\n /**\n * Specifiers to pass through as `bun build --external`. Only for a third-party dependency whose\n * OWN packaging is out of this gate's remit - e.g. one that relies on its `package.json` `browser`\n * field remap, which the downstream app's bundler (Vite, ...) honours and `bun build` does not.\n * Never for the repository's own source: an external hides that file from the module graph\n * entirely, so using it on our own code would let a real leak through unseen rather than prove\n * anything pure. Enforced by {@link PurityManifest.assertNoWorkspaceExternal}, not left to this comment alone.\n */\n external?: string[];\n /**\n * This row is EXPECTED to be impure, so failing is its passing state. Derived from\n * {@link IPurityClaim.impure} - never authored on a row directly.\n */\n expectImpure?: boolean;\n}\n\n/**\n * A package whose published entry points carry a browser-purity claim.\n *\n * The ROW SET IS NEVER AUTHORED. It is read from the package's own `exports` map, so a sub-path\n * added to a manifest is probed the moment it is published.\n */\nexport interface IPurityClaim {\n /** Directory under `packages/`, and the token `devz check purity <token>` filters on. */\n package: string;\n /**\n * Sub-paths (as spelled in `exports`) when the claim covers only PART of the published surface.\n * Omit it and the whole surface is claimed. Every sub-path named here must still exist in\n * `exports`; a rename fails the derivation loudly rather than quietly dropping a row.\n */\n subpaths?: string[];\n /** `external` for one sub-path - see {@link IPurityEntry.external}. Keyed as spelled in `exports`. */\n external?: Record<string, string[]>;\n /**\n * Entries that CANNOT be browser-pure, keyed as spelled in `exports`, valued by the conditions\n * that are impure. The waiver is exact in BOTH directions: a listed entry that turns out to be\n * pure fails as loudly as an unlisted one that is not. Deriving still owns the ROW SET, so a\n * sub-path added later is claimed pure by default and has to earn its line here.\n */\n impure?: Record<string, string[]>;\n}\n\n/** What a repository may tune about the engine; everything else is the engine's contract. */\nexport interface IPurityOptions {\n /**\n * When set, every claimed sub-path must publish its runtime entries below this prefix (for\n * example `./dist/esm/`): a browser bundler needs an ES module, so a CommonJS-only entry makes\n * the claim unconsumable. Omit it for a repository that publishes a single build.\n */\n esmEntryPrefix?: string;\n\n /**\n * Package-name prefix of this repository's own packages; an `external` may never start with it.\n *\n * @default '@venizia/'\n */\n workspaceScope?: string;\n}\n\nconst DEFAULT_WORKSPACE_SCOPE = '@venizia/';\n\n/** The one place this engine builds an `Error`: `getError` would make dev-configs depend on inversion, which depends on dev-configs. */\n// eslint-disable-next-line @venizia/no-new-error -- getError would be a dev-configs -> inversion cycle\nconst purityError = (message: string): Error => new Error(message);\n\n/** `types` describes the entry, it is not a runtime target; `./package.json` is not code. */\nconst NON_RUNTIME_CONDITION = 'types';\nconst NON_CODE_SUBPATH = './package.json';\n\ntype TExportsTarget = string | Record<string, string>;\n\nconst isObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\nconst isExportsTarget = (value: unknown): value is TExportsTarget =>\n typeof value === 'string' ||\n (isObject(value) && Object.values(value).every((file) => typeof file === 'string'));\n\nconst isExportsMap = (value: unknown): value is Record<string, TExportsTarget> =>\n isObject(value) && Object.values(value).every((target) => isExportsTarget(target));\n\nconst readExportsMap = (opts: {\n root: string;\n package: string;\n}): Record<string, TExportsTarget> => {\n const manifestPath = join(opts.root, 'packages', opts.package, 'package.json');\n const manifest: unknown = JSON.parse(readFileSync(manifestPath, 'utf8'));\n const exportsMap = isObject(manifest) ? manifest.exports : undefined;\n\n if (!exportsMap) {\n throw purityError(\n `[purity][manifest] '${opts.package}' claims browser purity but publishes no \\`exports\\` map ` +\n `| There is nothing to derive rows from - remove the claim or add the map`,\n );\n }\n\n if (!isExportsMap(exportsMap)) {\n throw purityError(\n `[purity][manifest] '${opts.package}' has an \\`exports\\` map this check cannot read | Expected each sub-path to name a file, or an object of condition names to files`,\n );\n }\n\n return exportsMap;\n};\n\n/**\n * `exports` may spell one sub-path as several conditions pointing at different builds - the dual\n * CJS/ESM packages do exactly that - and each is a separately resolvable file that a consumer can\n * end up importing, so each is probed. `default` normally repeats `require`, so files are deduped\n * and the FIRST condition naming a file is the one that labels it.\n */\nconst listConditionTargets = (\n target: TExportsTarget,\n): Array<{ condition: string; file: string }> => {\n if (typeof target === 'string') {\n return [{ condition: 'default', file: target }];\n }\n\n const seen = new Set<string>();\n const targets: Array<{ condition: string; file: string }> = [];\n\n const targetEntries = Object.entries(target);\n\n for (const [condition, file] of targetEntries) {\n if (condition === NON_RUNTIME_CONDITION || seen.has(file)) {\n continue;\n }\n\n seen.add(file);\n targets.push({ condition, file });\n }\n\n return targets;\n};\n\nconst buildLabel = (opts: {\n package: string;\n subpath: string;\n condition: string;\n isSoleTarget: boolean;\n}): string => {\n const { package: packageName, subpath, condition, isSoleTarget } = opts;\n const suffix = subpath === '.' ? '' : subpath.slice(1);\n const base = `${packageName}${suffix}`;\n\n return isSoleTarget ? base : `${base} [${condition}]`;\n};\n\n/** Derives the rows of the purity gate from the `exports` map of each claimed package, then runs the guards on them. */\nexport class PurityManifest {\n /**\n * A code-level guard, not just the JSDoc on `external`: it is an escape hatch from this gate, and a\n * hatch with no lock is one bad edit away from hiding a real leak - `external: ['@venizia/ignis-helpers']`\n * on a red entry would silently turn it green by removing the exact root-barrel import this gate\n * exists to catch from the module graph, rather than proving it absent.\n *\n * A plain `Error`, not `getError`: the engine runs from the repository root through `devz`, outside\n * every workspace package, and has no logger to resolve.\n */\n static assertNoWorkspaceExternal(opts: {\n manifest: IPurityEntry[];\n workspaceScope?: string;\n }): IPurityEntry[] {\n const { manifest, workspaceScope = DEFAULT_WORKSPACE_SCOPE } = opts;\n\n for (const row of manifest) {\n const specifiers = row.external ?? [];\n\n for (const specifier of specifiers) {\n if (!specifier.startsWith(workspaceScope)) {\n continue;\n }\n\n throw purityError(\n `[purity][manifest] Entry '${row.label}' externalises '${specifier}', a workspace package ` +\n `| \\`external\\` may only exempt THIRD-PARTY packaging, never the repository's own code - doing so ` +\n `would hide the exact leak this gate exists to catch`,\n );\n }\n }\n\n return manifest;\n }\n\n /**\n * Public for the tests, which have to drive a claim that no longer matches its package's\n * `exports` map - the staleness guard is the whole point of deriving, and it cannot be asserted\n * through a built manifest, which by construction is never stale.\n */\n static deriveEntries(opts: { claim: IPurityClaim; root: string }): IPurityEntry[] {\n const { claim, root } = opts;\n const exportsMap = readExportsMap({ root, package: claim.package });\n const published = Object.keys(exportsMap).filter((subpath) => subpath !== NON_CODE_SUBPATH);\n\n const subpathsList = claim.subpaths ?? [];\n\n for (const subpath of subpathsList) {\n if (published.includes(subpath)) {\n continue;\n }\n\n throw purityError(\n `[purity][manifest] '${claim.package}' claims '${subpath}', which its \\`exports\\` map no longer ` +\n `publishes | Published: ${published.join(', ')} - a renamed sub-path must not silently drop its row`,\n );\n }\n\n const claimExternalKeys = Object.keys(claim.external ?? {});\n\n for (const subpath of claimExternalKeys) {\n if (published.includes(subpath)) {\n continue;\n }\n\n throw purityError(\n `[purity][manifest] '${claim.package}' declares \\`external\\` for '${subpath}', which its ` +\n `\\`exports\\` map no longer publishes | An external that outlives its entry is a waiver ` +\n `nobody is reading`,\n );\n }\n\n const claimed = claim.subpaths ?? published;\n\n const claimImpureKeys = Object.keys(claim.impure ?? {});\n\n for (const subpath of claimImpureKeys) {\n if (claimed.includes(subpath)) {\n continue;\n }\n\n throw purityError(\n `[purity][manifest] '${claim.package}' waives '${subpath}' as impure, but that sub-path is not ` +\n `claimed | Claimed: ${claimed.join(', ')} - a waiver against nothing is one nobody is reading`,\n );\n }\n\n const entries: IPurityEntry[] = [];\n\n for (const subpath of claimed) {\n const targets = listConditionTargets(exportsMap[subpath]!);\n\n const conditions = claim.impure?.[subpath] ?? [];\n\n for (const condition of conditions) {\n if (targets.some((target) => target.condition === condition)) {\n continue;\n }\n\n throw purityError(\n `[purity][manifest] '${claim.package}' waives '${subpath}' under condition '${condition}', ` +\n `which its \\`exports\\` map does not publish | Published: ${targets.map((t) => t.condition).join(', ')}`,\n );\n }\n\n for (const { condition, file } of targets) {\n entries.push({\n label: buildLabel({\n package: claim.package,\n subpath,\n condition,\n isSoleTarget: targets.length === 1,\n }),\n package: claim.package,\n entry: join('packages', claim.package, file),\n ...(claim.external?.[subpath] ? { external: claim.external[subpath] } : {}),\n ...(claim.impure?.[subpath]?.includes(condition) ? { expectImpure: true } : {}),\n });\n }\n }\n\n return entries;\n }\n\n /**\n * A browser claim is only honest if a browser bundler can actually consume the entry. A CommonJS\n * entry forces every consumer into a workaround, so the claim carries the obligation: every claimed\n * sub-path must publish its runtime entries below `esmEntryPrefix`. Checked here rather than trusted\n * to a comment, for the same reason as {@link PurityManifest.assertNoWorkspaceExternal} - the failure is otherwise\n * invisible until someone tries to bundle the package downstream.\n */\n static assertBrowserEsmEntry(opts: {\n claims: IPurityClaim[];\n root: string;\n esmEntryPrefix: string;\n }): IPurityClaim[] {\n const { claims, root, esmEntryPrefix } = opts;\n\n for (const claim of claims) {\n const exportsMap = readExportsMap({ root, package: claim.package });\n const claimed =\n claim.subpaths ?? Object.keys(exportsMap).filter((s) => s !== NON_CODE_SUBPATH);\n\n for (const subpath of claimed) {\n const target = exportsMap[subpath];\n\n const runtimeTargets =\n typeof target === 'object' && target !== null\n ? Object.entries(target)\n .filter(([condition]) => condition !== NON_RUNTIME_CONDITION)\n .map(([, file]) => file)\n : [];\n\n if (\n runtimeTargets.length > 0 &&\n runtimeTargets.every((file) => file.startsWith(esmEntryPrefix))\n ) {\n continue;\n }\n\n throw purityError(\n `[purity][manifest] '${claim.package}' claims browser purity for '${subpath}' but its runtime ` +\n `entry is not in ${esmEntryPrefix.replace(/^\\.\\//, '')} | A browser bundler needs an ES module, so the claim ` +\n `cannot be consumed - build the package as ES modules`,\n );\n }\n }\n\n return claims;\n }\n\n /** The rows of a whole repository: every claim derived from its package's `exports`, then the guards. */\n static build(opts: {\n claims: IPurityClaim[];\n root: string;\n options?: IPurityOptions;\n }): IPurityEntry[] {\n const { claims, root, options = {} } = opts;\n const { esmEntryPrefix, workspaceScope = DEFAULT_WORKSPACE_SCOPE } = options;\n\n const checked =\n esmEntryPrefix === undefined\n ? claims\n : PurityManifest.assertBrowserEsmEntry({ claims, root, esmEntryPrefix });\n\n return PurityManifest.assertNoWorkspaceExternal({\n manifest: checked.flatMap((claim) => PurityManifest.deriveEntries({ claim, root })),\n workspaceScope,\n });\n }\n}\n"]}
|
|
@@ -4,6 +4,7 @@ exports.PurityProbe = exports.GLOBAL_PATTERNS = exports.ProbeSeverities = export
|
|
|
4
4
|
const promises_1 = require("node:fs/promises");
|
|
5
5
|
const node_module_1 = require("node:module");
|
|
6
6
|
const node_path_1 = require("node:path");
|
|
7
|
+
const cli_output_1 = require("../../common/cli-output");
|
|
7
8
|
/** Where the probe keeps its metafile, relative to the `cwd` it is given: the repository's own scratch, never the system temp. */
|
|
8
9
|
exports.PURITY_SCRATCH_DIR = '.agents/local/tmp';
|
|
9
10
|
/**
|
|
@@ -165,6 +166,17 @@ const findUnresolvedExternalSpecifiers = (opts) => {
|
|
|
165
166
|
}
|
|
166
167
|
return [...unresolved].sort();
|
|
167
168
|
};
|
|
169
|
+
/** Whether `value` carries what the probe reads: every input with its imports, each with a path. */
|
|
170
|
+
const isMetafile = (value) => {
|
|
171
|
+
const read = (node, key) => typeof node === 'object' && node !== null ? Reflect.get(node, key) : undefined;
|
|
172
|
+
const inputs = read(value, 'inputs');
|
|
173
|
+
return (typeof inputs === 'object' &&
|
|
174
|
+
inputs !== null &&
|
|
175
|
+
Object.values(inputs).every((input) => {
|
|
176
|
+
const imports = read(input, 'imports');
|
|
177
|
+
return Array.isArray(imports) && imports.every((it) => typeof read(it, 'path') === 'string');
|
|
178
|
+
}));
|
|
179
|
+
};
|
|
168
180
|
/**
|
|
169
181
|
* Reads and removes the metafile unconditionally. Returns `undefined` rather than throwing -
|
|
170
182
|
* `PurityProbe.probeEntry` reports on every entry it is given rather than aborting the run of the other five.
|
|
@@ -172,11 +184,16 @@ const findUnresolvedExternalSpecifiers = (opts) => {
|
|
|
172
184
|
const readMetafile = async (path) => {
|
|
173
185
|
try {
|
|
174
186
|
const result = await Bun.file(path).text();
|
|
175
|
-
|
|
187
|
+
const metafile = JSON.parse(result);
|
|
188
|
+
if (!isMetafile(metafile)) {
|
|
189
|
+
cli_output_1.CliOutput.error(`[purity] The build metafile at ${path} names no inputs with their imports`);
|
|
190
|
+
return undefined;
|
|
191
|
+
}
|
|
192
|
+
return metafile;
|
|
176
193
|
}
|
|
177
194
|
catch (error) {
|
|
178
195
|
const reason = error instanceof Error ? error.message : String(error);
|
|
179
|
-
|
|
196
|
+
cli_output_1.CliOutput.error(`[purity] Failed to read the build metafile at ${path}: ${reason}`);
|
|
180
197
|
return undefined;
|
|
181
198
|
}
|
|
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port { builtinModules } from 'node:module';\nimport { join } from 'node:path';\n\n/** Outcome of probing one entry: `ok` is the verdict, `builtins` and `globals` are what made it fail, `sizeBytes` is the bundle size. */\nexport interface IPurityResult {\n entry: string;\n ok: boolean;\n sizeBytes: number;\n builtins: string[];\n globals: string[];\n /** Node-global reads that cannot throw in a browser. Reported, never fatal. */\n guardedGlobals: string[];\n /**\n * Specifiers this probe run excluded from its own module graph. Always echoed back, on both the\n * passing and failing path - an entry that externalises something is measuring less than an entry\n * that does not, and that must stay visible next to the result, not be a silent input.\n */\n external: string[];\n buildError?: string;\n}\n\n/** Where the probe keeps its metafile, relative to the `cwd` it is given: the repository's own scratch, never the system temp. */\nexport const PURITY_SCRATCH_DIR = '.agents/local/tmp';\n\n/**\n * A browser entry must never reach `@venizia/dev-configs`: it is the Bun-only tooling package (its\n * `./testing` entry imports `bun:test`). Matches the workspace folder (not its own test fixtures) and the installed copy.\n */\nconst DEV_CONFIGS_PATH =\n /(^|\\/)(packages\\/dev-configs\\/(?!src\\/__tests__\\/)|node_modules\\/@venizia\\/dev-configs\\/)/;\n\n/** What a matched global means: ERROR is fatal, GUARDED is reported and never fatal. */\nexport class ProbeSeverities {\n static readonly ERROR = 'error';\n static readonly GUARDED = 'guarded';\n\n static readonly SCHEME_SET = new Set<string>([this.ERROR, this.GUARDED]);\n\n static isValid(value: string): value is TProbeSeverity {\n return this.SCHEME_SET.has(value);\n }\n}\n\n/** `error` or `guarded`: whether a matched Node global fails the probe or is only reported. */\nexport type TProbeSeverity = Extract<\n (typeof ProbeSeverities)[keyof typeof ProbeSeverities],\n string\n>;\n\n/**\n * Node globals survive verbatim into a `target: 'browser'` bundle, so a gate reading only module\n * specifiers reports clean on `process.env.NODE_ENV`. Each pattern must be anchored: a bundle\n * legitimately contains identifiers like `processQueue`. A lookbehind that rejects a preceding dot\n * also rejects `globalThis.process`, so every access path needs its own pattern.\n *\n * `severity` separates a read that throws from one that cannot. Optional chaining is not itself the\n * difference: `process?.env` throws a ReferenceError when `process` is a free identifier, while\n * `globalThis.process?.env` is an ordinary property read on an object that always exists.\n *\n * `guarded` means \"reported, never fatal\". Bare `process?.` sits there because this probe matches\n * bundled text and has no scope information: hono's `getColorEnabled` writes\n * `const { process, Deno } = globalThis;` and then `process?.env`, which is a local binding and\n * perfectly safe, and no regex can tell that apart from a free global. Failing on it would make the\n * gate cry wolf on a dependency; the unguarded `process.` and `globalThis.process.` forms stay\n * fatal, and those are the ones that are unambiguously browser-breaking.\n *\n * Exported for `probe.test.ts` to assert against directly, alongside {@link PurityProbe.stripBundlerPathComments}.\n */\nexport const GLOBAL_PATTERNS: Array<{\n name: string;\n pattern: RegExp;\n severity: TProbeSeverity;\n}> = [\n { name: 'process', pattern: /(?<![A-Za-z0-9_$.])process\\s*\\./, severity: 'error' },\n { name: 'process?.', pattern: /(?<![A-Za-z0-9_$.])process\\s*\\?\\./, severity: 'guarded' },\n {\n name: 'globalThis.process',\n pattern: /(?<![A-Za-z0-9_$.])globalThis\\s*\\.\\s*process\\s*\\./,\n severity: 'error',\n },\n {\n name: 'globalThis.process?.',\n pattern: /(?<![A-Za-z0-9_$.])globalThis\\s*\\.\\s*process\\s*\\?\\./,\n severity: 'guarded',\n },\n {\n name: '__dirname',\n pattern: /(?<![A-Za-z0-9_$.])__dirname(?![A-Za-z0-9_$])/,\n severity: 'error',\n },\n {\n name: '__filename',\n pattern: /(?<![A-Za-z0-9_$.])__filename(?![A-Za-z0-9_$])/,\n severity: 'error',\n },\n {\n name: 'createRequire',\n pattern: /(?<![A-Za-z0-9_$.])createRequire\\s*\\(/,\n severity: 'error',\n },\n { name: 'require(', pattern: /(?<![A-Za-z0-9_$.])require\\s*\\(/, severity: 'error' },\n // Member access only. `typeof Bun !== 'undefined'` is the legitimate runtime probe and never\n // throws; `Bun.serve(...)` in a browser does.\n { name: 'Bun', pattern: /(?<![A-Za-z0-9_$.])Bun\\s*\\./, severity: 'error' },\n];\n\n/**\n * Bun's bundler prefixes every CommonJS-wrapped module with a full-line `// <path>.js` header (this\n * whole workspace emits CJS `dist/*.js` - no package declares `\"type\": \"module\"`). A source path is\n * free-form and can legitimately contain `process` as a substring with no identifier boundary on\n * its left, e.g. this gate's own `transport/in-process.js`: the header reads\n * `// packages/core-worker/dist/transport/in-process.js`, and `process.` there is a filename\n * fragment, not a read of the global. `GLOBAL_PATTERNS` matches bundled TEXT with no scope\n * information, so it cannot tell a path comment from code - stripped before matching.\n */\nconst BUNDLER_PATH_COMMENT = /^\\/\\/ [\\w@./-]+\\.(?:c|m)?js$/gm;\n\ninterface IMetafileImport {\n path: string;\n original?: string;\n external?: boolean;\n}\n\ninterface IMetafileInput {\n imports: IMetafileImport[];\n}\n\ninterface IMetafile {\n inputs: Record<string, IMetafileInput>;\n}\n\n/**\n * `node:module`'s own list, not a hand-maintained one: a bare `import ... from 'fs'` bundles\n * identically to `'node:fs'` (Bun stubs both to an empty object), and the metafile records\n * whichever spelling the source used. Matching by prefix alone misses the bare form entirely.\n */\nconst BUILTIN_MODULE_NAMES = new Set(builtinModules);\n\nconst isBuiltinSpecifier = (specifier: string): boolean => {\n const bareName = specifier.startsWith('node:') ? specifier.slice('node:'.length) : specifier;\n\n return BUILTIN_MODULE_NAMES.has(bareName);\n};\n\n/**\n * Measured against Bun 1.3.14: `--target=browser` never fails on a `node:` import and never leaves\n * the specifier in the bundled text. An unpolyfillable builtin (`fs`, `child_process`, ...) is\n * stubbed to an empty object; a polyfillable one (`crypto`, `path`, ...) is inlined in full under a\n * `/bun-vfs$$/` virtual path. Either way `exitCode` stays 0 and the specifier never survives into\n * stdout. The `--metafile` module graph is the only place it is preserved.\n */\nconst findBuiltinSpecifiers = (metafile: IMetafile): string[] => {\n const builtins = new Set<string>();\n\n const metafileInputsEntries = Object.entries(metafile.inputs);\n\n for (const [inputPath, input] of metafileInputsEntries) {\n if (isBuiltinSpecifier(inputPath)) {\n builtins.add(inputPath);\n }\n\n for (const dependency of input.imports) {\n const specifier = dependency.original ?? dependency.path;\n\n if (isBuiltinSpecifier(specifier)) {\n builtins.add(specifier);\n }\n }\n }\n\n return [...builtins].sort();\n};\n\n/**\n * A real npm dependency bundles in full under this target (measured: `zod` produces zero\n * `external` entries) and a genuinely missing package fails the build outright (nonzero exit,\n * caught before this runs). But a package's own `browser` field can remap a dependency to `false` -\n * the standard convention for disabling a Node-only dependency in browser builds - and Bun honours\n * that remap by leaving the import external with exit 0, whether or not the remapped name is a\n * builtin. An unresolved import in a browser bundle is not safe to wave through either way -\n * UNLESS the manifest entry asked for exactly this specifier via `external`, in which case its\n * presence here is the requested exclusion working, not a leak.\n */\n/**\n * A relative specifier is the package's own file, and a truly unreachable one fails the build with a\n * nonzero exit, which is caught before this runs. Bun's METAFILE nonetheless marks a re-export of the\n * form `export { name } from './x.js'` as `external` while inlining it - measured on\n * `helpers/dist/esm/core.js`: six such specifiers reported external, `Bundled 192 modules`, and the\n * output contains `class BaseHelper` with no bare relative import left in it. Reading the metafile\n * literally there reports a leak the bundle does not have.\n */\nconst isRelativeSpecifier = (specifier: string): boolean => {\n return specifier.startsWith('./') || specifier.startsWith('../');\n};\n\nconst findUnresolvedExternalSpecifiers = (opts: {\n metafile: IMetafile;\n builtins: Set<string>;\n requestedExternal: Set<string>;\n}): string[] => {\n const { metafile, builtins, requestedExternal } = opts;\n const unresolved = new Set<string>();\n\n const isRequestedExternal = (specifier: string): boolean => {\n for (const requested of requestedExternal) {\n if (specifier === requested || specifier.startsWith(`${requested}/`)) {\n return true;\n }\n }\n\n return false;\n };\n\n const metafileInputsValues = Object.values(metafile.inputs);\n\n for (const input of metafileInputsValues) {\n for (const dependency of input.imports) {\n if (!dependency.external) {\n continue;\n }\n\n const specifier = dependency.original ?? dependency.path;\n\n if (\n isRelativeSpecifier(specifier) ||\n builtins.has(specifier) ||\n isRequestedExternal(specifier)\n ) {\n continue;\n }\n\n unresolved.add(specifier);\n }\n }\n\n return [...unresolved].sort();\n};\n\n/**\n * Reads and removes the metafile unconditionally. Returns `undefined` rather than throwing -\n * `PurityProbe.probeEntry` reports on every entry it is given rather than aborting the run of the other five.\n */\nconst readMetafile = async (path: string): Promise<IMetafile | undefined> => {\n try {\n const result = await Bun.file(path).text();\n\n return JSON.parse(result) as IMetafile;\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n console.error(`[purity] Failed to read the build metafile at ${path}: ${reason}`);\n\n return undefined;\n } finally {\n await rm(path, { force: true });\n }\n};\n\n/** Bundles a built entry for the browser with `bun build` and reports the Node builtins and Node globals that reach the bundle. */\nexport class PurityProbe {\n /**\n * Public so `probe.test.ts` can assert against the literal collision string directly, without\n * spawning `bun build` - a fixture whose OWN entry-path comment happens to reproduce the collision\n * is not something a filename choice can be relied on to keep reproducing.\n */\n static stripBundlerPathComments(opts: { text: string }): string {\n return opts.text.replace(BUNDLER_PATH_COMMENT, '');\n }\n\n /**\n * The CLI, not `Bun.build()`: the in-process bundler resolves this workspace's symlinked\n * dependencies to directories and dies on them.\n */\n static async probeEntry(opts: {\n entry: string;\n cwd: string;\n external?: string[];\n /** @default join(cwd, PURITY_SCRATCH_DIR) */\n scratchDir?: string;\n }): Promise<IPurityResult> {\n const { entry, cwd, external = [], scratchDir = join(cwd, PURITY_SCRATCH_DIR) } = opts;\n await mkdir(scratchDir, { recursive: true });\n const metafilePath = join(scratchDir, `purity-${crypto.randomUUID()}.json`);\n\n // `--env=disable`: Bun inlines `process.env.NODE_ENV` as a compile-time string constant by\n // default, regardless of whether the read is reachable. That erases the very read this probe\n // exists to catch, and the erasure depends on the ambient `NODE_ENV` the probe happens to run\n // under - the same failure shape as the undetected leak this gate was built to prevent.\n const externalArgs = external.flatMap((specifier) => ['--external', specifier]);\n const proc = Bun.spawn(\n [\n 'bun',\n 'build',\n entry,\n '--target=browser',\n '--format=esm',\n '--env=disable',\n `--metafile=${metafilePath}`,\n ...externalArgs,\n ],\n { cwd, stdout: 'pipe', stderr: 'pipe' },\n );\n\n const [stdout, stderr, exitCode] = await Promise.all([\n new Response(proc.stdout).text(),\n new Response(proc.stderr).text(),\n proc.exited,\n ]);\n\n if (exitCode !== 0) {\n await rm(metafilePath, { force: true });\n\n return {\n entry,\n ok: false,\n sizeBytes: 0,\n builtins: [],\n globals: [],\n guardedGlobals: [],\n external,\n buildError: stderr.trim(),\n };\n }\n\n const metafile = await readMetafile(metafilePath);\n\n if (!metafile) {\n return {\n entry,\n ok: false,\n sizeBytes: stdout.length,\n builtins: [],\n globals: [],\n guardedGlobals: [],\n external,\n buildError: 'Could not read the bun build metafile - the probe result is not trustworthy',\n };\n }\n\n const builtins = findBuiltinSpecifiers(metafile);\n const reachesDevConfigs = Object.keys(metafile.inputs).some((inputPath) =>\n DEV_CONFIGS_PATH.test(inputPath),\n );\n const unresolvedExternals = findUnresolvedExternalSpecifiers({\n metafile,\n builtins: new Set(builtins),\n requestedExternal: new Set(external),\n });\n const scannableText = PurityProbe.stripBundlerPathComments({ text: stdout });\n const matched = GLOBAL_PATTERNS.filter((g) => g.pattern.test(scannableText));\n const globals = matched.filter((g) => g.severity === ProbeSeverities.ERROR).map((g) => g.name);\n const guardedGlobals = matched\n .filter((g) => g.severity === ProbeSeverities.GUARDED)\n .map((g) => g.name);\n\n if (builtins.length > 0 || unresolvedExternals.length > 0 || reachesDevConfigs) {\n const reasons: string[] = [];\n\n if (reachesDevConfigs) {\n reasons.push(\n 'reaches @venizia/dev-configs, which is Bun-only tooling and never a browser dependency',\n );\n }\n\n if (builtins.length > 0) {\n reasons.push(`node builtin import(s): ${builtins.join(', ')}`);\n }\n\n if (unresolvedExternals.length > 0) {\n reasons.push(`unresolved external import(s): ${unresolvedExternals.join(', ')}`);\n }\n\n return {\n entry,\n ok: false,\n sizeBytes: stdout.length,\n builtins,\n globals,\n guardedGlobals,\n external,\n buildError: reasons.join(' | '),\n };\n }\n\n return {\n entry,\n ok: globals.length === 0,\n sizeBytes: stdout.length,\n builtins,\n globals,\n guardedGlobals,\n external,\n };\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"probe.js","sourceRoot":"","sources":["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AiB,EAAE,CAAC;YAC/E,MAAM,OAAO,GAAa,EAAE,CAAC;YAE7B,IAAI,iBAAiB,EAAE,CAAC;gBACtB,OAAO,CAAC,IAAI,CACV,wFAAwF,CACzF,CAAC;YACJ,CAAC;YAED,IAAI,QAAQ,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;gBACxB,OAAO,CAAC,IAAI,CAAC,2BAA2B,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;YACjE,CAAC;YAED,IAAI,mBAAmB,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;gBACnC,OAAO,CAAC,IAAI,CAAC,kCAAkC,mBAAmB,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;YACnF,CAAC;YAED,OAAO;gBACL,KAAK;gBACL,EAAE,EAAE,KAAK;gBACT,SAAS,EAAE,MAAM,CAAC,MAAM;gBACxB,QAAQ;gBACR,OAAO;gBACP,cAAc;gBACd,QAAQ;gBACR,UAAU,EAAE,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC;aAChC,CAAC;QACJ,CAAC;QAED,OAAO;YACL,KAAK;YACL,EAAE,EAAE,OAAO,CAAC,MAAM,KAAK,CAAC;YACxB,SAAS,EAAE,MAAM,CAAC,MAAM;YACxB,QAAQ;YACR,OAAO;YACP,cAAc;YACd,QAAQ;SACT,CAAC;IACJ,CAAC;CACF;AAvID,kCAuIC","sourcesContent":["import { mkdir, rm } from 'node:fs/promises';\nimport { builtinModules } from 'node:module';\nimport { join } from 'node:path';\nimport { CliOutput } from '../../common/cli-output';\n\n/** Outcome of probing one entry: `ok` is the verdict, `builtins` and `globals` are what made it fail, `sizeBytes` is the bundle size. */\nexport interface IPurityResult {\n entry: string;\n ok: boolean;\n sizeBytes: number;\n builtins: string[];\n globals: string[];\n /** Node-global reads that cannot throw in a browser. Reported, never fatal. */\n guardedGlobals: string[];\n /**\n * Specifiers this probe run excluded from its own module graph. Always echoed back, on both the\n * passing and failing path - an entry that externalises something is measuring less than an entry\n * that does not, and that must stay visible next to the result, not be a silent input.\n */\n external: string[];\n buildError?: string;\n}\n\n/** Where the probe keeps its metafile, relative to the `cwd` it is given: the repository's own scratch, never the system temp. */\nexport const PURITY_SCRATCH_DIR = '.agents/local/tmp';\n\n/**\n * A browser entry must never reach `@venizia/dev-configs`: it is the Bun-only tooling package (its\n * `./testing` entry imports `bun:test`). Matches the workspace folder (not its own test fixtures) and the installed copy.\n */\nconst DEV_CONFIGS_PATH =\n /(^|\\/)(packages\\/dev-configs\\/(?!src\\/__tests__\\/)|node_modules\\/@venizia\\/dev-configs\\/)/;\n\n/** What a matched global means: ERROR is fatal, GUARDED is reported and never fatal. */\nexport class ProbeSeverities {\n static readonly ERROR = 'error';\n static readonly GUARDED = 'guarded';\n\n static readonly SCHEME_SET = new Set<string>([this.ERROR, this.GUARDED]);\n\n static isValid(value: string): value is TProbeSeverity {\n return this.SCHEME_SET.has(value);\n }\n}\n\n/** `error` or `guarded`: whether a matched Node global fails the probe or is only reported. */\nexport type TProbeSeverity = Extract<\n (typeof ProbeSeverities)[keyof typeof ProbeSeverities],\n string\n>;\n\n/**\n * Node globals survive verbatim into a `target: 'browser'` bundle, so a gate reading only module\n * specifiers reports clean on `process.env.NODE_ENV`. Each pattern must be anchored: a bundle\n * legitimately contains identifiers like `processQueue`. A lookbehind that rejects a preceding dot\n * also rejects `globalThis.process`, so every access path needs its own pattern.\n *\n * `severity` separates a read that throws from one that cannot. Optional chaining is not itself the\n * difference: `process?.env` throws a ReferenceError when `process` is a free identifier, while\n * `globalThis.process?.env` is an ordinary property read on an object that always exists.\n *\n * `guarded` means \"reported, never fatal\". Bare `process?.` sits there because this probe matches\n * bundled text and has no scope information: hono's `getColorEnabled` writes\n * `const { process, Deno } = globalThis;` and then `process?.env`, which is a local binding and\n * perfectly safe, and no regex can tell that apart from a free global. Failing on it would make the\n * gate cry wolf on a dependency; the unguarded `process.` and `globalThis.process.` forms stay\n * fatal, and those are the ones that are unambiguously browser-breaking.\n *\n * Exported for `probe.test.ts` to assert against directly, alongside {@link PurityProbe.stripBundlerPathComments}.\n */\nexport const GLOBAL_PATTERNS: Array<{\n name: string;\n pattern: RegExp;\n severity: TProbeSeverity;\n}> = [\n { name: 'process', pattern: /(?<![A-Za-z0-9_$.])process\\s*\\./, severity: 'error' },\n { name: 'process?.', pattern: /(?<![A-Za-z0-9_$.])process\\s*\\?\\./, severity: 'guarded' },\n {\n name: 'globalThis.process',\n pattern: /(?<![A-Za-z0-9_$.])globalThis\\s*\\.\\s*process\\s*\\./,\n severity: 'error',\n },\n {\n name: 'globalThis.process?.',\n pattern: /(?<![A-Za-z0-9_$.])globalThis\\s*\\.\\s*process\\s*\\?\\./,\n severity: 'guarded',\n },\n {\n name: '__dirname',\n pattern: /(?<![A-Za-z0-9_$.])__dirname(?![A-Za-z0-9_$])/,\n severity: 'error',\n },\n {\n name: '__filename',\n pattern: /(?<![A-Za-z0-9_$.])__filename(?![A-Za-z0-9_$])/,\n severity: 'error',\n },\n {\n name: 'createRequire',\n pattern: /(?<![A-Za-z0-9_$.])createRequire\\s*\\(/,\n severity: 'error',\n },\n { name: 'require(', pattern: /(?<![A-Za-z0-9_$.])require\\s*\\(/, severity: 'error' },\n // Member access only. `typeof Bun !== 'undefined'` is the legitimate runtime probe and never\n // throws; `Bun.serve(...)` in a browser does.\n { name: 'Bun', pattern: /(?<![A-Za-z0-9_$.])Bun\\s*\\./, severity: 'error' },\n];\n\n/**\n * Bun's bundler prefixes every CommonJS-wrapped module with a full-line `// <path>.js` header (this\n * whole workspace emits CJS `dist/*.js` - no package declares `\"type\": \"module\"`). A source path is\n * free-form and can legitimately contain `process` as a substring with no identifier boundary on\n * its left, e.g. this gate's own `transport/in-process.js`: the header reads\n * `// packages/core-worker/dist/transport/in-process.js`, and `process.` there is a filename\n * fragment, not a read of the global. `GLOBAL_PATTERNS` matches bundled TEXT with no scope\n * information, so it cannot tell a path comment from code - stripped before matching.\n */\nconst BUNDLER_PATH_COMMENT = /^\\/\\/ [\\w@./-]+\\.(?:c|m)?js$/gm;\n\ninterface IMetafileImport {\n path: string;\n original?: string;\n external?: boolean;\n}\n\ninterface IMetafileInput {\n imports: IMetafileImport[];\n}\n\ninterface IMetafile {\n inputs: Record<string, IMetafileInput>;\n}\n\n/**\n * `node:module`'s own list, not a hand-maintained one: a bare `import ... from 'fs'` bundles\n * identically to `'node:fs'` (Bun stubs both to an empty object), and the metafile records\n * whichever spelling the source used. Matching by prefix alone misses the bare form entirely.\n */\nconst BUILTIN_MODULE_NAMES = new Set(builtinModules);\n\nconst isBuiltinSpecifier = (specifier: string): boolean => {\n const bareName = specifier.startsWith('node:') ? specifier.slice('node:'.length) : specifier;\n\n return BUILTIN_MODULE_NAMES.has(bareName);\n};\n\n/**\n * Measured against Bun 1.3.14: `--target=browser` never fails on a `node:` import and never leaves\n * the specifier in the bundled text. An unpolyfillable builtin (`fs`, `child_process`, ...) is\n * stubbed to an empty object; a polyfillable one (`crypto`, `path`, ...) is inlined in full under a\n * `/bun-vfs$$/` virtual path. Either way `exitCode` stays 0 and the specifier never survives into\n * stdout. The `--metafile` module graph is the only place it is preserved.\n */\nconst findBuiltinSpecifiers = (metafile: IMetafile): string[] => {\n const builtins = new Set<string>();\n\n const metafileInputsEntries = Object.entries(metafile.inputs);\n\n for (const [inputPath, input] of metafileInputsEntries) {\n if (isBuiltinSpecifier(inputPath)) {\n builtins.add(inputPath);\n }\n\n for (const dependency of input.imports) {\n const specifier = dependency.original ?? dependency.path;\n\n if (isBuiltinSpecifier(specifier)) {\n builtins.add(specifier);\n }\n }\n }\n\n return [...builtins].sort();\n};\n\n/**\n * A real npm dependency bundles in full under this target (measured: `zod` produces zero\n * `external` entries) and a genuinely missing package fails the build outright (nonzero exit,\n * caught before this runs). But a package's own `browser` field can remap a dependency to `false` -\n * the standard convention for disabling a Node-only dependency in browser builds - and Bun honours\n * that remap by leaving the import external with exit 0, whether or not the remapped name is a\n * builtin. An unresolved import in a browser bundle is not safe to wave through either way -\n * UNLESS the manifest entry asked for exactly this specifier via `external`, in which case its\n * presence here is the requested exclusion working, not a leak.\n */\n/**\n * A relative specifier is the package's own file, and a truly unreachable one fails the build with a\n * nonzero exit, which is caught before this runs. Bun's METAFILE nonetheless marks a re-export of the\n * form `export { name } from './x.js'` as `external` while inlining it - measured on\n * `helpers/dist/esm/core.js`: six such specifiers reported external, `Bundled 192 modules`, and the\n * output contains `class BaseHelper` with no bare relative import left in it. Reading the metafile\n * literally there reports a leak the bundle does not have.\n */\nconst isRelativeSpecifier = (specifier: string): boolean => {\n return specifier.startsWith('./') || specifier.startsWith('../');\n};\n\nconst findUnresolvedExternalSpecifiers = (opts: {\n metafile: IMetafile;\n builtins: Set<string>;\n requestedExternal: Set<string>;\n}): string[] => {\n const { metafile, builtins, requestedExternal } = opts;\n const unresolved = new Set<string>();\n\n const isRequestedExternal = (specifier: string): boolean => {\n for (const requested of requestedExternal) {\n if (specifier === requested || specifier.startsWith(`${requested}/`)) {\n return true;\n }\n }\n\n return false;\n };\n\n const metafileInputsValues = Object.values(metafile.inputs);\n\n for (const input of metafileInputsValues) {\n for (const dependency of input.imports) {\n if (!dependency.external) {\n continue;\n }\n\n const specifier = dependency.original ?? dependency.path;\n\n if (\n isRelativeSpecifier(specifier) ||\n builtins.has(specifier) ||\n isRequestedExternal(specifier)\n ) {\n continue;\n }\n\n unresolved.add(specifier);\n }\n }\n\n return [...unresolved].sort();\n};\n\n/** Whether `value` carries what the probe reads: every input with its imports, each with a path. */\nconst isMetafile = (value: unknown): value is IMetafile => {\n const read = (node: unknown, key: string): unknown =>\n typeof node === 'object' && node !== null ? Reflect.get(node, key) : undefined;\n const inputs = read(value, 'inputs');\n\n return (\n typeof inputs === 'object' &&\n inputs !== null &&\n Object.values(inputs).every((input) => {\n const imports = read(input, 'imports');\n\n return Array.isArray(imports) && imports.every((it) => typeof read(it, 'path') === 'string');\n })\n );\n};\n\n/**\n * Reads and removes the metafile unconditionally. Returns `undefined` rather than throwing -\n * `PurityProbe.probeEntry` reports on every entry it is given rather than aborting the run of the other five.\n */\nconst readMetafile = async (path: string): Promise<IMetafile | undefined> => {\n try {\n const result = await Bun.file(path).text();\n\n const metafile: unknown = JSON.parse(result);\n\n if (!isMetafile(metafile)) {\n CliOutput.error(`[purity] The build metafile at ${path} names no inputs with their imports`);\n\n return undefined;\n }\n\n return metafile;\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n CliOutput.error(`[purity] Failed to read the build metafile at ${path}: ${reason}`);\n\n return undefined;\n } finally {\n await rm(path, { force: true });\n }\n};\n\n/** Bundles a built entry for the browser with `bun build` and reports the Node builtins and Node globals that reach the bundle. */\nexport class PurityProbe {\n /**\n * Public so `probe.test.ts` can assert against the literal collision string directly, without\n * spawning `bun build` - a fixture whose OWN entry-path comment happens to reproduce the collision\n * is not something a filename choice can be relied on to keep reproducing.\n */\n static stripBundlerPathComments(opts: { text: string }): string {\n return opts.text.replace(BUNDLER_PATH_COMMENT, '');\n }\n\n /**\n * The CLI, not `Bun.build()`: the in-process bundler resolves this workspace's symlinked\n * dependencies to directories and dies on them.\n */\n static async probeEntry(opts: {\n entry: string;\n cwd: string;\n external?: string[];\n /** @default join(cwd, PURITY_SCRATCH_DIR) */\n scratchDir?: string;\n }): Promise<IPurityResult> {\n const { entry, cwd, external = [], scratchDir = join(cwd, PURITY_SCRATCH_DIR) } = opts;\n await mkdir(scratchDir, { recursive: true });\n const metafilePath = join(scratchDir, `purity-${crypto.randomUUID()}.json`);\n\n // `--env=disable`: Bun inlines `process.env.NODE_ENV` as a compile-time string constant by\n // default, regardless of whether the read is reachable. That erases the very read this probe\n // exists to catch, and the erasure depends on the ambient `NODE_ENV` the probe happens to run\n // under - the same failure shape as the undetected leak this gate was built to prevent.\n const externalArgs = external.flatMap((specifier) => ['--external', specifier]);\n const proc = Bun.spawn(\n [\n 'bun',\n 'build',\n entry,\n '--target=browser',\n '--format=esm',\n '--env=disable',\n `--metafile=${metafilePath}`,\n ...externalArgs,\n ],\n { cwd, stdout: 'pipe', stderr: 'pipe' },\n );\n\n const [stdout, stderr, exitCode] = await Promise.all([\n new Response(proc.stdout).text(),\n new Response(proc.stderr).text(),\n proc.exited,\n ]);\n\n if (exitCode !== 0) {\n await rm(metafilePath, { force: true });\n\n return {\n entry,\n ok: false,\n sizeBytes: 0,\n builtins: [],\n globals: [],\n guardedGlobals: [],\n external,\n buildError: stderr.trim(),\n };\n }\n\n const metafile = await readMetafile(metafilePath);\n\n if (!metafile) {\n return {\n entry,\n ok: false,\n sizeBytes: stdout.length,\n builtins: [],\n globals: [],\n guardedGlobals: [],\n external,\n buildError: 'Could not read the bun build metafile - the probe result is not trustworthy',\n };\n }\n\n const builtins = findBuiltinSpecifiers(metafile);\n const reachesDevConfigs = Object.keys(metafile.inputs).some((inputPath) =>\n DEV_CONFIGS_PATH.test(inputPath),\n );\n const unresolvedExternals = findUnresolvedExternalSpecifiers({\n metafile,\n builtins: new Set(builtins),\n requestedExternal: new Set(external),\n });\n const scannableText = PurityProbe.stripBundlerPathComments({ text: stdout });\n const matched = GLOBAL_PATTERNS.filter((g) => g.pattern.test(scannableText));\n const globals = matched.filter((g) => g.severity === ProbeSeverities.ERROR).map((g) => g.name);\n const guardedGlobals = matched\n .filter((g) => g.severity === ProbeSeverities.GUARDED)\n .map((g) => g.name);\n\n if (builtins.length > 0 || unresolvedExternals.length > 0 || reachesDevConfigs) {\n const reasons: string[] = [];\n\n if (reachesDevConfigs) {\n reasons.push(\n 'reaches @venizia/dev-configs, which is Bun-only tooling and never a browser dependency',\n );\n }\n\n if (builtins.length > 0) {\n reasons.push(`node builtin import(s): ${builtins.join(', ')}`);\n }\n\n if (unresolvedExternals.length > 0) {\n reasons.push(`unresolved external import(s): ${unresolvedExternals.join(', ')}`);\n }\n\n return {\n entry,\n ok: false,\n sizeBytes: stdout.length,\n builtins,\n globals,\n guardedGlobals,\n external,\n buildError: reasons.join(' | '),\n };\n }\n\n return {\n entry,\n ok: globals.length === 0,\n sizeBytes: stdout.length,\n builtins,\n globals,\n guardedGlobals,\n external,\n };\n }\n}\n"]}
|
|
@@ -10,6 +10,7 @@ exports.SplitReport = void 0;
|
|
|
10
10
|
const node_fs_1 = require("node:fs");
|
|
11
11
|
const node_path_1 = require("node:path");
|
|
12
12
|
const module_cycles_1 = require("./module-cycles");
|
|
13
|
+
const cli_output_1 = require("../common/cli-output");
|
|
13
14
|
const SKIP = new Set(['node_modules', 'dist', '__tests__', 'generated', '.turbo']);
|
|
14
15
|
const SOFT_LINE_MARK = 500;
|
|
15
16
|
const HUB_EXPORT_MARK = 10;
|
|
@@ -20,7 +21,7 @@ const EXPORTED_CLASS = /^export\s+(?:abstract\s+)?class\s+(\w+)/gm;
|
|
|
20
21
|
class SplitReport {
|
|
21
22
|
/** `distDir` is the built ESM folder inside a package (`dist/esm`, or `dist` where one build is published); `print` takes the report line by line. */
|
|
22
23
|
static run(opts) {
|
|
23
|
-
const { distDir = 'dist', print =
|
|
24
|
+
const { distDir = 'dist', print = cli_output_1.CliOutput.log } = opts;
|
|
24
25
|
const src = (0, node_path_1.join)(opts.packageDir, 'src');
|
|
25
26
|
if (!(0, node_fs_1.existsSync)(src)) {
|
|
26
27
|
return;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"split-report.js","sourceRoot":"","sources":["../../src/checks/split-report.ts"],"names":[],"mappings":";;;AAAA;;;;;GAKG;AACH,qCAA0E;AAC1E,yCAA8D;AAC9D,mDAA8C;AAE9C,MAAM,IAAI,GAAG,IAAI,GAAG,CAAC,CAAC,cAAc,EAAE,MAAM,EAAE,WAAW,EAAE,WAAW,EAAE,QAAQ,CAAC,CAAC,CAAC;AACnF,MAAM,cAAc,GAAG,GAAG,CAAC;AAC3B,MAAM,eAAe,GAAG,EAAE,CAAC;AAC3B,MAAM,oBAAoB,GAAG,CAAC,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,EAAE,KAAK,CAAC,CAAC;A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9D,CAAC;QAED,OAAO,GAAG,CAAC;IACb,CAAC;CACF;AA5ID,kCA4IC","sourcesContent":["/**\n * Informational report behind the file-splitting convention (conventions/file-splitting.md):\n * hub candidates, stray types files, scope folders without a barrel, files over the soft mark,\n * and import cycles per package. Never a gate. Usage: devz check split-report [--dist <dir>] [packages/kernel]\n * - with no argument, scans every packages/* and examples/* directory that has a src/.\n */\nimport { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';\nimport { basename, join, relative, resolve } from 'node:path';\nimport { ModuleGraph } from './module-cycles';\n\nconst SKIP = new Set(['node_modules', 'dist', '__tests__', 'generated', '.turbo']);\nconst SOFT_LINE_MARK = 500;\nconst HUB_EXPORT_MARK = 10;\nconst DECLARATION_KEYWORDS = ['class', 'const', 'type', 'interface', 'function', 'enum', 'let'];\nconst DECLARATION = new RegExp(\n `^export\\\\s+(?:default\\\\s+)?(?:abstract\\\\s+)?(${DECLARATION_KEYWORDS.join('|')})\\\\s+(\\\\w+)`,\n 'gm',\n);\nconst EXPORTED_CLASS = /^export\\s+(?:abstract\\s+)?class\\s+(\\w+)/gm;\n\ninterface IFileFacts {\n file: string;\n lines: number;\n exports: number;\n classes: string[];\n}\n\n/** The `devz check split-report` command: prints the file-splitting report for one package, or every package that has a `src/` folder. */\nexport class SplitReport {\n /** `distDir` is the built ESM folder inside a package (`dist/esm`, or `dist` where one build is published); `print` takes the report line by line. */\n static run(opts: { packageDir: string; distDir?: string; print?: (line: string) => void }): void {\n const { distDir = 'dist', print = console.log } = opts;\n const src = join(opts.packageDir, 'src');\n\n if (!existsSync(src)) {\n return;\n }\n\n const facts = SplitReport.walk({ dir: src }).map((file) => SplitReport.facts({ file }));\n const rel = (file: string) => relative(opts.packageDir, file);\n\n const hubs = facts.filter(\n (f) => ['types.ts', 'constants.ts'].includes(basename(f.file)) && f.exports > HUB_EXPORT_MARK,\n );\n const multiClass = facts.filter(\n (f) => f.classes.length >= 2 && !SplitReport.isAbstractBasePair({ facts: f }),\n );\n const strayTypes = facts.filter(\n (f) =>\n ['types.ts', 'constants.ts'].includes(basename(f.file)) && !f.file.includes('/common/'),\n );\n const long = facts.filter((f) => f.lines > SOFT_LINE_MARK);\n const noBarrel = SplitReport.foldersWithoutIndex({ dir: src });\n const esm = join(opts.packageDir, distDir);\n const cycles = existsSync(esm) ? ModuleGraph.fromDirectory({ dir: esm }).cycles().length : -1;\n\n print(`\\n## ${basename(opts.packageDir)} - ${facts.length} files`);\n const hubTitle = `hub candidates (> ${HUB_EXPORT_MARK} exports)`;\n const hubRows = hubs.map((f) => `${rel(f.file)} (${f.exports})`);\n SplitReport.section({ title: hubTitle, rows: hubRows, print });\n const classTitle = 'files with 2+ exported classes';\n const classRows = multiClass.map((f) => `${rel(f.file)} (${f.classes.join(', ')})`);\n SplitReport.section({ title: classTitle, rows: classRows, print });\n const strayTitle = 'types/constants outside common/';\n const strayRows = strayTypes.map((f) => rel(f.file));\n SplitReport.section({ title: strayTitle, rows: strayRows, print });\n const barrelTitle = 'scope folders without index.ts';\n const barrelRows = noBarrel.map((d) => relative(opts.packageDir, d));\n SplitReport.section({ title: barrelTitle, rows: barrelRows, print });\n const longTitle = `over ${SOFT_LINE_MARK} lines (a prompt to explain, not a defect)`;\n const longRows = long.map((f) => `${rel(f.file)} (${f.lines})`);\n SplitReport.section({ title: longTitle, rows: longRows, print });\n const cycleMsg = cycles < 0 ? 'no dist' : cycles;\n print(`- import cycles in ${distDir}: ${cycleMsg}`);\n }\n\n /** Every packages/* and examples/* directory that has a src/ folder. */\n static defaultTargets(opts: { root?: string } = {}): string[] {\n const root = opts.root ?? process.cwd();\n const withSource = (folder: string): string[] =>\n existsSync(resolve(root, folder))\n ? readdirSync(resolve(root, folder))\n .map((name) => resolve(root, folder, name))\n .filter((dir) => existsSync(join(dir, 'src')))\n : [];\n\n return [...withSource('packages'), ...withSource('examples')];\n }\n\n private static section(opts: {\n title: string;\n rows: string[];\n print: (line: string) => void;\n }): void {\n opts.print(`- ${opts.title}: ${opts.rows.length}`);\n\n for (const row of opts.rows) {\n opts.print(` ${row}`);\n }\n }\n\n private static facts(opts: { file: string }): IFileFacts {\n const text = readFileSync(opts.file, 'utf8');\n\n return {\n file: opts.file,\n lines: text.split('\\n').length,\n exports: [...text.matchAll(DECLARATION)].length,\n classes: [...text.matchAll(EXPORTED_CLASS)].map((match) => match[1]),\n };\n }\n\n /** abstract.ts + base.ts pairs are the format; exactly one of each is one concept. */\n private static isAbstractBasePair(opts: { facts: IFileFacts }): boolean {\n const [first, second] = opts.facts.classes;\n\n return opts.facts.classes.length === 2 && /Abstract/.test(first) && /Base/.test(second);\n }\n\n private static walk(opts: { dir: string }): string[] {\n const out: string[] = [];\n const dirEntries = readdirSync(opts.dir);\n\n for (const name of dirEntries) {\n if (SKIP.has(name)) {\n continue;\n }\n\n const full = join(opts.dir, name);\n\n if (statSync(full).isDirectory()) {\n out.push(...SplitReport.walk({ dir: full }));\n } else if (full.endsWith('.ts') && !full.endsWith('.d.ts')) {\n out.push(full);\n }\n }\n\n return out;\n }\n\n private static foldersWithoutIndex(opts: { dir: string }): string[] {\n const out: string[] = [];\n const dirEntries = readdirSync(opts.dir);\n\n for (const name of dirEntries) {\n if (SKIP.has(name)) {\n continue;\n }\n\n const full = join(opts.dir, name);\n\n if (!statSync(full).isDirectory()) {\n continue;\n }\n\n const hasTs = readdirSync(full).some(\n (entry) => entry.endsWith('.ts') && entry !== 'index.ts',\n );\n\n if (hasTs && !existsSync(join(full, 'index.ts'))) {\n out.push(full);\n }\n\n out.push(...SplitReport.foldersWithoutIndex({ dir: full }));\n }\n\n return out;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"split-report.js","sourceRoot":"","sources":["../../src/checks/split-report.ts"],"names":[],"mappings":";;;AAAA;;;;;GAKG;AACH,qCAA0E;AAC1E,yCAA8D;AAC9D,mDAA8C;AAC9C,qDAAiD;AAEjD,MAAM,IAAI,GAAG,IAAI,GAAG,CAAC,CAAC,cAAc,EAAE,MAAM,EAAE,WAAW,E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EAAC,IAAA,gBAAI,EAAC,IAAI,EAAE,UAAU,CAAC,CAAC,EAAE,CAAC;gBACjD,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;YACjB,CAAC;YAED,GAAG,CAAC,IAAI,CAAC,GAAG,WAAW,CAAC,mBAAmB,CAAC,EAAE,GAAG,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;QAC9D,CAAC;QAED,OAAO,GAAG,CAAC;IACb,CAAC;CACF;AA5ID,kCA4IC","sourcesContent":["/**\n * Informational report behind the file-splitting convention (conventions/file-splitting.md):\n * hub candidates, stray types files, scope folders without a barrel, files over the soft mark,\n * and import cycles per package. Never a gate. Usage: devz check split-report [--dist <dir>] [packages/kernel]\n * - with no argument, scans every packages/* and examples/* directory that has a src/.\n */\nimport { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';\nimport { basename, join, relative, resolve } from 'node:path';\nimport { ModuleGraph } from './module-cycles';\nimport { CliOutput } from '../common/cli-output';\n\nconst SKIP = new Set(['node_modules', 'dist', '__tests__', 'generated', '.turbo']);\nconst SOFT_LINE_MARK = 500;\nconst HUB_EXPORT_MARK = 10;\nconst DECLARATION_KEYWORDS = ['class', 'const', 'type', 'interface', 'function', 'enum', 'let'];\nconst DECLARATION = new RegExp(\n `^export\\\\s+(?:default\\\\s+)?(?:abstract\\\\s+)?(${DECLARATION_KEYWORDS.join('|')})\\\\s+(\\\\w+)`,\n 'gm',\n);\nconst EXPORTED_CLASS = /^export\\s+(?:abstract\\s+)?class\\s+(\\w+)/gm;\n\ninterface IFileFacts {\n file: string;\n lines: number;\n exports: number;\n classes: string[];\n}\n\n/** The `devz check split-report` command: prints the file-splitting report for one package, or every package that has a `src/` folder. */\nexport class SplitReport {\n /** `distDir` is the built ESM folder inside a package (`dist/esm`, or `dist` where one build is published); `print` takes the report line by line. */\n static run(opts: { packageDir: string; distDir?: string; print?: (line: string) => void }): void {\n const { distDir = 'dist', print = CliOutput.log } = opts;\n const src = join(opts.packageDir, 'src');\n\n if (!existsSync(src)) {\n return;\n }\n\n const facts = SplitReport.walk({ dir: src }).map((file) => SplitReport.facts({ file }));\n const rel = (file: string) => relative(opts.packageDir, file);\n\n const hubs = facts.filter(\n (f) => ['types.ts', 'constants.ts'].includes(basename(f.file)) && f.exports > HUB_EXPORT_MARK,\n );\n const multiClass = facts.filter(\n (f) => f.classes.length >= 2 && !SplitReport.isAbstractBasePair({ facts: f }),\n );\n const strayTypes = facts.filter(\n (f) =>\n ['types.ts', 'constants.ts'].includes(basename(f.file)) && !f.file.includes('/common/'),\n );\n const long = facts.filter((f) => f.lines > SOFT_LINE_MARK);\n const noBarrel = SplitReport.foldersWithoutIndex({ dir: src });\n const esm = join(opts.packageDir, distDir);\n const cycles = existsSync(esm) ? ModuleGraph.fromDirectory({ dir: esm }).cycles().length : -1;\n\n print(`\\n## ${basename(opts.packageDir)} - ${facts.length} files`);\n const hubTitle = `hub candidates (> ${HUB_EXPORT_MARK} exports)`;\n const hubRows = hubs.map((f) => `${rel(f.file)} (${f.exports})`);\n SplitReport.section({ title: hubTitle, rows: hubRows, print });\n const classTitle = 'files with 2+ exported classes';\n const classRows = multiClass.map((f) => `${rel(f.file)} (${f.classes.join(', ')})`);\n SplitReport.section({ title: classTitle, rows: classRows, print });\n const strayTitle = 'types/constants outside common/';\n const strayRows = strayTypes.map((f) => rel(f.file));\n SplitReport.section({ title: strayTitle, rows: strayRows, print });\n const barrelTitle = 'scope folders without index.ts';\n const barrelRows = noBarrel.map((d) => relative(opts.packageDir, d));\n SplitReport.section({ title: barrelTitle, rows: barrelRows, print });\n const longTitle = `over ${SOFT_LINE_MARK} lines (a prompt to explain, not a defect)`;\n const longRows = long.map((f) => `${rel(f.file)} (${f.lines})`);\n SplitReport.section({ title: longTitle, rows: longRows, print });\n const cycleMsg = cycles < 0 ? 'no dist' : cycles;\n print(`- import cycles in ${distDir}: ${cycleMsg}`);\n }\n\n /** Every packages/* and examples/* directory that has a src/ folder. */\n static defaultTargets(opts: { root?: string } = {}): string[] {\n const root = opts.root ?? process.cwd();\n const withSource = (folder: string): string[] =>\n existsSync(resolve(root, folder))\n ? readdirSync(resolve(root, folder))\n .map((name) => resolve(root, folder, name))\n .filter((dir) => existsSync(join(dir, 'src')))\n : [];\n\n return [...withSource('packages'), ...withSource('examples')];\n }\n\n private static section(opts: {\n title: string;\n rows: string[];\n print: (line: string) => void;\n }): void {\n opts.print(`- ${opts.title}: ${opts.rows.length}`);\n\n for (const row of opts.rows) {\n opts.print(` ${row}`);\n }\n }\n\n private static facts(opts: { file: string }): IFileFacts {\n const text = readFileSync(opts.file, 'utf8');\n\n return {\n file: opts.file,\n lines: text.split('\\n').length,\n exports: [...text.matchAll(DECLARATION)].length,\n classes: [...text.matchAll(EXPORTED_CLASS)].map((match) => match[1]),\n };\n }\n\n /** abstract.ts + base.ts pairs are the format; exactly one of each is one concept. */\n private static isAbstractBasePair(opts: { facts: IFileFacts }): boolean {\n const [first, second] = opts.facts.classes;\n\n return opts.facts.classes.length === 2 && /Abstract/.test(first) && /Base/.test(second);\n }\n\n private static walk(opts: { dir: string }): string[] {\n const out: string[] = [];\n const dirEntries = readdirSync(opts.dir);\n\n for (const name of dirEntries) {\n if (SKIP.has(name)) {\n continue;\n }\n\n const full = join(opts.dir, name);\n\n if (statSync(full).isDirectory()) {\n out.push(...SplitReport.walk({ dir: full }));\n } else if (full.endsWith('.ts') && !full.endsWith('.d.ts')) {\n out.push(full);\n }\n }\n\n return out;\n }\n\n private static foldersWithoutIndex(opts: { dir: string }): string[] {\n const out: string[] = [];\n const dirEntries = readdirSync(opts.dir);\n\n for (const name of dirEntries) {\n if (SKIP.has(name)) {\n continue;\n }\n\n const full = join(opts.dir, name);\n\n if (!statSync(full).isDirectory()) {\n continue;\n }\n\n const hasTs = readdirSync(full).some(\n (entry) => entry.endsWith('.ts') && entry !== 'index.ts',\n );\n\n if (hasTs && !existsSync(join(full, 'index.ts'))) {\n out.push(full);\n }\n\n out.push(...SplitReport.foldersWithoutIndex({ dir: full }));\n }\n\n return out;\n }\n}\n"]}
|
|
@@ -1,3 +1,11 @@
|
|
|
1
|
+
import type { TConstValue } from '../linters/rules/common';
|
|
2
|
+
/** What a registry entry's `file` is: a test file, or a negative fixture a test needs absent from the result. */
|
|
3
|
+
export declare class ControlEntryTypes {
|
|
4
|
+
static readonly TEST = "test";
|
|
5
|
+
static readonly FILE = "file";
|
|
6
|
+
}
|
|
7
|
+
/** One of `ControlEntryTypes`. */
|
|
8
|
+
export type TControlEntryType = TConstValue<typeof ControlEntryTypes>;
|
|
1
9
|
/**
|
|
2
10
|
* A positive control is a test that proves a gate can fail: a fixture that must be refused, a broken
|
|
3
11
|
* subject the check must catch. Deleting one makes the gate pass for the wrong reason, so the trim-tests
|
|
@@ -16,7 +24,7 @@ export interface IControlEntry {
|
|
|
16
24
|
*
|
|
17
25
|
* @default 'test'
|
|
18
26
|
*/
|
|
19
|
-
|
|
27
|
+
type?: TControlEntryType;
|
|
20
28
|
/** A regular expression matched against the TITLES (suite and case) in that file. Not used by `file` entries. */
|
|
21
29
|
titlePattern?: string;
|
|
22
30
|
/**
|
|
@@ -1,8 +1,14 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.TestControlsCheck = void 0;
|
|
3
|
+
exports.TestControlsCheck = exports.ControlEntryTypes = void 0;
|
|
4
4
|
const node_fs_1 = require("node:fs");
|
|
5
5
|
const node_path_1 = require("node:path");
|
|
6
|
+
/** What a registry entry's `file` is: a test file, or a negative fixture a test needs absent from the result. */
|
|
7
|
+
class ControlEntryTypes {
|
|
8
|
+
static { this.TEST = 'test'; }
|
|
9
|
+
static { this.FILE = 'file'; }
|
|
10
|
+
}
|
|
11
|
+
exports.ControlEntryTypes = ControlEntryTypes;
|
|
6
12
|
/** Verifies that every positive control in the registry still exists: its file is present and, for a test entry, enough test titles match its pattern. */
|
|
7
13
|
class TestControlsCheck {
|
|
8
14
|
/**
|
|
@@ -53,11 +59,11 @@ class TestControlsCheck {
|
|
|
53
59
|
if (!(0, node_fs_1.existsSync)(path)) {
|
|
54
60
|
problems.push({
|
|
55
61
|
entry,
|
|
56
|
-
message: `the ${entry.
|
|
62
|
+
message: `the ${entry.type === ControlEntryTypes.FILE ? 'negative fixture' : 'test file'} ${entry.file} does not exist`,
|
|
57
63
|
});
|
|
58
64
|
continue;
|
|
59
65
|
}
|
|
60
|
-
if (entry.
|
|
66
|
+
if (entry.type === ControlEntryTypes.FILE) {
|
|
61
67
|
continue;
|
|
62
68
|
}
|
|
63
69
|
const titles = await TestControlsCheck.listTitles({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"test-controls.js","sourceRoot":"","sources":["../../src/checks/test-controls.ts"],"names":[],"mappings":";;;AAAA,qCAAmD;AACnD,yCAAiC;
|
|
1
|
+
{"version":3,"file":"test-controls.js","sourceRoot":"","sources":["../../src/checks/test-controls.ts"],"names":[],"mappings":";;;AAAA,qCAAmD;AACnD,yCAAiC;AAKjC,iHAAiH;AACjH,MAAa,iBAAiB;aACZ,SAAI,GAAG,MAAM,CAAC;aACd,SAAI,GAAG,MAAM,CAAC;;AAFhC,8CAGC;AA8CD,0JAA0J;AAC1J,MAAa,iBAAiB;IAC5B;;;;;OAKG;IACH,MAAM,CAAC,KAAK,CAAC,UAAU,CAAC,IAA2C;QACjE,MAAM,MAAM,GAAG,MAAM,MAAM,CAAC,YAAY,CAAC,CAAC;QAC1C,MAAM,UAAU,GAAc,MAAM,CAAC,OAAO,CAAC;QAC7C,MAAM,IAAI,GAAG,UAAU,CAAC,gBAAgB,CACtC,IAAI,CAAC,QAAQ,IAAI,cAAc,EAC/B,IAAI,CAAC,MAAM,EACX,UAAU,CAAC,YAAY,CAAC,MAAM,EAC9B,IAAI,CACL,CAAC;QACF,MAAM,MAAM,GAAa,EAAE,CAAC;QAC5B,MAAM,OAAO,GAAG,IAAI,GAAG,CAAC,CAAC,MAAM,EAAE,IAAI,EAAE,UAAU,CAA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AAG,oCAAoC,KAAK,CAAC,IAAI,sBAAsB;iBAC9J,CAAC,CAAC;YACL,CAAC;QACH,CAAC;QAED,OAAO,EAAE,OAAO,EAAE,IAAI,CAAC,QAAQ,CAAC,MAAM,EAAE,QAAQ,EAAE,CAAC;IACrD,CAAC;CACF;AA/FD,8CA+FC","sourcesContent":["import { existsSync, readFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type ts from 'typescript';\n\nimport type { TConstValue } from '../linters/rules/common';\n\n/** What a registry entry's `file` is: a test file, or a negative fixture a test needs absent from the result. */\nexport class ControlEntryTypes {\n static readonly TEST = 'test';\n static readonly FILE = 'file';\n}\n\n/** One of `ControlEntryTypes`. */\nexport type TControlEntryType = TConstValue<typeof ControlEntryTypes>;\n\n/**\n * A positive control is a test that proves a gate can fail: a fixture that must be refused, a broken\n * subject the check must catch. Deleting one makes the gate pass for the wrong reason, so the trim-tests\n * method keeps a committed registry of them and fails when one disappears.\n */\nexport interface IControlEntry {\n /** The gate the control belongs to; reported with a failure. */\n gate: string;\n /** Repository-relative path of the test file. */\n file: string;\n /**\n * `test`: `file` is a test file and `titlePattern` is matched against its titles.\n * `file`: `file` is a NEGATIVE FIXTURE, a file a test needs to be absent from the result (a class the\n * scanner must ignore). It only has to exist: without it the test's \"not found\" assertion passes for the\n * wrong reason.\n *\n * @default 'test'\n */\n type?: TControlEntryType;\n /** A regular expression matched against the TITLES (suite and case) in that file. Not used by `file` entries. */\n titlePattern?: string;\n /**\n * At least this many titles must match.\n *\n * @default 1\n */\n min?: number;\n}\n\n/** One registry entry that failed its check, with the reason. */\nexport interface IControlProblem {\n entry: IControlEntry;\n message: string;\n}\n\n/** Result of `TestControlsCheck.run`: how many registry entries were checked and which failed. */\nexport interface IControlsReport {\n checked: number;\n problems: IControlProblem[];\n}\n\n/** Verifies that every positive control in the registry still exists: its file is present and, for a test entry, enough test titles match its pattern. */\nexport class TestControlsCheck {\n /**\n * The titles in a test file: the first string argument of `test`, `it`, `describe` and of the\n * second call of `test.each(rows)('title', ...)`, with their `.only`/`.skip`/`.if(...)` forms.\n * A `test.each` title is returned as written (`%s` and all): the registry patterns are regular\n * expressions, so the expansion does not matter.\n */\n static async listTitles(opts: { source: string; fileName?: string }): Promise<string[]> {\n const result = await import('typescript');\n const typescript: typeof ts = result.default;\n const file = typescript.createSourceFile(\n opts.fileName ?? 'file.test.ts',\n opts.source,\n typescript.ScriptTarget.Latest,\n true,\n );\n const titles: string[] = [];\n const RUNNERS = new Set(['test', 'it', 'describe']);\n\n const rootName = (expression: ts.Expression): string | undefined => {\n if (typescript.isIdentifier(expression)) {\n return expression.text;\n }\n\n if (typescript.isPropertyAccessExpression(expression)) {\n return rootName(expression.expression);\n }\n\n if (typescript.isCallExpression(expression)) {\n return rootName(expression.expression);\n }\n\n return undefined;\n };\n\n const visit = (node: ts.Node): void => {\n if (typescript.isCallExpression(node)) {\n const first = node.arguments[0];\n const root = rootName(node.expression);\n\n if (\n root !== undefined &&\n RUNNERS.has(root) &&\n first &&\n (typescript.isStringLiteral(first) || typescript.isNoSubstitutionTemplateLiteral(first))\n ) {\n titles.push(first.text);\n }\n }\n\n typescript.forEachChild(node, visit);\n };\n\n visit(file);\n\n return titles;\n }\n\n /** Checks every entry of the registry against the test files it names. */\n static async run(opts: { root: string; controls: IControlEntry[] }): Promise<IControlsReport> {\n const problems: IControlProblem[] = [];\n\n for (const entry of opts.controls) {\n const path = join(opts.root, entry.file);\n\n if (!existsSync(path)) {\n problems.push({\n entry,\n message: `the ${entry.type === ControlEntryTypes.FILE ? 'negative fixture' : 'test file'} ${entry.file} does not exist`,\n });\n continue;\n }\n\n if (entry.type === ControlEntryTypes.FILE) {\n continue;\n }\n\n const titles = await TestControlsCheck.listTitles({\n source: readFileSync(path, 'utf8'),\n fileName: entry.file,\n });\n const pattern = new RegExp(entry.titlePattern ?? '');\n const matched = titles.filter((title) => pattern.test(title)).length;\n const min = entry.min ?? 1;\n\n if (matched < min) {\n problems.push({\n entry,\n message: `${matched} title(s) match /${entry.titlePattern ?? ''}/ in ${entry.file}, ${min} required | the control of gate '${entry.gate}' is gone or renamed`,\n });\n }\n }\n\n return { checked: opts.controls.length, problems };\n }\n}\n"]}
|
|
@@ -1,3 +1,11 @@
|
|
|
1
|
+
import type { TConstValue } from '../linters/rules/common';
|
|
2
|
+
/** Why a support file is a candidate for deletion. */
|
|
3
|
+
export declare class DeadTestCodeCandidateTypes {
|
|
4
|
+
static readonly UNREFERENCED = "unreferenced";
|
|
5
|
+
static readonly FOLDER_REFERENCED = "folder-referenced";
|
|
6
|
+
}
|
|
7
|
+
/** One of `DeadTestCodeCandidateTypes`. */
|
|
8
|
+
export type TDeadTestCodeCandidateType = TConstValue<typeof DeadTestCodeCandidateTypes>;
|
|
1
9
|
/**
|
|
2
10
|
* Support files of the tests (fixtures, helpers, probes) that no other file refers to. The second
|
|
3
11
|
* step of the trim-tests method. The output is CANDIDATES: a fixture can be loaded by a path built at
|
|
@@ -10,7 +18,7 @@ export interface IDeadTestCodeCandidate {
|
|
|
10
18
|
* `unreferenced`: neither its name nor its path under `__tests__` appears in another file, nor does
|
|
11
19
|
* its folder. `folder-referenced`: only its folder path does, so a scan of that folder may load it.
|
|
12
20
|
*/
|
|
13
|
-
|
|
21
|
+
type: TDeadTestCodeCandidateType;
|
|
14
22
|
}
|
|
15
23
|
/** Finds support files under `__tests__` (fixtures, helpers) that no tracked file refers to, using `git grep` in the given repository. */
|
|
16
24
|
export declare class DeadTestCodeCheck {
|