@evobug_com/safe-ts-transform 0.2.0 → 0.3.0

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/cache.mjs CHANGED
@@ -1,28 +1,41 @@
1
1
  // The Node loader's on-disk cache of transformed files (register.mjs), so a restart, a worker
2
2
  // thread or a test process doesn't transform the same file again.
3
3
  //
4
- // One entry per file and set of options: a later version of the file replaces it, so the cache
5
- // doesn't grow with edits. A shared validator module (`<file>?safe-ts-json=<key>`) is an entry
6
- // of its own, keyed by its URL; its "content" is the key, and its dependencies are the
7
- // declarations it was built from, the declaring file first. An entry is used only when the file's content, every file the
8
- // transform read for it (imported types, `@inline` functions, enum tables, the tsconfig), the
9
- // transform's version and the options all match. Entries are written to a temporary file and
10
- // renamed into place, so threads and processes writing at once never leave a partial entry.
4
+ // One directory per source file, one entry in it per set of options (dev checks, shared
5
+ // validators, the current directory) and transform version: a later version of the file
6
+ // replaces its entry, so the cache doesn't grow with edits. Writing an entry prunes the file's
7
+ // directory to its newest few entries (`KEEP`), so entries made by an older addon or with options
8
+ // no longer used go away; about once a day, a write also drops the directories of files that no
9
+ // longer exist. A shared validator module (`<file>?safe-ts-json=<key>`) is an entry of its own,
10
+ // keyed by its URL; its "content" is the key, and its dependencies are the declarations it was
11
+ // built from, the declaring file first. An entry is used only when the file's content, every
12
+ // file the transform read for it (imported types, `@inline` functions, enum tables, the
13
+ // tsconfig), the transform's version and the options all match. Entries are written to a
14
+ // temporary file and renamed into place, so threads and processes writing at once never leave a
15
+ // partial entry.
11
16
  //
12
17
  // Where: SAFE_TS_CACHE_DIR, else node_modules/.cache/safe-ts in the nearest directory above the
13
18
  // current one that has node_modules, else the system's temporary directory. SAFE_TS_CACHE=0 (or
14
- // false) turns it off. Problems with the cache never fail a load: the file is transformed.
19
+ // false) turns it off. Deleting the directory (`rm -rf node_modules/.cache/safe-ts`) is always
20
+ // safe. Problems with the cache never fail a load: the file is transformed.
15
21
  import { createRequire } from "node:module";
16
22
  import { hash, randomBytes } from "node:crypto";
