@evobug_com/safe-ts-transform 0.3.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @evobug_com/safe-ts-transform
2
2
 
3
- SAFE-TS build-time transform: a Vite/Rolldown/Rollup plugin and a Node loader that rewrite q(), match(), parseJson<T>(), loops and @inline, and run the SAFE-TS checks.
3
+ SAFE-TS build-time transform: a Vite/Rolldown/Rollup plugin, a Node loader and a Bun plugin that rewrite q(), match(), parseJson<T>(), loops and @inline, and run the SAFE-TS checks.
4
4
 
5
5
  **Documentation: [safe-ts.evobug-pages.com/guide/adoption](https://safe-ts.evobug-pages.com/guide/adoption)**
6
6
 
@@ -8,6 +8,11 @@ SAFE-TS build-time transform: a Vite/Rolldown/Rollup plugin and a Node loader th
8
8
  npm install -D @evobug_com/safe-ts-transform
9
9
  ```
10
10
 
11
+ The checker's settings go in the `"safe-ts"` field of package.json: each rule's level, per rule
12
+ and per directory ([rule levels](https://safe-ts.evobug-pages.com/guide/adoption#rule-levels-errors-warnings-off)), and the
13
+ opt-in [idiomatic rules](https://safe-ts.evobug-pages.com/guide/adoption#idiomatic-rules) (`"idiomatic": true`). One line that is
14
+ right as it is takes `// safe-ts-ignore <rule>: <reason>` ([ignoring one finding](https://safe-ts.evobug-pages.com/guide/adoption#ignoring-one-finding)).
15
+
11
16
  Part of [SAFE-TS](https://safe-ts.evobug-pages.com/), a strict, Rust-flavoured subset of TypeScript. The website has the
12
17
  guides, a page per rule, and a playground that runs the checker in your browser.
13
18
 
package/bun-plugin.mjs ADDED
@@ -0,0 +1,136 @@
1
+ // The safe-ts transform as a Bun plugin: the same rewrite the Node loader (register.mjs) and the
2
+ // Vite plugin make, for Bun's runtime (`bun run`, `bun test`, through the `./bun` preload) and
3
+ // for its bundler (`Bun.build({ plugins: [safeTsBun()] })`).
4
+ //
5
+ // Bun has no `module.registerHooks`, so the Node loader can't run there; `Bun.plugin` is its
6
+ // equivalent. The shared validator modules (`<declaring file>?safe-ts-json=<key>`) are served
7
+ // from a namespace of their own, and the Node loader's disk cache (cache.mjs) is used as is.
8
+ import { readFileSync } from "node:fs";
9
+ import { createRequire } from "node:module";
10
+ import { dirname, resolve } from "node:path";
11
+ import { pathToFileURL } from "node:url";
12
+
13
+ import { openCache } from "./cache.mjs";
14
+ import { devChecksEnabled, SHARED_QUERY, sharedModule, sharedModuleId, transformWithDependencies } from "./index.mjs";
15
+
16
+ const require = createRequire(import.meta.url);
17
+
18
+ /** The files the transform takes, outside node_modules (Bun's own loader keeps those). */
19
+ const TS_FILE = /^(?!.*[\\/]node_modules[\\/]).*\.(ts|tsx|mts|cts)$/;
20
+ // index.mjs re-exports this module, so its imports may not be initialised yet at the top level.
21
+ const SHARED_IMPORT = /\?safe-ts-json=/;
22
+ const NAMESPACE = "safe-ts-json";
23
+
24
+ /**
25
+ * The directory imports of `importer` resolve from. Bun names an importer in another namespace
26
+ * with that prefix (`safe-ts-json:/src/types.ts?safe-ts-json=v$User`).
27
+ */
28
+ function importerDir(importer) {
29
+ const path = importer.startsWith(`${NAMESPACE}:`) ? importer.slice(NAMESPACE.length + 1) : importer;
30
+ return dirname(path.split("?")[0]);
31
+ }
32
+
33
+ /**
34
+ * Bun plugin: rewrites q(), match(), parseJson<T>(), validate<T>(), loops and prelude names in
35
+ * project TypeScript, for `Bun.plugin(...)` (the runtime) and `Bun.build({ plugins })` (the
36
+ * bundler). Options default to what fits where it runs: at runtime as the Node loader does
37
+ * (dev checks unless NODE_ENV=production, no rule checks), in `Bun.build` as `vite build` does.
38
+ *
39
+ * @param {{ check?: "warn" | "error" | false, devChecks?: boolean, sharedValidators?: boolean }} [options]
40
+ * check: run the safe-ts rules on every transformed file. "warn" prints problems, "error"
41
+ * fails the load (the build, or the import at runtime); false turns it off. Default: "warn"
42
+ * in `Bun.build`, false at runtime.
43
+ * devChecks: insert dev-only runtime checks. Default: off in `Bun.build`; at runtime, on
44
+ * unless NODE_ENV=production, and SAFE_TS_DEV_CHECKS=1 / =0 overrides it.
45
+ * sharedValidators: one validator module per named type (default), or a copy per file
46
+ * (false; at runtime also SAFE_TS_SHARED_VALIDATORS=0).
47
+ */
48
+ export function safeTsBun(options = {}) {
49
+ return {
50
+ name: "safe-ts",
51
+ setup(build) {
52
+ // `Bun.build` passes its config; `Bun.plugin` (the runtime) doesn't.
53
+ const bundling = build.config !== undefined;
54
+ const env = process.env;
55
+ const check = options.check ?? (bundling ? "warn" : false);
56
+ const devChecks = options.devChecks ?? (bundling ? false : devChecksEnabled(env));
57
+ const sharedValidators =
58
+ options.sharedValidators ?? (bundling || !["0", "false"].includes(env.SAFE_TS_SHARED_VALIDATORS ?? ""));
59
+ const cache = openCache(env, { devChecks, sharedValidators });
60
+ const root = process.cwd();
61
+ let checker;
62
+ // The files the runtime transformed, for the Vite plugin's config check (index.mjs), as
63
+ // the Node loader records them.
64
+ const loaded = bundling ? undefined : (globalThis[Symbol.for("safe-ts.loader.files")] ??= new Set());
65
+ const warned = new Set();
66
+ const warn = (message) => {
67
+ if (warned.has(message)) return;
68
+ warned.add(message);
69
+ process.stderr.write(`safe-ts warning: ${message}\n`);
70
+ };
71
+
72
+ // `./types.ts?safe-ts-json=v$User` from a transformed file (or from another shared
73
+ // module): the declaring file, with the key, in a namespace of its own.
74
+ for (const namespace of ["file", NAMESPACE]) {
75
+ build.onResolve({ filter: SHARED_IMPORT, namespace }, (args) => {
76
+ const shared = sharedModuleId(args.path);
77
+ const from = importerDir(args.importer);
78
+ return { path: `${resolve(from, shared.file)}?${SHARED_QUERY}=${shared.key}`, namespace: NAMESPACE };
79
+ });
80
+ }
81
+ // A bare import in a shared module (the std helpers) resolves from the declaring file, or
82
+ // else from the current directory: a package of types may not depend on the std library.
83
+ build.onResolve({ filter: /^[^./]/, namespace: NAMESPACE }, (args) => {
84
+ const from = importerDir(args.importer);
85
+ try {
86
+ return { path: Bun.resolveSync(args.path, from) };
87
+ } catch {
88
+ return { path: Bun.resolveSync(args.path, root) };
89
+ }
90
+ });
91
+ // Relative imports in a shared module (types it imports for its own checks).
92
+ build.onResolve({ filter: /^\.\.?\//, namespace: NAMESPACE }, (args) => ({
93
+ path: Bun.resolveSync(args.path, importerDir(args.importer)),
94
+ }));
95
+
96
+ build.onLoad({ filter: /./, namespace: NAMESPACE }, (args) => {
97
+ const shared = sharedModuleId(args.path);
98
+ // Keyed by URL, as the Node loader keys it: the cache's sweep reads the file from it.
99
+ const url = `${pathToFileURL(shared.file).href}?${SHARED_QUERY}=${shared.key}`;
100
+ let contents = cache?.get(url, shared.key);
101
+ if (contents === undefined) {
102
+ const module = sharedModule(shared.file, shared.key);
103
+ contents = module.code;
104
+ cache?.set(url, shared.key, module);
105
+ }
106
+ return { contents, loader: "ts" };
107
+ });
108
+
109
+ build.onLoad({ filter: TS_FILE }, (args) => {
110
+ const file = args.path;
111
+ const code = readFileSync(file, "utf8");
112
+ const loader = file.endsWith(".tsx") ? "tsx" : "ts";
113
+ if (check !== false) {
114
+ checker ??= new (require("@evobug_com/safe-ts-native").Checker)(root);
115
+ const problems = checker.checkFile(file, code);
116
+ if (problems.length > 0) {
117
+ const lines = problems.map((d) => ` ${file}:${d.line}:${d.column + 1} safe-ts(${d.rule}): ${d.message}`);
118
+ const message = `safe-ts: ${problems.length} problem(s)\n${lines.join("\n")}`;
119
+ if (check === "error") throw new Error(message);
120
+ process.stderr.write(`${message}\n`);
121
+ }
122
+ }
123
+ let contents = cache?.get(file, code);
124
+ if (contents === undefined) {
125
+ const result = transformWithDependencies(file, code, { devChecks, sharedValidators });
126
+ contents = result.code;
127
+ // A file with a warning isn't cached, so the warning shows on every run until it's fixed.
128
+ if (result.warnings.length === 0) cache?.set(file, code, result);
129
+ for (const warning of result.warnings) warn(warning);
130
+ }
131
+ loaded?.add(file);
132
+ return { contents, loader };
133
+ });
134
+ },
135
+ };
136
+ }
package/bun.mjs ADDED
@@ -0,0 +1,19 @@
1
+ // Run TypeScript with `q(...)` support directly in Bun: the Bun counterpart of `./register`.
2
+ // Preload it, in bunfig.toml (both lines: `bun test` reads only its own section):
3
+ // preload = ["@evobug_com/safe-ts-transform/bun"]
4
+ // [test]
5
+ // preload = ["@evobug_com/safe-ts-transform/bun"]
6
+ // or on the command line: bun --preload @evobug_com/safe-ts-transform/bun src/main.ts
7
+ // Dev checks, the cache and shared validators follow the same variables as the Node loader:
8
+ // SAFE_TS_DEV_CHECKS, NODE_ENV=production, SAFE_TS_CACHE, SAFE_TS_CACHE_DIR,
9
+ // SAFE_TS_SHARED_VALIDATORS. For `Bun.build`, pass `safeTsBun()` from the package instead.
10
+ import { safeTsBun } from "./bun-plugin.mjs";
11
+
12
+ if (typeof globalThis.Bun?.plugin !== "function") {
13
+ throw new Error(
14
+ "safe-ts: @evobug_com/safe-ts-transform/bun is the preload for Bun. In Node, use " +
15
+ "`node --import @evobug_com/safe-ts-transform/register`: https://safe-ts.evobug-pages.com/guide/bun",
16
+ );
17
+ }
18
+
19
+ Bun.plugin(safeTsBun());
package/index.d.ts CHANGED
@@ -6,7 +6,9 @@
6
6
  export type SafeTsOptions = {
7
7
  /**
8
8
  * Run the safe-ts rules on every transformed file. "warn" (default) prints problems in the
9
- * terminal; "error" shows Vite's error overlay and fails the build; false turns it off.
9
+ * terminal; "error" shows Vite's error overlay and fails the build when a finding is an
10
+ * error (rules at "warn", in package.json's `"safe-ts": { "rules" }` or the oxlint preset,
11
+ * are only printed); false turns it off.
10
12
  */
11
13
  check?: "warn" | "error" | false;
12
14
  /**
@@ -24,8 +26,20 @@ export type SafeTsOptions = {
24
26
  * its own that every file using it imports, instead of a copy per file. On by default.
25
27
  */
26
28
  sharedValidators?: boolean;
29
+ /**
30
+ * Files the plugin leaves alone: not checked, not transformed. Globs relative to Vite's root
31
+ * (`"src/vendor/**"`, `"**\/*.generated.ts"`), regular expressions tested on the absolute path
32
+ * (with `/` on every OS), or a function of the absolute path; one or a list. An excluded file
33
+ * must not need the transform (`q`, `match`, `parseJson`, prelude names). For code not
34
+ * migrated yet, use the `// @safe-ts legacy` marker instead: it turns the rules off and keeps
35
+ * the rewrites the file needs to run.
36
+ */
37
+ exclude?: SafeTsExclude | readonly SafeTsExclude[];
27
38
  };
28
39
 
40
+ /** One `exclude` entry: a glob, a regular expression, or a test of the absolute path. */
41
+ export type SafeTsExclude = string | RegExp | ((file: string) => boolean);
42
+
29
43
  /** A source map, as the plugin returns it. */
30
44
  export type SafeTsSourceMap = {
31
45
  version: number;
@@ -42,9 +56,10 @@ export interface SafeTsPlugin {
42
56
  enforce: "pre";
43
57
  configResolved(config: {
44
58
  readonly root: string;
59
+ readonly resolve?: { readonly alias?: unknown };
45
60
  readonly command: "build" | "serve";
46
61
  readonly configFile?: string | undefined;
47
- readonly logger: { warn(message: string): void };
62
+ readonly logger: { warn(message: string): void; info(message: string): void };
48
63
  }): void;
49
64
  resolveId(
50
65
  this: { resolve(source: string, importer?: string, options?: { skipSelf?: boolean }): Promise<{ id: string } | null> },
@@ -62,6 +77,9 @@ export interface SafeTsPlugin {
62
77
  code: string,
63
78
  id: string,
64
79
  ): { code: string; map: SafeTsSourceMap } | null;
80
+ buildStart(): void;
81
+ /** At the end of `vite build`: `safe-ts: 1,293 files checked, 960 legacy, 0 problems`. */
82
+ buildEnd(this: { info?(message: string): void } | void): void;
65
83
  renderChunk(code: string, chunk: { readonly isEntry: boolean; readonly name: string }): { code: string; map: SafeTsSourceMap } | null;
66
84
  generateBundle(options: unknown, bundle: { [fileName: string]: object }): void;
67
85
  }
@@ -69,23 +87,81 @@ export interface SafeTsPlugin {
69
87
  /** Bundler plugin (Vite, Rolldown, Rollup): rewrites q(), match(), parseJson<T>() and more. */
70
88
  export function safeTs(options?: SafeTsOptions): SafeTsPlugin;
71
89
 
90
+ export type SafeTsBunOptions = {
91
+ /**
92
+ * Run the safe-ts rules on every transformed file. "warn" prints problems; "error" fails the
93
+ * load (the build, or the import at runtime); false turns it off. Default: "warn" in
94
+ * `Bun.build`, false at runtime (`Bun.plugin`), as with the Node loader.
95
+ */
96
+ check?: "warn" | "error" | false;
97
+ /**
98
+ * Insert dev-only runtime checks. Default: off in `Bun.build`; at runtime on unless
99
+ * `NODE_ENV=production`, and `SAFE_TS_DEV_CHECKS=1` / `=0` overrides that.
100
+ */
101
+ devChecks?: boolean;
102
+ /** One validator module per named type (default), or a copy per file (false). */
103
+ sharedValidators?: boolean;
104
+ };
105
+
106
+ /** What the Bun plugin reads of Bun's `PluginBuilder` (typed by its shape, without bun-types). */
107
+ export interface SafeTsBunBuilder {
108
+ readonly config?: object;
109
+ onResolve(
110
+ constraints: { filter: RegExp; namespace?: string },
111
+ callback: (args: { path: string; importer: string }) => { path: string; namespace?: string },
112
+ ): unknown;
113
+ onLoad(
114
+ constraints: { filter: RegExp; namespace?: string },
115
+ callback: (args: { path: string }) => { contents: string; loader: "ts" | "tsx" },
116
+ ): unknown;
117
+ }
118
+
119
+ /** The Bun plugin: assignable to Bun's `BunPlugin`. */
120
+ export interface SafeTsBunPlugin {
121
+ name: "safe-ts";
122
+ setup(build: SafeTsBunBuilder): void;
123
+ }
124
+
125
+ /**
126
+ * Bun plugin: the same rewrite as `safeTs()` and the Node loader, for `Bun.build({ plugins:
127
+ * [safeTsBun()] })` and `Bun.plugin(safeTsBun())`. For `bun run` and `bun test`, preload
128
+ * `@evobug_com/safe-ts-transform/bun` instead, which registers it.
129
+ */
130
+ export function safeTsBun(options?: SafeTsBunOptions): SafeTsBunPlugin;
131
+
72
132
  /** Rewrite one file. Throws with all errors if the file can't be transformed. */
73
133
  export function transform(filename: string, code: string, options?: { devChecks?: boolean }): string;
74
134
 
135
+ /**
136
+ * A bundler alias with a string `find` (Vite's `resolve.alias`): `find` and anything below it
137
+ * (`find/x`) resolve to `replacement`, an absolute path. Tried before tsconfig.json `paths`.
138
+ */
139
+ export type SafeTsAlias = { find: string; replacement: string };
140
+
75
141
  /**
76
142
  * `transform`, also returning the other files the result depends on (imported types, `@inline`
77
- * functions, enum tables, the tsconfig that turns the prelude on).
143
+ * functions, enum tables, the tsconfig that turns the prelude on). Imports resolve through
144
+ * tsconfig.json `paths`, and `aliases` first.
78
145
  */
79
146
  export function transformWithDependencies(
80
147
  filename: string,
81
148
  code: string,
82
- options?: { devChecks?: boolean; sharedValidators?: boolean },
83
- ): { code: string; dependencies: string[]; warnings: string[] };
149
+ options?: { devChecks?: boolean; sharedValidators?: boolean; aliases?: readonly SafeTsAlias[] },
150
+ ): { code: string; dependencies: string[]; warnings: string[]; legacy: boolean };
151
+
152
+ /**
153
+ * The aliases of a resolved Vite config (`config.resolve.alias`) the checker can use: string
154
+ * `find`, absolute `replacement`. Regular expressions are left out.
155
+ */
156
+ export function stringAliases(alias: unknown): SafeTsAlias[];
157
+
158
+ /** Is `file` library code: under a `node_modules` directory below `root`? */
159
+ export function isLibraryFile(file: string, root: string): boolean;
84
160
 
85
161
  /**
86
162
  * Import a module with the safe-ts transform from code that wasn't transformed (a Vite config:
87
- * Vite loads it without plugins). Registers the Node loader's hooks in this process, then
88
- * imports `url` through them; returns the module's exports.
163
+ * Vite loads it without plugins). Registers the Node loader's hooks in this process (in Bun, the
164
+ * Bun plugin), then imports `url` through them; returns the module's exports.
89
165
  *
90
166
  * ```ts
91
167
  * const { offlinePage } = await loadTransformed<typeof import("./scripts/plugins.ts")>(
@@ -105,7 +181,7 @@ export const SHARED_QUERY: "safe-ts-json";
105
181
  export function sharedModuleId(id: string): { file: string; key: string } | undefined;
106
182
 
107
183
  /** The shared module `key` of types declared in `file`, and the files it was built from. */
108
- export function sharedModule(file: string, key: string): { code: string; dependencies: string[] };
184
+ export function sharedModule(file: string, key: string, aliases?: readonly SafeTsAlias[]): { code: string; dependencies: string[] };
109
185
 
110
186
  /**
111
187
  * Whether the Node loader inserts dev checks: yes unless `NODE_ENV=production`;
@@ -119,6 +195,15 @@ export function devChecksEnabled(env: Record<string, string | undefined>): boole
119
195
  */
120
196
  export function configFileWarning(configFile: string | undefined): string | undefined;
121
197
 
198
+ /** The line `vite build` ends with: `safe-ts: 1,293 files checked, 960 legacy, 0 problems`. */
199
+ export function summaryLine(
200
+ stats: { files: number; legacy: number; excluded: number; problems: number },
201
+ checked: boolean,
202
+ ): string;
203
+
204
+ /** The `exclude` option as a test of an absolute file path and Vite's root. */
205
+ export function excludeFilter(exclude: SafeTsExclude | readonly SafeTsExclude[] | undefined): (file: string, root: string) => boolean;
206
+
122
207
  /** Source map for a line-preserving rewrite (every generated line maps to its original line). */
123
208
  export function lineMap(
124
209
  file: string,
package/index.mjs CHANGED
@@ -2,7 +2,7 @@
2
2
  // and q(...) early returns. Every rewrite keeps the original line structure.
3
3
  import { readFileSync } from "node:fs";
4
4
  import { createRequire } from "node:module";
5
- import { dirname, isAbsolute, join, resolve } from "node:path";
5
+ import { dirname, isAbsolute, join, relative, resolve } from "node:path";
6
6
  import { pathToFileURL } from "node:url";
7
7
 
8
8
  import MagicString from "magic-string";
@@ -10,6 +10,8 @@ import MagicString from "magic-string";
10
10
  const require = createRequire(import.meta.url);
11
11
  const native = require("@evobug_com/safe-ts-native");
12
12
 
13
+ export { safeTsBun } from "./bun-plugin.mjs";
14
+
13
15
  const TS_FILE = /\.(ts|mts|cts|tsx)$/;
14
16
  const VUE_FILE = /\.vue$/;
15
17
 
@@ -27,17 +29,20 @@ export function transform(filename, code, options = {}) {
27
29
  * `transform`, also returning the other files the result depends on (types, `@inline`
28
30
  * functions and enum tables read from imports, the tsconfig that turns the prelude on): a
29
31
  * cached result stays valid while none of them changes. Used by the Node loader's cache.
32
+ * Imports resolve through tsconfig.json `paths`; `aliases` adds a bundler's own
33
+ * (`[{ find: "@", replacement: "/abs/src" }]`), as the Vite plugin does with `resolve.alias`.
30
34
  */
31
35
  export function transformWithDependencies(filename, code, options = {}) {
32
36
  const result = native.transform(filename, code, {
33
37
  devChecks: options.devChecks === true,
34
38
  sharedValidators: options.sharedValidators === true,
39
+ ...(options.aliases?.length ? { aliases: options.aliases } : {}),
35
40
  });
36
41
  if (result.errors.length > 0) {
37
42
  const lines = result.errors.map((e) => ` ${filename}:${e.line}:${e.column + 1} ${e.rule}: ${e.message}`);
38
43
  throw new Error(`safe-ts transform failed:\n${lines.join("\n")}`);
39
44
  }
40
- return { code: result.code, dependencies: result.dependencies ?? [], warnings: result.warnings ?? [] };
45
+ return { code: result.code, dependencies: result.dependencies ?? [], warnings: result.warnings ?? [], legacy: result.legacy === true };
41
46
  }
42
47
 
43
48
  /**
@@ -46,10 +51,11 @@ export function transformWithDependencies(filename, code, options = {}) {
46
51
  * Node loader's hooks in this process (as `--import @evobug_com/safe-ts-transform/register`
47
52
  * does), then imports the module through them, so it and everything it imports are transformed.
48
53
  * Returns the module's namespace: its exports, functions included. A module Node already loaded
49
- * without the hooks stays as it was: load it only this way.
54
+ * without the hooks stays as it was: load it only this way. In Bun (`bunx --bun vite`), the same
55
+ * with the Bun plugin (bun.mjs) in place of the hooks.
50
56
  */
51
57
  export async function loadTransformed(url) {
52
- await import("./register.mjs");
58
+ await import(process.versions.bun === undefined ? "./register.mjs" : "./bun.mjs");
53
59
  const href = url instanceof URL ? url.href : isAbsolute(String(url)) ? pathToFileURL(String(url)).href : String(url);
54
60
  return import(href);
55
61
  }
@@ -75,12 +81,36 @@ export function sharedModuleId(id) {
75
81
  * was built from (`file` included): it stays valid while none of them changes. Throws if `file`
76
82
  * no longer declares the type.
77
83
  */
78
- export function sharedModule(file, key) {
79
- const result = native.sharedModule(file, key);
84
+ export function sharedModule(file, key, aliases) {
85
+ const result = aliases?.length ? native.sharedModule(file, key, aliases) : native.sharedModule(file, key);
80
86
  if (result.code == null) throw new Error(`safe-ts: shared validators ${file}?${SHARED_QUERY}=${key}: ${result.error}`);
81
87
  return { code: result.code, dependencies: result.dependencies };
82
88
  }
83
89
 
90
+ /**
91
+ * The aliases of a resolved Vite config (`config.resolve.alias`) that the checker can use: a
92
+ * string `find` and an absolute `replacement`. A `find` that is a regular expression can't be
93
+ * handed over: write that alias in tsconfig.json `paths` too.
94
+ */
95
+ export function stringAliases(alias) {
96
+ const entries = Array.isArray(alias)
97
+ ? alias
98
+ : Object.entries(alias ?? {}).map(([find, replacement]) => ({ find, replacement }));
99
+ return entries
100
+ .filter((a) => typeof a?.find === "string" && typeof a.replacement === "string" && isAbsolute(a.replacement))
101
+ .map((a) => ({ find: a.find, replacement: a.replacement }));
102
+ }
103
+
104
+ /**
105
+ * Is `file` library code: under a `node_modules` directory below `root`? A project that itself
106
+ * lives under some `node_modules` is still a project. (The checker decides the same way.)
107
+ */
108
+ export function isLibraryFile(file, root) {
109
+ const below = relative(root, file);
110
+ const inside = below !== "" && !below.startsWith("..") && !isAbsolute(below);
111
+ return (inside ? below : file).split(/[\\/]/).includes("node_modules");
112
+ }
113
+
84
114
  /**
85
115
  * Whether the Node loader (`register.mjs`) inserts dev checks: yes unless
86
116
  * `NODE_ENV=production`; `SAFE_TS_DEV_CHECKS=1` / `=0` (or `true` / `false`) overrides that.
@@ -116,7 +146,9 @@ export function lineMap(file, original, transformed) {
116
146
  * @param {{ check?: "warn" | "error" | false, compileHints?: boolean | string[], devChecks?: boolean }} [options]
117
147
  * check: run the safe-ts rules on every transformed file (the same checks as the editor).
118
148
  * "warn" (default) prints problems in the terminal; "error" shows Vite's error overlay in
119
- * the browser and fails the build; false turns it off.
149
+ * the browser and fails the build when a finding is an error (a rule at "warn" in
150
+ * package.json's `"safe-ts": { "rules" }`, or in the oxlint preset, is only printed); false
151
+ * turns it off.
120
152
  * compileHints: add `//# allFunctionsCalledOnLoad` to entry chunks (`true`) or to the chunks
121
153
  * with these names, so Chrome 136+ compiles their functions eagerly, in the background,
122
154
  * instead of on first call (https://v8.dev/blog/explicit-compile-hints). It costs memory and
@@ -128,20 +160,38 @@ export function lineMap(file, original, transformed) {
128
160
  * sharedValidators: generate the validator (and test-data generator) of each named type once,
129
161
  * in a module of its own that every file using it imports, instead of a copy per file. On by
130
162
  * default; false gives every file its own copies, as before.
163
+ * exclude: files the plugin leaves alone, neither checked nor transformed: globs relative to
164
+ * Vite's root (`"src/vendor/**"`), regular expressions tested on the absolute path, or a
165
+ * function of the absolute path; one or a list. An excluded file must not need the transform
166
+ * (`q`, `match`, `parseJson`, prelude names). For code that isn't migrated yet, the
167
+ * `// @safe-ts legacy` marker is usually what you want: such a file is not reported on, and
168
+ * gets only the rewrites it needs to run.
169
+ *
170
+ * `vite build` ends with one line: `safe-ts: 1,293 files checked, 960 legacy, 0 problems`.
131
171
  */
132
172
  export function safeTs(options = {}) {
133
173
  const check = options.check ?? "warn";
174
+ const excluded = excludeFilter(options.exclude);
134
175
  const hints = options.compileHints ?? false;
135
176
  const wantsHint = (chunk) => (hints === true ? chunk.isEntry : Array.isArray(hints) && hints.includes(chunk.name));
136
177
  let devChecks = options.devChecks ?? false;
137
178
  const sharedValidators = options.sharedValidators ?? true;
138
179
  let root = process.cwd();
139
180
  let checker;
181
+ let logger;
182
+ let command;
183
+ // For the line at the end of a build.
184
+ let stats = { files: 0, legacy: 0, excluded: 0, problems: 0 };
185
+ let aliases = [];
186
+ const unresolvedWarned = new Set();
140
187
  return {
141
188
  name: "safe-ts",
142
189
  enforce: "pre",
143
190
  configResolved(config) {
144
191
  root = config.root;
192
+ logger = config.logger;
193
+ command = config.command;
194
+ aliases = stringAliases(config.resolve?.alias);
145
195
  devChecks = options.devChecks ?? config.command === "serve";
146
196
  const warning = configFileWarning(config.configFile);
147
197
  if (warning !== undefined) config.logger.warn(warning);
@@ -163,7 +213,7 @@ export function safeTs(options = {}) {
163
213
  load(id) {
164
214
  const shared = sharedModuleId(id);
165
215
  if (shared === undefined) return null;
166
- const module = sharedModule(shared.file, shared.key);
216
+ const module = sharedModule(shared.file, shared.key, aliases);
167
217
  // The dev server invalidates the module when the declaring file changes; these cover the
168
218
  // rest (types it extends or picks from elsewhere).
169
219
  if (typeof this?.addWatchFile === "function") for (const file of module.dependencies) this.addWatchFile(file);
@@ -174,27 +224,59 @@ export function safeTs(options = {}) {
174
224
  const [file, query] = id.split("?");
175
225
  // `App.vue?vue&type=script...`: parts @vitejs/plugin-vue serves from the SFC it got from us.
176
226
  const wanted = VUE_FILE.test(file) ? query === undefined : TS_FILE.test(file);
177
- if (!wanted || file.includes("/node_modules/")) return null;
178
- if (check) {
179
- checker ??= new native.Checker(root);
227
+ if (!wanted || isLibraryFile(file, root)) return null;
228
+ if (excluded(file, root)) {
229
+ stats.excluded++;
230
+ return null;
231
+ }
232
+ stats.files++;
233
+ if (check !== false) {
234
+ checker ??= new native.Checker(root, { aliases });
180
235
  const problems = checker.checkFile(file, code);
236
+ stats.problems += problems.length;
237
+ // Once per import and file: the checker can't follow these, so it misses what they do.
238
+ for (const specifier of checker.unresolvedImports?.(file, code) ?? []) {
239
+ const key = `${file}\0${specifier}`;
240
+ if (unresolvedWarned.has(key)) continue;
241
+ unresolvedWarned.add(key);
242
+ this.warn(`safe-ts: could not resolve "${specifier}" from ${relative(root, file).replaceAll("\\", "/")}`);
243
+ }
181
244
  if (problems.length > 0) {
182
- const lines = problems.map((d) => ` ${file}:${d.line}:${d.column + 1} safe-ts(${d.rule}): ${d.message}`);
183
- const message = `safe-ts: ${problems.length} problem(s)\n${lines.join("\n")}`;
184
- if (check === "error") {
185
- this.error({ message, id: file, loc: { line: problems[0].line, column: problems[0].column } });
245
+ // A rule's level comes from package.json (`"safe-ts": { "rules": ... }`), else the
246
+ // oxlint preset's: with check "error", only errors stop the build.
247
+ const errors = problems.filter((d) => d.severity !== "warning");
248
+ const label = (d) => (d.severity === "warning" ? " warning" : "");
249
+ const lines = problems.map((d) => ` ${file}:${d.line}:${d.column + 1} safe-ts(${d.rule})${label(d)}: ${d.message}`);
250
+ const counts = [[errors.length, "error"], [problems.length - errors.length, "warning"]]
251
+ .filter(([n]) => n > 0)
252
+ .map(([n, word]) => `${n} ${word}${n === 1 ? "" : "s"}`);
253
+ const message = `safe-ts: ${counts.join(", ")}\n${lines.join("\n")}`;
254
+ if (check === "error" && errors.length > 0) {
255
+ this.error({ message, id: file, loc: { line: errors[0].line, column: errors[0].column } });
186
256
  } else {
187
257
  this.warn(message);
188
258
  }
189
259
  }
190
260
  }
191
- const { code: out, dependencies, warnings } = transformWithDependencies(file, code, { devChecks, sharedValidators });
261
+ const { code: out, dependencies, warnings, legacy } = transformWithDependencies(file, code, { devChecks, sharedValidators, aliases });
262
+ if (legacy) stats.legacy++;
192
263
  for (const warning of warnings) this.warn(`safe-ts: ${warning}`);
193
264
  // Generated validators follow the types they were made from, wherever those are declared.
194
265
  // (Not when a wrapper plugin calls this hook without a context.)
195
266
  if (typeof this?.addWatchFile === "function") for (const dependency of dependencies) this.addWatchFile(dependency);
196
267
  return out === code ? null : { code: out, map: lineMap(file, code, out) };
197
268
  },
269
+ buildStart() {
270
+ stats = { files: 0, legacy: 0, excluded: 0, problems: 0 };
271
+ },
272
+ // One line, so a build log shows the plugin ran and what it saw. Not on the dev server,
273
+ // which transforms files as the browser asks for them: there is no point where all are done.
274
+ buildEnd() {
275
+ if (command === "serve" || (stats.files === 0 && stats.excluded === 0)) return;
276
+ const line = summaryLine(stats, check !== false);
277
+ if (logger !== undefined) logger.info(line);
278
+ else if (typeof this?.info === "function") this.info(line);
279
+ },
198
280
  renderChunk(code, chunk) {
199
281
  if (!wantsHint(chunk)) return null;
200
282
  const s = new MagicString(code);
@@ -221,6 +303,66 @@ export function safeTs(options = {}) {
221
303
 
222
304
  const COMPILE_HINT = "//# allFunctionsCalledOnLoad";
223
305
 
306
+ /** `safe-ts: 1,293 files checked, 960 legacy, 0 problems` (`transformed`, without the count, when `check` is off). */
307
+ export function summaryLine(stats, checked) {
308
+ const n = (count) => count.toLocaleString("en-US");
309
+ const files = `${n(stats.files)} file${stats.files === 1 ? "" : "s"}`;
310
+ const parts = checked
311
+ ? [`${files} checked`, `${n(stats.legacy)} legacy`, `${n(stats.problems)} problem${stats.problems === 1 ? "" : "s"}`]
312
+ : [`${files} transformed (check: false)`, `${n(stats.legacy)} legacy`];
313
+ if (stats.excluded > 0) parts.push(`${n(stats.excluded)} excluded`);
314
+ return `safe-ts: ${parts.join(", ")}`;
315
+ }
316
+
317
+ /**
318
+ * The `exclude` option as a test of (absolute file, Vite root): globs match the path relative
319
+ * to the root (or the absolute path, for an absolute glob), regular expressions the absolute
320
+ * path, a function gets the absolute path. Paths use `/` on every OS.
321
+ */
322
+ export function excludeFilter(exclude) {
323
+ if (exclude === undefined || exclude === null) return () => false;
324
+ const list = Array.isArray(exclude) ? exclude : [exclude];
325
+ const tests = list.map((pattern) => {
326
+ if (typeof pattern === "function") return (file) => pattern(file) === true;
327
+ if (pattern instanceof RegExp) return (file) => { pattern.lastIndex = 0; return pattern.test(file); };
328
+ if (typeof pattern === "string") {
329
+ const glob = globRegExp(pattern.replaceAll("\\", "/"));
330
+ const absolute = isAbsolute(pattern) || /^[A-Za-z]:\//.test(pattern);
331
+ return (file, root) => glob.test(absolute ? file : relative(root, file).replaceAll("\\", "/"));
332
+ }
333
+ throw new TypeError(`safe-ts: exclude takes globs, regular expressions or a function, not ${typeof pattern}`);
334
+ });
335
+ return (file, root) => {
336
+ const path = file.replaceAll("\\", "/");
337
+ return tests.some((test) => test(path, root));
338
+ };
339
+ }
340
+
341
+ /** `**` any directories, `*` and `?` within one, `{a,b}` either; a leading `./` is dropped. */
342
+ function globRegExp(glob) {
343
+ let source = "";
344
+ let braces = 0;
345
+ const text = glob.replace(/^\.\//, "");
346
+ for (let i = 0; i < text.length; i++) {
347
+ const c = text[i];
348
+ if (c === "*" && text[i + 1] === "*") {
349
+ const slash = text[i + 2] === "/";
350
+ source += slash ? "(?:.*/)?" : ".*";
351
+ i += slash ? 2 : 1;
352
+ } else if (c === "*") source += "[^/]*";
353
+ else if (c === "?") source += "[^/]";
354
+ else if (c === "{") {
355
+ braces++;
356
+ source += "(?:";
357
+ } else if (c === "}" && braces > 0) {
358
+ braces--;
359
+ source += ")";
360
+ } else if (c === "," && braces > 0) source += "|";
361
+ else source += c.replace(/[.+^$()|[\]\\{}]/g, "\\$&");
362
+ }
363
+ return new RegExp(`^${source}$`);
364
+ }
365
+
224
366
  /** Set by the Node loader (`register.mjs`): the files it transformed in this process. */
225
367
  const LOADED = Symbol.for("safe-ts.loader.files");
226
368
 
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@evobug_com/safe-ts-transform",
3
- "version": "0.3.0",
4
- "description": "SAFE-TS build-time transform: a Vite/Rolldown/Rollup plugin and a Node loader that rewrite q(), match(), parseJson<T>(), loops and @inline, and run the SAFE-TS checks.",
3
+ "version": "0.5.1",
4
+ "description": "SAFE-TS build-time transform: a Vite/Rolldown/Rollup plugin, a Node loader and a Bun plugin that rewrite q(), match(), parseJson<T>(), loops and @inline, and run the SAFE-TS checks.",
5
5
  "keywords": [
6
6
  "safe-ts",
7
7
  "typescript",
@@ -10,6 +10,7 @@
10
10
  "rollup-plugin",
11
11
  "rolldown",
12
12
  "node-loader",
13
+ "bun-plugin",
13
14
  "transform",
14
15
  "result",
15
16
  "pattern-matching"
@@ -29,12 +30,15 @@
29
30
  "types": "./index.d.ts",
30
31
  "default": "./index.mjs"
31
32
  },
32
- "./register": "./register.mjs"
33
+ "./register": "./register.mjs",
34
+ "./bun": "./bun.mjs"
33
35
  },
34
36
  "files": [
35
37
  "index.mjs",
36
38
  "index.d.ts",
37
39
  "register.mjs",
40
+ "bun.mjs",
41
+ "bun-plugin.mjs",
38
42
  "cache.mjs",
39
43
  "LICENSE-MIT",
40
44
  "LICENSE-APACHE"
@@ -43,11 +47,11 @@
43
47
  "node": ">=22.18.0"
44
48
  },
45
49
  "dependencies": {
46
- "@evobug_com/safe-ts-native": "0.3.0",
50
+ "@evobug_com/safe-ts-native": "0.5.1",
47
51
  "magic-string": "^1.4.5"
48
52
  },
49
53
  "peerDependencies": {
50
- "@evobug_com/safe-ts-std": "^0.3.0",
54
+ "@evobug_com/safe-ts-std": "^0.5.1",
51
55
  "vite": "^6.0.0 || ^7.0.0 || ^8.0.0"
52
56
  },
53
57
  "peerDependenciesMeta": {
package/register.mjs CHANGED
@@ -8,13 +8,32 @@
8
8
  // The validators of named types are generated once, in shared modules every file using them
9
9
  // imports (`<declaring file>?safe-ts-json=<key>`, served here); SAFE_TS_SHARED_VALIDATORS=0
10
10
  // gives every file its own copies instead.
11
+ // Imports Node can't resolve are resolved as the checker resolves them: tsconfig.json `paths`
12
+ // and `baseUrl` (`@utils/x`), and extensions or `index` files left out.
13
+ // Bun has no `module.registerHooks`: there, preload `@evobug_com/safe-ts-transform/bun` (bun.mjs).
11
14
  import { readFileSync } from "node:fs";
12
- import { registerHooks } from "node:module";
15
+ // Not `import { registerHooks }`: where it's missing (Bun, Node before 22.15) that is a
16
+ // SyntaxError naming `registerHooks`, before any code here could say what to use instead.
17
+ import * as nodeModule from "node:module";
13
18
  import { join } from "node:path";
14
19
  import { fileURLToPath, pathToFileURL } from "node:url";
15
20
 
16
21
  import { openCache } from "./cache.mjs";
17
- import { devChecksEnabled, sharedModule, sharedModuleId, transformWithDependencies } from "./index.mjs";
22
+ import { devChecksEnabled, isLibraryFile, sharedModule, sharedModuleId, transformWithDependencies } from "./index.mjs";
23
+
24
+ const native = nodeModule.createRequire(import.meta.url)("@evobug_com/safe-ts-native");
25
+ const root = process.cwd();
26
+
27
+ const { registerHooks } = nodeModule;
28
+ if (typeof registerHooks !== "function") {
29
+ throw new Error(
30
+ process.versions.bun !== undefined
31
+ ? "safe-ts: @evobug_com/safe-ts-transform/register is the Node loader, and Bun has no `module.registerHooks`. " +
32
+ 'In Bun, preload the Bun plugin instead: `preload = ["@evobug_com/safe-ts-transform/bun"]` in bunfig.toml ' +
33
+ "(and under `[test]`), or `bun --preload @evobug_com/safe-ts-transform/bun`: https://safe-ts.evobug-pages.com/guide/bun"
34
+ : `safe-ts: the Node loader needs \`module.registerHooks\` (Node 22.15 or later); this is Node ${process.versions.node}.`,
35
+ );
36
+ }
18
37
 
19
38
  const TS_FILE = /\.(ts|mts)$/;
20
39
  const HAS_EXTENSION = /\.[cm]?[jt]sx?$/;
@@ -38,7 +57,18 @@ registerHooks({
38
57
  }
39
58
  // Extensionless relative imports, as with bundlers / `moduleResolution: "Bundler"`.
40
59
  if (error?.code === "ERR_MODULE_NOT_FOUND" && /^\.\.?\//.test(specifier) && !HAS_EXTENSION.test(specifier)) {
41
- return nextResolve(`${specifier}.ts`, context);
60
+ try {
61
+ return nextResolve(`${specifier}.ts`, context);
62
+ } catch {
63
+ // A directory's index file: the checker's resolution, below.
64
+ }
65
+ }
66
+ // tsconfig `paths` (`@utils/x`) and the rest of a bundler's resolution, as the checker
67
+ // follows them: a file runs with the imports `safe-ts check` saw.
68
+ const notFound = error?.code === "ERR_MODULE_NOT_FOUND" || error?.code === "ERR_UNSUPPORTED_DIR_IMPORT";
69
+ if (notFound && context.parentURL?.startsWith("file:") && typeof native.resolveModule === "function") {
70
+ const found = native.resolveModule(fileURLToPath(context.parentURL.split("?")[0]), specifier);
71
+ if (found != null) return nextResolve(pathToFileURL(found).href, context);
42
72
  }
43
73
  throw error;
44
74
  }
@@ -56,7 +86,7 @@ registerHooks({
56
86
  }
57
87
  return { format: "module-typescript", source, shortCircuit: true };
58
88
  }
59
- if (!url.startsWith("file:") || !TS_FILE.test(new URL(url).pathname) || url.includes("/node_modules/")) {
89
+ if (!url.startsWith("file:") || !TS_FILE.test(new URL(url).pathname) || isLibraryFile(fileURLToPath(url), root)) {
60
90
  return nextLoad(url, context);
61
91
  }
62
92
  const filename = fileURLToPath(url);