@timefoldai/viz-cli 0.0.0 → 0.1.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/README.md CHANGED
@@ -1,3 +1,65 @@
1
1
  # @timefoldai/viz-cli
2
2
 
3
- Placeholder that reserves the name. The first release is 0.1.0.
3
+ Build tools for a Timefold model visualization app: the shared Vite and Vitest configs, the oxlint and
4
+ stylelint rules, and the build guards `viz-check-leaked-env`, `viz-check-css-layer-order` and
5
+ `viz-codegen`.
6
+
7
+ ## Install
8
+
9
+ ```sh
10
+ pnpm add --save-dev @timefoldai/viz-cli vite
11
+ ```
12
+
13
+ The package needs Node 26 or later.
14
+ `vite` 8 is required. Each other peer is optional: install it when you use the entry or the bin that needs it.
15
+ Each peer range names the major that the package is tested with: `vite` 8, `vitest` 5, `stylelint` 18, `@tailwindcss/vite` 4, `@vitejs/plugin-react` 6 and `openapi-typescript` 7.
16
+ You need no registry token and no `.npmrc`.
17
+
18
+ | Entry or bin | Install with it |
19
+ | ---------------------------- | ------------------------------------------------------------- |
20
+ | `@timefoldai/viz-cli/vite` | `@tailwindcss/vite`, `@vitejs/plugin-react` |
21
+ | `@timefoldai/viz-cli/vitest` | `vitest`, `@vitest/coverage-istanbul`, `@vitejs/plugin-react` |
22
+ | `viz-codegen` | `openapi-typescript` |
23
+ | `./stylelint/*` | `stylelint` |
24
+
25
+ ## Example
26
+
27
+ ```ts
28
+ // vite.config.ts
29
+ import { appViteConfig } from "@timefoldai/viz-cli/vite";
30
+
31
+ export default appViteConfig({ appDir: import.meta.dirname, port: 5173 });
32
+ ```
33
+
34
+ The config adds React, Tailwind CSS, and a `<style>` that declares the layer order of `@timefoldai/viz-react/theme.css`.
35
+
36
+ ## Lint rules
37
+
38
+ | Plugin | Registers in | Rules |
39
+ | ----------------------------------------------------- | ---------------------------------- | --------------------------------------------------------- |
40
+ | `@timefoldai/viz-cli/oxlint/comment-rules` | `.oxlintrc.json` `jsPlugins` | `comments/no-inline-comment`, `comments/docblock-prose` |
41
+ | `@timefoldai/viz-cli/oxlint/test-file-rules` | `.oxlintrc.json` `jsPlugins` | `tests/one-test-file-per-source` |
42
+ | `@timefoldai/viz-cli/stylelint/no-stylesheet-comment` | `.stylelintrc.json` `plugins` | `viz/no-stylesheet-comment` |
43
+
44
+ `comments/no-inline-comment` allows no comment in a function body but a tool directive with its reason on the same line, or one `// why:` line.
45
+ `comments/docblock-prose` allows docblock prose only on an exported declaration: at most 2 lines, 4 on a class.
46
+ `viz/no-stylesheet-comment` allows no comment in a stylesheet but `tokens-allow`.
47
+
48
+ ## Build guards
49
+
50
+ Run each guard after `vite build`. Pass `--out-dir` when Vite's `build.outDir` is not `dist`.
51
+ Pass `viz-check-css-layer-order` the option `--base` when Vite's `base` is a sub-path, such as `--base /app/`.
52
+
53
+ ## TypeScript
54
+
55
+ The types support TypeScript 7 and later. CI type-checks the package with TypeScript 7.
56
+
57
+ ## Support
58
+
59
+ - To report a security vulnerability, email security@timefold.ai. Don't post the details in public.
60
+ - To report a bug or to get help with this package, email support@timefold.ai.
61
+
62
+ ## License
63
+
64
+ Apache License 2.0: the `LICENSE` file of this package holds the text.
65
+ The license grants no right to use the Timefold name, logo, or brand colors, except to describe where the package comes from.
@@ -0,0 +1,14 @@
1
+ import process from "node:process";
2
+
3
+ /**
4
+ * Runs `main` with the command-line arguments when `meta` is the process entry.
5
+ * Exits 1 on a Node with no `import.meta.main`; the supported floor is Node 26.
6
+ */
7
+ export function runBin(meta, name, main) {
8
+ if (meta.main === undefined) {
9
+ console.error(`${name}: FAIL — this command needs Node 26 or newer`);
10
+ process.exit(1);
11
+ }
12
+
13
+ if (meta.main) return main(process.argv.slice(2));
14
+ }
@@ -0,0 +1,149 @@
1
+ #!/usr/bin/env node
2
+ import { readFileSync } from "node:fs";
3
+ import { isAbsolute, join, relative, resolve } from "node:path";
4
+ import process from "node:process";
5
+ import { parseArgs } from "node:util";
6
+
7
+ import { declaredLayerOrder } from "@timefoldai/viz-cli/layer-order";
8
+
9
+ import { runBin } from "./run-bin.mjs";
10
+
11
+ const SHEET_PATTERN =
12
+ /<style[^>]*>([\s\S]*?)<\/style>|<link\b[^>]*\brel="stylesheet"[^>]*>/g;
13
+ const LAYER_RULE_PATTERN = /@layer\s+([^;{]+)([;{])/;
14
+
15
+ const layerNames = (list) => list.split(",").map((name) => name.trim());
16
+
17
+ function pageSheets(html, readLinkedSheet) {
18
+ return [...html.matchAll(SHEET_PATTERN)].map(
19
+ ([tag, inlineCss]) =>
20
+ inlineCss ?? readLinkedSheet(/\bhref="([^"]+)"/.exec(tag)[1]),
21
+ );
22
+ }
23
+
24
+ /** The first `@layer` rule a page's stylesheets reach, in document order, or `null` when none names a layer. */
25
+ export function firstLayerRule(html, readLinkedSheet) {
26
+ for (const css of pageSheets(html, readLinkedSheet)) {
27
+ const rule = LAYER_RULE_PATTERN.exec(css);
28
+
29
+ if (rule) {
30
+ return { names: layerNames(rule[1]), isStatement: rule[2] === ";" };
31
+ }
32
+ }
33
+
34
+ return null;
35
+ }
36
+
37
+ function usedTopLevelLayers(html, readLinkedSheet) {
38
+ const rules = pageSheets(html, readLinkedSheet).flatMap((css) => [
39
+ ...css.matchAll(new RegExp(LAYER_RULE_PATTERN, "g")),
40
+ ]);
41
+
42
+ return new Set(
43
+ rules.flatMap(([, list]) =>
44
+ layerNames(list).map((name) => name.split(".")[0]),
45
+ ),
46
+ );
47
+ }
48
+
49
+ /** Why a built page fails to declare the full layer order first, or `null` when it does. */
50
+ export function layerOrderViolation(html, readLinkedSheet, statement) {
51
+ const expected = layerNames(LAYER_RULE_PATTERN.exec(statement)[1]);
52
+ const first = firstLayerRule(html, readLinkedSheet);
53
+
54
+ if (!first) return "no stylesheet names a cascade layer";
55
+ if (!first.isStatement) {
56
+ return `the first layer rule is the "${first.names[0]}" block, not the order statement "${statement}"`;
57
+ }
58
+ if (first.names.join() !== expected.join()) {
59
+ return `the first layer statement orders ${first.names.join(", ")}, not ${expected.join(", ")}`;
60
+ }
61
+
62
+ const undeclared = [...usedTopLevelLayers(html, readLinkedSheet)].filter(
63
+ (name) => !expected.includes(name),
64
+ );
65
+
66
+ if (undeclared.length > 0) {
67
+ return `the layer(s) ${undeclared.join(", ")} are missing from "${statement}" in the theme stylesheet, so they rank above utilities`;
68
+ }
69
+
70
+ return null;
71
+ }
72
+
73
+ function distRelativeHref(href, base) {
74
+ if (/^[a-z][a-z\d+.-]*:|^\/\//i.test(href)) return null;
75
+ if (!href.startsWith("/")) return href;
76
+
77
+ const basePath = base.endsWith("/") ? base : `${base}/`;
78
+
79
+ return href.startsWith(basePath) ? href.slice(basePath.length) : null;
80
+ }
81
+
82
+ function isInsideDist(distDir, distHref) {
83
+ if (distHref === null) return false;
84
+
85
+ const fromDist = relative(distDir, resolve(distDir, distHref));
86
+
87
+ return !fromDist.startsWith("..") && !isAbsolute(fromDist);
88
+ }
89
+
90
+ /** Reads a stylesheet that a built page links, and refuses one that lies outside the build output. */
91
+ export function readDistSheet(distDir, href, base) {
92
+ const distHref = distRelativeHref(href, base);
93
+
94
+ if (!isInsideDist(distDir, distHref)) {
95
+ throw new Error(
96
+ `check-css-layer-order: the stylesheet "${href}" lies outside ${distDir} served at base "${base}", so its layer rules cannot be checked`,
97
+ );
98
+ }
99
+
100
+ return readFileSync(resolve(distDir, distHref), "utf8");
101
+ }
102
+
103
+ function readIndexHtml(outDir) {
104
+ const indexPath = join(outDir, "index.html");
105
+
106
+ try {
107
+ return readFileSync(indexPath, "utf8");
108
+ } catch (error) {
109
+ if (error.code !== "ENOENT") throw error;
110
+ console.error(
111
+ `check-css-layer-order: FAIL — ${indexPath} is missing; build the app first`,
112
+ );
113
+ process.exit(1);
114
+ }
115
+ }
116
+
117
+ function main(args) {
118
+ const { values, positionals } = parseArgs({
119
+ args,
120
+ allowPositionals: true,
121
+ options: {
122
+ "out-dir": { type: "string", default: "dist" },
123
+ base: { type: "string", default: "/" },
124
+ "theme-stylesheet": { type: "string" },
125
+ },
126
+ });
127
+ const appDir = resolve(positionals[0] ?? ".");
128
+ const outDir = resolve(appDir, values["out-dir"]);
129
+ const violation = layerOrderViolation(
130
+ readIndexHtml(outDir),
131
+ (href) => readDistSheet(outDir, href, values.base),
132
+ declaredLayerOrder(appDir, values["theme-stylesheet"]),
133
+ );
134
+
135
+ if (violation) {
136
+ console.error(
137
+ `check-css-layer-order: FAIL — in ${join(outDir, "index.html")}, ${violation}.\n` +
138
+ "The first layer rule a page reaches fixes the order of every layer, so a CSS chunk\n" +
139
+ "that loads first could put `base` after `components` and let the reset beat every component.",
140
+ );
141
+ process.exit(1);
142
+ }
143
+
144
+ console.log(
145
+ `check-css-layer-order: OK — ${appDir} declares the layer order first`,
146
+ );
147
+ }
148
+
149
+ runBin(import.meta, "check-css-layer-order", main);
@@ -0,0 +1,417 @@
1
+ #!/usr/bin/env node
2
+ import { spawnSync } from "node:child_process";
3
+ import { randomBytes } from "node:crypto";
4
+ import {
5
+ copyFileSync,
6
+ existsSync,
7
+ mkdtempSync,
8
+ readdirSync,
9
+ readFileSync,
10
+ realpathSync,
11
+ rmSync,
12
+ statSync,
13
+ } from "node:fs";
14
+ import { createRequire } from "node:module";
15
+ import { tmpdir } from "node:os";
16
+ import { basename, dirname, join, relative, resolve } from "node:path";
17
+ import process from "node:process";
18
+ import { pathToFileURL } from "node:url";
19
+ import { parseArgs } from "node:util";
20
+
21
+ import { runBin } from "./run-bin.mjs";
22
+
23
+ const MIN_ARTIFACT_SCAN_LENGTH = 8;
24
+
25
+ const BUILD_MODE = "production";
26
+
27
+ const BUILD_NODE_ENV = "production";
28
+
29
+ const DEFAULT_OUT_DIR = "dist";
30
+
31
+ const EXTRA_OUTPUT_DIRS = ["storybook-static"];
32
+
33
+ class GuardFailure extends Error {}
34
+
35
+ function selectLocal(repoRoot, paths) {
36
+ return paths.filter((path) => {
37
+ const { status, stderr } = spawnSync(
38
+ "git",
39
+ ["ls-files", "--error-unmatch", "--", path],
40
+ { cwd: repoRoot, encoding: "utf8" },
41
+ );
42
+
43
+ if (status !== 0 && status !== 1) {
44
+ throw new GuardFailure(
45
+ `git ls-files --error-unmatch ${path} failed (status ${status}): ${stderr}`,
46
+ );
47
+ }
48
+
49
+ return status === 1;
50
+ });
51
+ }
52
+
53
+ async function appEnvOptions(dir) {
54
+ const require = createRequire(join(dir, "package.json"));
55
+
56
+ try {
57
+ const vite = await import(pathToFileURL(require.resolve("vite")).href);
58
+ const config = await vite.resolveConfig(
59
+ { root: dir, mode: BUILD_MODE, logLevel: "silent" },
60
+ "build",
61
+ BUILD_MODE,
62
+ BUILD_NODE_ENV,
63
+ );
64
+
65
+ return {
66
+ loadEnv: vite.loadEnv,
67
+ envDir: config.envDir,
68
+ prefixes: vite.resolveEnvPrefix(config),
69
+ };
70
+ } catch (error) {
71
+ throw new GuardFailure(
72
+ `could not resolve the vite config of ${dir}, so the guard cannot tell which env files ` +
73
+ `and keys a build reads: ${error.message}`,
74
+ );
75
+ }
76
+ }
77
+
78
+ function localEnvValues(env, localEnvFiles, committedEnvFiles) {
79
+ if (localEnvFiles.length === 0) return [];
80
+
81
+ const resolved = env.loadEnv(BUILD_MODE, env.envDir, env.prefixes);
82
+ const committedOnlyDir = mkdtempSync(join(tmpdir(), "check-env-leak-"));
83
+
84
+ try {
85
+ for (const file of committedEnvFiles) {
86
+ copyFileSync(file, join(committedOnlyDir, basename(file)));
87
+ }
88
+
89
+ const committed = env.loadEnv(
90
+ BUILD_MODE,
91
+ committedOnlyDir,
92
+ env.prefixes,
93
+ );
94
+
95
+ return Object.entries(resolved).filter(
96
+ ([key, value]) => value && committed[key] !== value,
97
+ );
98
+ } finally {
99
+ rmSync(committedOnlyDir, { recursive: true, force: true });
100
+ }
101
+ }
102
+
103
+ const isScannable = (name) =>
104
+ /\.(js|mjs|cjs|css|html|json|map|svg|txt)$/.test(name);
105
+
106
+ function walk(dir, predicate) {
107
+ return readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
108
+ const path = join(dir, entry.name);
109
+ if (entry.isDirectory()) return walk(path, predicate);
110
+ return predicate(entry.name) ? [path] : [];
111
+ });
112
+ }
113
+
114
+ const sentinelFor = (key) =>
115
+ `tfEnvLeakProbe${key.replaceAll(/[^A-Za-z0-9]/g, "")}${randomBytes(12).toString("hex")}`;
116
+
117
+ const VITE_CONFIG_NAMES = [
118
+ "vite.config.ts",
119
+ "vite.config.mts",
120
+ "vite.config.js",
121
+ "vite.config.mjs",
122
+ ];
123
+
124
+ function inlinedKeys(dir, keys) {
125
+ if (keys.length === 0) return [];
126
+
127
+ if (!VITE_CONFIG_NAMES.some((name) => existsSync(join(dir, name)))) {
128
+ throw new GuardFailure(
129
+ `${dir} has local env values but no vite config, so the inlining probe cannot run.\n` +
130
+ "Add a vite.config file, or remove the local env file.",
131
+ );
132
+ }
133
+
134
+ const require = createRequire(join(dir, "package.json"));
135
+ const viteBin = join(
136
+ dirname(require.resolve("vite/package.json")),
137
+ "bin",
138
+ "vite.js",
139
+ );
140
+ const sentinels = keys.map((key) => [key, sentinelFor(key)]);
141
+ const outDir = mkdtempSync(join(tmpdir(), "check-env-leak-probe-"));
142
+
143
+ try {
144
+ const { status, stdout, stderr } = spawnSync(
145
+ process.execPath,
146
+ [
147
+ viteBin,
148
+ "build",
149
+ "--mode",
150
+ BUILD_MODE,
151
+ "--outDir",
152
+ outDir,
153
+ "--emptyOutDir",
154
+ "--logLevel",
155
+ "error",
156
+ ],
157
+ {
158
+ cwd: dir,
159
+ encoding: "utf8",
160
+ env: { ...process.env, ...Object.fromEntries(sentinels) },
161
+ },
162
+ );
163
+
164
+ if (status !== 0) {
165
+ throw new GuardFailure(
166
+ `the inlining probe build of ${dir} failed (status ${status}):\n${stdout}${stderr}`,
167
+ );
168
+ }
169
+
170
+ const files = walk(outDir, isScannable).map((path) => ({
171
+ path,
172
+ text: readFileSync(path, "utf8"),
173
+ }));
174
+
175
+ return sentinels
176
+ .filter(([, sentinel]) =>
177
+ files.some((file) => file.text.includes(sentinel)),
178
+ )
179
+ .map(([key]) => key);
180
+ } finally {
181
+ rmSync(outDir, { recursive: true, force: true });
182
+ }
183
+ }
184
+
185
+ const isSearchableSource = (path) =>
186
+ /\.(m?[jt]sx?|c[jt]s|css|html?|json|svg|txt)$/i.test(path) ||
187
+ /(^|\/)\.env(\.|$)/.test(path);
188
+
189
+ function sourceExplainer(repoRoot) {
190
+ let corpus = null;
191
+
192
+ function committedSources() {
193
+ if (corpus) return corpus;
194
+
195
+ const { status, stdout, stderr } = spawnSync(
196
+ "git",
197
+ ["ls-files", "-z", "--full-name"],
198
+ { cwd: repoRoot, encoding: "utf8", maxBuffer: 64 * 1024 * 1024 },
199
+ );
200
+
201
+ if (status !== 0) {
202
+ throw new GuardFailure(
203
+ `git ls-files failed (status ${status}): ${stderr}`,
204
+ );
205
+ }
206
+
207
+ corpus = stdout
208
+ .split("\0")
209
+ .filter((name) => name && isSearchableSource(name))
210
+ .map((name) => join(repoRoot, name))
211
+ .filter((path) => existsSync(path) && statSync(path).isFile())
212
+ .map((path) => ({ path, text: readFileSync(path, "utf8") }));
213
+
214
+ return corpus;
215
+ }
216
+
217
+ return (value) =>
218
+ committedSources()
219
+ .filter((file) => file.text.includes(value))
220
+ .map((file) => relative(repoRoot, file.path));
221
+ }
222
+
223
+ function gitTopLevel(cwd) {
224
+ const { status, stdout, stderr } = spawnSync(
225
+ "git",
226
+ ["rev-parse", "--show-toplevel"],
227
+ { cwd, encoding: "utf8" },
228
+ );
229
+
230
+ if (status !== 0) {
231
+ throw new GuardFailure(
232
+ `git rev-parse --show-toplevel failed in ${cwd} (status ${status}): ${stderr.trim()}\n` +
233
+ "This guard asks git which env files are local, so the app must sit in a git repository.",
234
+ );
235
+ }
236
+
237
+ return stdout.trim();
238
+ }
239
+
240
+ function appDirectory(positionals) {
241
+ if (positionals.length > 1) {
242
+ throw new GuardFailure(`expected one app directory\n${USAGE}`);
243
+ }
244
+
245
+ const name = positionals[0] ?? ".";
246
+ const dir = resolve(name);
247
+
248
+ if (!existsSync(join(dir, "package.json"))) {
249
+ throw new GuardFailure(
250
+ `${name} has no package.json, so it is not an app directory`,
251
+ );
252
+ }
253
+
254
+ return realpathSync(dir);
255
+ }
256
+
257
+ const USAGE = "usage: viz-check-leaked-env [<appDir>] [--out-dir <dir>]";
258
+
259
+ function parseCli(args) {
260
+ try {
261
+ return parseArgs({
262
+ args,
263
+ allowPositionals: true,
264
+ options: { "out-dir": { type: "string" } },
265
+ });
266
+ } catch (error) {
267
+ if (error.code?.startsWith("ERR_PARSE_ARGS")) {
268
+ throw new GuardFailure(`${error.message}\n${USAGE}`);
269
+ }
270
+
271
+ throw error;
272
+ }
273
+ }
274
+
275
+ function assertExplicitOutDirExists(dir, explicitOutDir) {
276
+ const outDir = resolve(dir, explicitOutDir);
277
+
278
+ if (!existsSync(outDir)) {
279
+ throw new GuardFailure(
280
+ `${outDir} does not exist; build the app first or fix --out-dir`,
281
+ );
282
+ }
283
+ }
284
+
285
+ function envFilesIn(envDir) {
286
+ if (envDir === false || !existsSync(envDir)) return [];
287
+
288
+ return readdirSync(envDir, { withFileTypes: true })
289
+ .filter((entry) => entry.isFile() && entry.name.startsWith(".env"))
290
+ .map((entry) => join(envDir, entry.name));
291
+ }
292
+
293
+ async function checkApp({ dir, repoRoot, explicitOutDir, sourcesExplaining }) {
294
+ if (explicitOutDir !== undefined) {
295
+ assertExplicitOutDirExists(dir, explicitOutDir);
296
+ }
297
+
298
+ const result = { failed: false, checkedKeys: 0, scannedFiles: 0 };
299
+ const label = relative(repoRoot, dir) || ".";
300
+ const env = await appEnvOptions(dir);
301
+ const envCandidates = envFilesIn(env.envDir);
302
+ const localEnvFiles = selectLocal(repoRoot, envCandidates);
303
+ const values = localEnvValues(
304
+ env,
305
+ localEnvFiles,
306
+ envCandidates.filter((path) => !localEnvFiles.includes(path)),
307
+ );
308
+ if (values.length === 0) return result;
309
+ result.checkedKeys = values.length;
310
+
311
+ const leakingKeys = new Set(
312
+ inlinedKeys(
313
+ dir,
314
+ values.map(([key]) => key),
315
+ ),
316
+ );
317
+
318
+ for (const key of leakingKeys) {
319
+ console.error(
320
+ `INLINED ${key} (local env of ${label}) — a production build bakes this key's value into the bundle`,
321
+ );
322
+ result.failed = true;
323
+ }
324
+
325
+ const outputs = [explicitOutDir ?? DEFAULT_OUT_DIR, ...EXTRA_OUTPUT_DIRS]
326
+ .map((name) => resolve(dir, name))
327
+ .filter((path) => existsSync(path));
328
+ if (outputs.length === 0) {
329
+ console.log(
330
+ `check-no-leaked-env: ${label} has a local env file but no built output — only the inlining probe ran`,
331
+ );
332
+ return result;
333
+ }
334
+
335
+ const builtFiles = outputs
336
+ .flatMap((path) => walk(path, isScannable))
337
+ .map((path) => ({ path, text: readFileSync(path, "utf8") }));
338
+ result.scannedFiles = builtFiles.length;
339
+
340
+ for (const [key, value] of values) {
341
+ if (leakingKeys.has(key)) continue;
342
+ if (value.length < MIN_ARTIFACT_SCAN_LENGTH) {
343
+ console.log(
344
+ `check-no-leaked-env: ${key} (${label}) is under ${MIN_ARTIFACT_SCAN_LENGTH} chars — too short to match built output reliably, so only the inlining probe covered it (it did)`,
345
+ );
346
+ continue;
347
+ }
348
+
349
+ const hits = builtFiles.filter((file) => file.text.includes(value));
350
+
351
+ if (hits.length === 0) continue;
352
+
353
+ const explanations = sourcesExplaining(value);
354
+
355
+ if (explanations.length > 0) {
356
+ console.log(
357
+ `check-no-leaked-env: ${key} (${label}) matches ${hits.length} built file(s), but the same string is a literal in committed source (${explanations.join(", ")}) and the probe proved the key is not inlined — not a leak`,
358
+ );
359
+ continue;
360
+ }
361
+
362
+ console.error(
363
+ `LEAKED ${key} (local env of ${label}) into ${hits.map((hit) => hit.path).join(", ")}`,
364
+ );
365
+ result.failed = true;
366
+ }
367
+
368
+ return result;
369
+ }
370
+
371
+ const FAILURE_GUIDANCE =
372
+ "\ncheck-no-leaked-env: FAIL — a local env value can reach, or already sits in, a production bundle.\n" +
373
+ "A production bundle must never carry local config. Three ways to resolve this:\n\n" +
374
+ " * INLINED — a local-dev value: read it only inside an `import.meta.env.DEV` branch,\n" +
375
+ " so the production build strips it.\n" +
376
+ " * INLINED — deployment config that is meant to be inlined: move it out of the local\n" +
377
+ " env file into a committed `.env.production` or a CI environment variable, so the\n" +
378
+ " value in the bundle is a reviewed one.\n" +
379
+ " * LEAKED — the value sits in the built output although the current source cannot inline\n" +
380
+ " it: the output is stale. Delete the output directory and build again, so the bundle\n" +
381
+ " matches the source that was checked.";
382
+
383
+ async function main(args) {
384
+ const { values, positionals } = parseCli(args);
385
+ const dir = appDirectory(positionals);
386
+ const repoRoot = gitTopLevel(dir);
387
+ const { failed, checkedKeys, scannedFiles } = await checkApp({
388
+ dir,
389
+ repoRoot,
390
+ explicitOutDir: values["out-dir"],
391
+ sourcesExplaining: sourceExplainer(repoRoot),
392
+ });
393
+
394
+ if (failed) {
395
+ console.error(FAILURE_GUIDANCE);
396
+ } else {
397
+ console.log(
398
+ checkedKeys === 0
399
+ ? "check-no-leaked-env: OK — no local env value could have been inlined"
400
+ : `check-no-leaked-env: OK — ${checkedKeys} local env key(s) are not inlined by the source and absent from ${scannedFiles} built file(s)`,
401
+ );
402
+ }
403
+
404
+ process.exit(failed ? 1 : 0);
405
+ }
406
+
407
+ async function runCli(args) {
408
+ try {
409
+ await main(args);
410
+ } catch (error) {
411
+ if (!(error instanceof GuardFailure)) throw error;
412
+ console.error(`check-no-leaked-env: FAIL — ${error.message}`);
413
+ process.exit(1);
414
+ }
415
+ }
416
+
417
+ await runBin(import.meta, "check-no-leaked-env", runCli);