17
- import { accessSync, constants, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
23
+ import { accessSync, constants, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, utimesSync, writeFileSync } from "node:fs";
18
24
  import { tmpdir } from "node:os";
19
25
  import { dirname, join } from "node:path";
26
+ import { fileURLToPath } from "node:url";
20
27
  import { threadId } from "node:worker_threads";
21
28
 
22
29
  const require = createRequire(import.meta.url);
23
30
 
24
31
  /** Bumped when the entry format changes. */
25
- const FORMAT = 1;
32
+ const FORMAT = 2;
33
+
34
+ /** Entries kept per source file: the newest, by when they were written. */
35
+ export const KEEP = 3;
36
+
37
+ /** How often a write also looks for entries of files that are gone. */
38
+ const SWEEP_EVERY_MS = 24 * 60 * 60 * 1000;
26
39
 
27
40
  const digest = (data) => hash("sha256", data, "hex");
28
41
 
@@ -87,7 +100,9 @@ export function openCache(env, options) {
87
100
  if (dir === undefined) return undefined;
88
101
  // Dev checks name files relative to the current directory: it is part of the key too.
89
102
  const version = JSON.stringify([FORMAT, transformVersion(), options.devChecks === true, options.sharedValidators === true, process.cwd()]);
90
- const entryPath = (filename) => join(dir, `${digest(`${version}\0${filename}`).slice(0, 40)}.json`);
103
+ const versionKey = digest(version).slice(0, 24);
104
+ const fileDir = (filename) => join(dir, digest(filename).slice(0, 32));
105
+ const entryPath = (filename) => join(fileDir(filename), `${versionKey}.json`);
91
106
  // Many files depend on the same few (the tsconfig, std modules): hash each version once.
92
107
  const dependencyDigests = new Map();
93
108
  const dependencyDigest = (file) => {
@@ -127,12 +142,97 @@ export function openCache(env, options) {
127
142
  const temporary = `${target}.${process.pid}.${threadId}.${randomBytes(4).toString("hex")}.tmp`;
128
143
  try {
129
144
  const dependencies = result.dependencies.map((file) => [file, dependencyDigest(file)]);
130
- writeFileSync(temporary, JSON.stringify({ format: FORMAT, source: digest(code), dependencies, code: result.code }));
145
+ mkdirSync(dirname(target), { recursive: true });
146
+ writeFileSync(temporary, JSON.stringify({ format: FORMAT, file: filename, source: digest(code), dependencies, code: result.code }));
131
147
  renameSync(temporary, target);
132
148
  } catch {
133
149
  // A dependency gone in between, a full disk, a read-only directory: just don't cache.
134
150
  rmSync(temporary, { force: true });
151
+ return;
135
152
  }
153
+ prune(target);
154
+ sweep(dir);
136
155
  },
137
156
  };
138
157
  }
158
+
159
+ /** Keep the newest `KEEP` entries of one file's directory: `written` and the newest others. */
160
+ function prune(written) {
161
+ const fileDir = dirname(written);
162
+ try {
163
+ const entries = readdirSync(fileDir).filter((name) => name.endsWith(".json") && join(fileDir, name) !== written);
164
+ if (entries.length < KEEP) return;
165
+ const dated = entries.map((name) => {
166
+ const path = join(fileDir, name);
167
+ try {
168
+ return { path, at: statSync(path).mtimeMs };
169
+ } catch {
170
+ return { path, at: 0 };
171
+ }
172
+ });
173
+ dated.sort((a, b) => b.at - a.at);
174
+ for (const { path } of dated.slice(KEEP - 1)) rmSync(path, { force: true });
175
+ } catch {
176
+ // Another process pruned it first.
177
+ }
178
+ }
179
+
180
+ /**
181
+ * About once a day: drop the directories of source files that no longer exist, and the flat
182
+ * entries of the first cache format. The marker file's time says when it last ran.
183
+ */
184
+ function sweep(dir) {
185
+ const marker = join(dir, "swept");
186
+ try {
187
+ if (Date.now() - statSync(marker).mtimeMs < SWEEP_EVERY_MS) return;
188
+ } catch {
189
+ // Never swept.
190
+ }
191
+ try {
192
+ writeFileSync(marker, "");
193
+ const now = new Date();
194
+ utimesSync(marker, now, now);
195
+ for (const name of readdirSync(dir)) {
196
+ const path = join(dir, name);
197
+ if (/^[0-9a-f]{40}\.json$/.test(name)) {
198
+ rmSync(path, { force: true });
199
+ continue;
200
+ }
201
+ if (!/^[0-9a-f]{32}$/.test(name)) continue;
202
+ const entries = readdirSync(path).filter((entry) => entry.endsWith(".json"));
203
+ const file = entries.length === 0 ? undefined : sourceOf(join(path, entries[0]));
204
+ if (file === undefined || !exists(sourcePath(file))) rmSync(path, { recursive: true, force: true });
205
+ }
206
+ } catch {
207
+ // Another process is sweeping, or the directory is read-only.
208
+ }
209
+ }
210
+
211
+ /** The source path an entry was made for. */
212
+ function sourceOf(entry) {
213
+ try {
214
+ const file = JSON.parse(readFileSync(entry, "utf8"))?.file;
215
+ return typeof file === "string" ? file : undefined;
216
+ } catch {
217
+ return undefined;
218
+ }
219
+ }
220
+
221
+ /** A path, or a shared module's URL (`file:///src/types.ts?safe-ts-json=...`): its file. */
222
+ function sourcePath(file) {
223
+ if (!file.startsWith("file:")) return file;
224
+ try {
225
+ return fileURLToPath(file.split("?")[0]);
226
+ } catch {
227
+ return file;
228
+ }
229
+ }
230
+
231
+ function exists(path) {
232
+ try {
233
+ statSync(path);
234
+ return true;
235
+ } catch {
236
+ return false;
237
+ }
238
+ }
package/index.d.ts CHANGED
@@ -80,7 +80,20 @@ export function transformWithDependencies(
80
80
  filename: string,
81
81
  code: string,
82
82
  options?: { devChecks?: boolean; sharedValidators?: boolean },
83
- ): { code: string; dependencies: string[] };
83
+ ): { code: string; dependencies: string[]; warnings: string[] };
84
+
85
+ /**
86
+ * 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.
89
+ *
90
+ * ```ts
91
+ * const { offlinePage } = await loadTransformed<typeof import("./scripts/plugins.ts")>(
92
+ * new URL("./scripts/plugins.ts", import.meta.url),
93
+ * );
94
+ * ```
95
+ */
96
+ export function loadTransformed<Module = Record<string, unknown>>(url: URL | string): Promise<Module>;
84
97
 
85
98
  /** The query parameter of a shared validator module: `/src/types.ts?safe-ts-json=v$User`. */
86
99
  export const SHARED_QUERY: "safe-ts-json";
package/index.mjs CHANGED
@@ -1,7 +1,9 @@
1
1
  // safe-ts build-time transform: prelude imports, parseJson<T> validators, match -> switch,
2
2
  // and q(...) early returns. Every rewrite keeps the original line structure.
3
+ import { readFileSync } from "node:fs";
3
4
  import { createRequire } from "node:module";
4
- import { dirname, join, resolve } from "node:path";
5
+ import { dirname, isAbsolute, join, resolve } from "node:path";
6
+ import { pathToFileURL } from "node:url";
5
7
 
6
8
  import MagicString from "magic-string";
7
9
 
@@ -35,7 +37,21 @@ export function transformWithDependencies(filename, code, options = {}) {
35
37
  const lines = result.errors.map((e) => ` ${filename}:${e.line}:${e.column + 1} ${e.rule}: ${e.message}`);
36
38
  throw new Error(`safe-ts transform failed:\n${lines.join("\n")}`);
37
39
  }
38
- return { code: result.code, dependencies: result.dependencies ?? [] };
40
+ return { code: result.code, dependencies: result.dependencies ?? [], warnings: result.warnings ?? [] };
41
+ }
42
+
43
+ /**
44
+ * Import `url` (a `file:` URL, `URL`, or absolute path) with the safe-ts transform, from code
45
+ * that itself wasn't transformed: a Vite config, which Vite loads without plugins. Registers the
46
+ * Node loader's hooks in this process (as `--import @evobug_com/safe-ts-transform/register`
47
+ * does), then imports the module through them, so it and everything it imports are transformed.
48
+ * 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.
50
+ */
51
+ export async function loadTransformed(url) {
52
+ await import("./register.mjs");
53
+ const href = url instanceof URL ? url.href : isAbsolute(String(url)) ? pathToFileURL(String(url)).href : String(url);
54
+ return import(href);
39
55
  }
40
56
 
41
57
  /** The query parameter of a shared validator module: `/src/types.ts?safe-ts-json=v$User`. */
@@ -172,7 +188,8 @@ export function safeTs(options = {}) {
172
188
  }
173
189
  }
174
190
  }
175
- const { code: out, dependencies } = transformWithDependencies(file, code, { devChecks, sharedValidators });
191
+ const { code: out, dependencies, warnings } = transformWithDependencies(file, code, { devChecks, sharedValidators });
192
+ for (const warning of warnings) this.warn(`safe-ts: ${warning}`);
176
193
  // Generated validators follow the types they were made from, wherever those are declared.
177
194
  // (Not when a wrapper plugin calls this hook without a context.)
178
195
  if (typeof this?.addWatchFile === "function") for (const dependency of dependencies) this.addWatchFile(dependency);
@@ -207,10 +224,14 @@ const COMPILE_HINT = "//# allFunctionsCalledOnLoad";
207
224
  /** Set by the Node loader (`register.mjs`): the files it transformed in this process. */
208
225
  const LOADED = Symbol.for("safe-ts.loader.files");
209
226
 
227
+ /** The loader's hooks, imported by a config: they apply only to what it loads afterwards. */
228
+ const REGISTER_IMPORT = /["']@evobug_com\/safe-ts-transform\/register(?:\.mjs)?["']/;
229
+
210
230
  /**
211
231
  * Vite loads its config file, and what the config imports, without plugins: code there that
212
232
  * needs the transform fails (`PropagateError is not defined`, "q() was not compiled"). Unless
213
233
  * the Node loader transformed it (`--configLoader native` with the loader registered first).
234
+ * Only what runs counts: imports of types, `import()` and `loadTransformed(...)` are left out.
214
235
  */
215
236
  export function configFileWarning(configFile) {
216
237
  if (typeof configFile !== "string" || globalThis[LOADED]?.has(configFile)) return undefined;
@@ -223,10 +244,22 @@ export function configFileWarning(configFile) {
223
244
  const untransformed = needs.filter((n) => !globalThis[LOADED]?.has(n.file));
224
245
  if (untransformed.length === 0) return undefined;
225
246
  const lines = untransformed.map((n) => ` ${n.file}: uses ${n.needs}`);
247
+ let registers = false;
248
+ try {
249
+ registers = REGISTER_IMPORT.test(readFileSync(configFile, "utf8"));
250
+ } catch {
251
+ // Gone in between: no hint.
252
+ }
253
+ const register = registers
254
+ ? "Importing @evobug_com/safe-ts-transform/register in the config doesn't cover these: a module's imports " +
255
+ "load before its code runs, so the hooks apply only to what the config loads later (`import()` in a hook, " +
256
+ "`loadTransformed(...)`).\n"
257
+ : "";
226
258
  return (
227
259
  `safe-ts: Vite loads ${configFile} without the safe-ts transform (plugins don't apply to the config), ` +
228
- `but it imports code that needs it:\n${lines.join("\n")}\n` +
229
- "That code fails when it runs. Start Vite with `--configLoader native` and " +
260
+ `but it imports code that needs it:\n${lines.join("\n")}\n${register}` +
261
+ "That code fails when it runs. Load it with `await loadTransformed(new URL(\"./plugins.ts\", import.meta.url))` " +
262
+ "from @evobug_com/safe-ts-transform, start Vite with `--configLoader native` and " +
230
263
  'NODE_OPTIONS="--import @evobug_com/safe-ts-transform/register", or keep code the config imports free of it: ' +
231
264
  "https://safe-ts.evobug-pages.com/guide/adoption#the-vite-config"
232
265
  );
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@evobug_com/safe-ts-transform",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
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.",
5
5
  "keywords": [
6
6
  "safe-ts",
@@ -43,11 +43,11 @@
43
43
  "node": ">=22.18.0"
44
44
  },
45
45
  "dependencies": {
46
- "@evobug_com/safe-ts-native": "0.2.0",
46
+ "@evobug_com/safe-ts-native": "0.3.0",
47
47
  "magic-string": "^1.4.5"
48
48
  },
49
49
  "peerDependencies": {
50
- "@evobug_com/safe-ts-std": "^0.2.0",
50
+ "@evobug_com/safe-ts-std": "^0.3.0",
51
51
  "vite": "^6.0.0 || ^7.0.0 || ^8.0.0"
52
52
  },
53
53
  "peerDependenciesMeta": {
package/register.mjs CHANGED
@@ -3,6 +3,8 @@
3
3
  // Dev checks (https://safe-ts.evobug-pages.com/guide/dev-checks) are on unless
4
4
  // NODE_ENV=production; SAFE_TS_DEV_CHECKS=1 or =0 overrides that.
5
5
  // Transformed files are cached on disk (cache.mjs); SAFE_TS_CACHE=0 turns that off.
6
+ // A file that uses prelude names where no tsconfig.json turns the prelude on (a copy of a script
7
+ // outside the project) is still loaded, with a warning: those names aren't defined there.
6
8
  // The validators of named types are generated once, in shared modules every file using them
7
9
  // imports (`<declaring file>?safe-ts-json=<key>`, served here); SAFE_TS_SHARED_VALIDATORS=0
8
10
  // gives every file its own copies instead.
@@ -22,6 +24,7 @@ const cache = openCache(process.env, { devChecks, sharedValidators });
22
24
 
23
25
  // The files this thread transformed, for the Vite plugin's config check (index.mjs).
24
26
  const loaded = (globalThis[Symbol.for("safe-ts.loader.files")] ??= new Set());
27
+ const warned = new Set();
25
28
 
26
29
  registerHooks({
27
30
  resolve(specifier, context, nextResolve) {
@@ -62,7 +65,13 @@ registerHooks({
62
65
  if (source === undefined) {
63
66
  const result = transformWithDependencies(filename, code, { devChecks, sharedValidators });
64
67
  source = result.code;
65
- cache?.set(filename, code, result);
68
+ // A file with a warning isn't cached, so the warning shows on every run until it's fixed.
69
+ if (result.warnings.length === 0) cache?.set(filename, code, result);
70
+ for (const warning of result.warnings) {
71
+ // Right away (not `process.emitWarning`, which waits a tick): the file may fail as it loads.
72
+ if (!warned.has(warning)) process.stderr.write(`safe-ts warning: ${warning}\n`);
73
+ warned.add(warning);
74
+ }
66
75
  }
67
76
  loaded.add(filename);
68
77
  return { format: "module-typescript", source, shortCircuit: true };