@ultimat3/cli 31.3.0 → 31.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/package.json +29 -29
  2. package/src/cmd-doctor.ts +12 -316
  3. package/src/doctor-database.ts +121 -0
  4. package/src/doctor-port.ts +88 -0
  5. package/src/doctor-probe.ts +148 -0
  6. package/src/framework-schema.ts +4 -2
  7. package/src/guard-sources.ts +32 -11
  8. package/src/templates/guard-bare-error.ts +1 -1
  9. package/src/templates/guard-error-declared.ts +51 -5
  10. package/src/templates/guard-image-dimensions.ts +3 -2
  11. package/src/templates/guard-local-binding.ts +74 -0
  12. package/src/templates/guard-native-confirm.ts +16 -1
  13. package/src/templates/guard-raw-fetch.ts +11 -3
  14. package/src/templates/guard-raw-interval.ts +8 -1
  15. package/src/templates/guard-raw-motion.ts +20 -4
  16. package/src/templates/guard-semantic-interactive.ts +20 -2
  17. package/src/templates/guard-undeclared-custom-property.ts +34 -10
  18. package/src/templates/guard-undefined-style-class.ts +34 -7
  19. package/src/templates/guard-untranslated-string.ts +5 -4
  20. package/src/templates/guard-unzoned-date.ts +14 -1
  21. package/src/templates/scaffold-auth.ts +7 -10
  22. package/src/templates/scaffold-claude-agents.ts +1 -1
  23. package/src/templates/scaffold-claude-commands.ts +1 -1
  24. package/src/templates/scaffold-docs.ts +1 -1
  25. package/src/templates/scaffold-domain-package.ts +1 -1
  26. package/src/templates/slice-foundation.ts +1 -1
  27. package/wiki/Actions.md +3 -2
  28. package/wiki/Agents.md +1 -1
  29. package/wiki/Building-Your-Own-Base.md +1 -1
  30. package/wiki/Interface-Rules.md +3 -3
  31. package/wiki/MCP-And-AI.md +1 -1
  32. package/wiki/Stability.md +6 -5
  33. package/wiki/Upgrading.md +11 -10
@@ -0,0 +1,148 @@
1
+ // The seam `runDoctor` reads instead of the environment, and the real one over this machine: every
2
+ // fact `x doctor` judges is reached through `DoctorProbe`, so every rule is testable with a stub.
3
+
4
+ // why: Bun has no synchronous file-exists or path-join API; the probe answers `exists` synchronously.
5
+ import { existsSync } from 'node:fs';
6
+ import { join } from 'node:path';
7
+ import { PGLITE_PACKAGE } from '@ultimat3/db';
8
+ import { loadApp } from './app-load';
9
+ import { IMPORT_UNRESOLVED } from './app-load-unresolved';
10
+ import { findAppRoot } from './app-root';
11
+ import { checkMigrationSnapshots } from './db-snapshot';
12
+ import { type AuthStorageFact, authStorageProbe } from './doctor-auth';
13
+ import type { EmbeddedDatabase } from './doctor-database';
14
+ import { externalUrl, installedAbove, probeDatabase } from './doctor-database';
15
+ import type { OfflineFallbackFact } from './doctor-offline';
16
+ import { offlineFallbackProbe } from './doctor-offline';
17
+ import type { PoolerFact } from './doctor-pooler';
18
+ import { poolerProbe } from './doctor-pooler';
19
+ import { rowSecurityProbe } from './doctor-row-security';
20
+ import type { SealedKeysFact } from './doctor-sealed';
21
+ import { sealedKeysProbe } from './doctor-sealed';
22
+ import { typescriptProbe } from './doctor-typescript';
23
+ import { machineSecretFindings } from './framework-env';
24
+ import type { Finding } from './output';
25
+ import { portFree } from './port-probe';
26
+ import { checkMigrationDrift } from './schema-drift';
27
+ import type { TypescriptLag } from './typescript-floor';
28
+
29
+ /**
30
+ * The injection seam `runDoctor` reads instead of the environment. Not a semver surface —
31
+ * `wiki/Upgrading.md` covers `X_*` codes, the eight primitive shapes, the `x` CLI surface, the
32
+ * tier table and `app.config.ts` fields, and not this — so a new fact the probe must report is a
33
+ * REQUIRED field: an optional one lets an implementation skip the check and still typecheck.
34
+ */
35
+ export interface DoctorProbe {
36
+ readonly bunVersion: string;
37
+ /** App root, or undefined when the command runs outside an app. */
38
+ readonly root: string | undefined;
39
+ readonly port: number;
40
+ /** `APP_URL` as this environment declares it; `undefined` when unset. */
41
+ readonly appUrl: string | undefined;
42
+ /**
43
+ * The framework's own secrets this machine lacks — `framework-env.ts`'s
44
+ * `machineSecretFindings`, gated by `namedDeployed`: only an environment NAMED staging or
45
+ * production (an unnamed developer shell owes nothing; `x env check` is the fail-closed answer).
46
+ * The list's own `needed`/`unsafe` decide; doctor reports.
47
+ */
48
+ readonly frameworkFindings: readonly Finding[];
49
+ exists(relativePath: string): boolean;
50
+ portFree(port: number): Promise<boolean>;
51
+ /**
52
+ * Is the configured database reachable, and what refused? `null` is "reachable, or there is
53
+ * nothing external to reach" — an unset `DATABASE_URL` is embedded PGlite, which `x dev` owns
54
+ * and which a probe would take the single-writer lock on.
55
+ *
56
+ * Until this existed `x doctor` answered "no findings — environment is shippable" against
57
+ * `DATABASE_URL=postgres://nope:nope@localhost:5432/nope`, while `x db migrate` on the same env
58
+ * correctly answered `X_DB_UNAVAILABLE` (#F5).
59
+ */
60
+ database(): Promise<Finding | null>;
61
+ /**
62
+ * Is the EMBEDDED database usable, and is it the one this environment would open? A FACT and not
63
+ * a finding, the split `offlineFallback` makes below: reaching a module resolver is IO, and what
64
+ * an unresolvable optional peer MEANS is a pure rule with a pure test.
65
+ *
66
+ * `database()` answers `null` the moment `DATABASE_URL` is unset — which is exactly a bare VM,
67
+ * the configuration `x dev` invents a database FOR — so until this existed `x doctor` was silent
68
+ * about the only database a fresh box has. `bin/setup` found out instead, at `x db migrate`.
69
+ */
70
+ embeddedDatabase(): Promise<EmbeddedDatabase>;
71
+ drift(): Promise<readonly Finding[]>;
72
+ /**
73
+ * The other half of the migrations directory: a newest migration with no `.snapshot.json`, which
74
+ * is what `x db gen` refuses on. Separate from `drift()` because they are separate questions with
75
+ * separate remedies — one is "generate a migration", the other is "this migration is incomplete".
76
+ */
77
+ snapshots(): Promise<readonly Finding[]>;
78
+ /**
79
+ * What the app declared as its offline fallback, and which routes it really serves. A FACT and
80
+ * not a finding, because deciding is `offlineFallbackFinding`'s and this seam's whole job is
81
+ * reaching the disk — the same split `drift()` makes one question over.
82
+ */
83
+ offlineFallback(): Promise<OfflineFallbackFact>;
84
+ /**
85
+ * The app's `.sealed()` columns and the master keys this environment declares. A FACT, for the
86
+ * reason `offlineFallback` is one: loading the app and opening the secrets file is IO, and what
87
+ * a retired key beside a sealed column means is `sealedKeyFindings`' pure rule.
88
+ */
89
+ sealedKeys(): Promise<SealedKeysFact>;
90
+ /**
91
+ * What an upgrade left in the auth tables for an operator to finish: unsealed second-factor
92
+ * secrets, and tables no release reads. Asked of an external database only.
93
+ */
94
+ authStorage(): Promise<AuthStorageFact>;
95
+ /** The statement bound the session really reads, and what a pooler refused (`doctor-pooler.ts`). */
96
+ pooler(): Promise<PoolerFact>;
97
+ /** Each manifest whose `typescript` range lags the scaffold's (`doctor-typescript.ts`). */
98
+ typescript(): Promise<readonly TypescriptLag[]>;
99
+ /** With `database.rowSecurity` on, whether the serving role is exempt (`doctor-row-security.ts`). */
100
+ rowSecurity?(): Promise<readonly Finding[]>;
101
+ }
102
+
103
+ export function probeFor(
104
+ cwd: string,
105
+ bunVersion: string,
106
+ port: number,
107
+ // The environment `doctorPort` read `PORT` from, so `APP_URL` is judged against the same one.
108
+ env: Readonly<Record<string, string | undefined>> = process.env,
109
+ ): DoctorProbe {
110
+ const root = findAppRoot(cwd)?.dir;
111
+ return {
112
+ bunVersion,
113
+ root,
114
+ port,
115
+ appUrl: env['APP_URL'],
116
+ frameworkFindings: machineSecretFindings(env),
117
+ exists: (relativePath) => (root === undefined ? false : existsSync(join(root, relativePath))),
118
+ portFree,
119
+ database: () => probeDatabase(process.env['DATABASE_URL'], env),
120
+ // `root ?? cwd` because the walk needs a directory that exists; outside an app `runDoctor`
121
+ // returns on `X_NOT_IN_APP` before this is ever asked, so the value only has to be honest.
122
+ embeddedDatabase: async () => ({
123
+ selected: externalUrl(process.env['DATABASE_URL']) === undefined,
124
+ resolved: installedAbove(root ?? cwd, PGLITE_PACKAGE),
125
+ }),
126
+ drift: async () => (root === undefined ? [] : checkMigrationDrift(root)),
127
+ // The import half too: `X_CLI_UNEXPECTED` used to send a reader here and find this silent.
128
+ snapshots: async () =>
129
+ root === undefined
130
+ ? []
131
+ : [...(await unresolvedImportFindings(root)), ...(await checkMigrationSnapshots(root))],
132
+ // `routes: undefined` outside an app is "not judged", which is what the caller already is:
133
+ // `runDoctor` returns on `X_NOT_IN_APP` before this can be asked.
134
+ offlineFallback: async () =>
135
+ root === undefined ? { fallback: null, routes: undefined } : offlineFallbackProbe(root),
136
+ sealedKeys: async () =>
137
+ root === undefined ? { columns: undefined, keys: undefined } : sealedKeysProbe(root),
138
+ authStorage: () => authStorageProbe(process.env['DATABASE_URL'], env),
139
+ pooler: () => poolerProbe(process.env['DATABASE_URL'], env),
140
+ typescript: async () => (root === undefined ? [] : typescriptProbe(root)),
141
+ rowSecurity: async () =>
142
+ root === undefined ? [] : rowSecurityProbe(root, process.env['DATABASE_URL'], env),
143
+ };
144
+ }
145
+
146
+ /** What a load reports, narrowed to the one failure a doctor can name a repair for. */
147
+ const unresolvedImportFindings = async (root: string): Promise<readonly Finding[]> =>
148
+ (await loadApp(root)).findings.filter((finding) => finding.code === IMPORT_UNRESOLVED);
@@ -20,7 +20,7 @@ import {
20
20
  SQL_AUTH_LIMIT_TABLES,
21
21
  SQL_AUTH_SERVER_TABLES,
22
22
  SQL_TOTP_REPLAY_TABLE,
23
- } from '@ultimat3/auth';
23
+ } from '@ultimat3/auth/schema';
24
24
  import { FAILURES_TABLE, SQL_FAILURES_TABLE } from '@ultimat3/db';
25
25
  import { SQL_RATE_LIMIT_TABLE } from '@ultimat3/http';
26
26
  import { SQL_JOBS_TABLE } from '@ultimat3/jobs';
@@ -123,7 +123,9 @@ export const FRAMEWORK_SCHEMA: readonly FrameworkSchema[] = Object.freeze([
123
123
  * here on exactly the rule the rate-limit and audit rows already follow.
124
124
  *
125
125
  * `AUTH_TABLE_NAMES` rather than eight literals: @ultimat3/auth already publishes the list, and a
126
- * second copy is a second thing to keep right when a table is added.
126
+ * second copy is a second thing to keep right when a table is added. Every auth row reads
127
+ * `@ultimat3/auth/schema`, a leaf, for the admin row's reason: not one auth runtime module on
128
+ * `ROLE=migrate`'s path (#1051).
127
129
  */
128
130
  Object.freeze({
129
131
  pkg: '@ultimat3/auth',
@@ -5,6 +5,7 @@
5
5
 
6
6
  // why: `join` builds the host-separator path a glob entry is read at; Bun ships no path API.
7
7
  import { join } from 'node:path';
8
+ import { renderThrowable, stringField } from '@ultimat3/core';
8
9
 
9
10
  export interface GuardFile {
10
11
  /** App-root-relative POSIX path, so a finding names the file an author opens. */
@@ -31,6 +32,12 @@ export interface GuardSources {
31
32
  * (`X_PRERENDER_FAILED`, with the Sass error), never a guard's to repeat.
32
33
  */
33
34
  compiled(path: string): Promise<GuardStylesheet | undefined>;
35
+ /**
36
+ * Why `compiled(path)` is `undefined`: the compiler's (or the read's) first line, so a guard
37
+ * that reports a broken sheet names the error. `undefined` when the sheet compiles. Optional
38
+ * so a `GuardSources` an app built itself, before this existed, still satisfies the type.
39
+ */
40
+ compileError?(path: string): Promise<string | undefined>;
34
41
  }
35
42
 
36
43
  /** Path segments that are never the app's own source. */
@@ -49,7 +56,7 @@ export function guardSources(
49
56
  const texts = new Map<string, Promise<string>>();
50
57
  for (const file of seed) texts.set(file.path, Promise.resolve(file.source));
51
58
  const walks = new Map<string, Promise<readonly GuardFile[]>>();
52
- const sheets = new Map<string, Promise<GuardStylesheet | undefined>>();
59
+ const sheets = new Map<string, Promise<GuardStylesheet | string>>();
53
60
 
54
61
  const textOf = (path: string): Promise<string> => {
55
62
  let text = texts.get(path);
@@ -70,7 +77,8 @@ export function guardSources(
70
77
  return Promise.all(paths.map(async (path) => ({ path, text: await textOf(path) })));
71
78
  };
72
79
 
73
- const compile = async (path: string): Promise<GuardStylesheet | undefined> => {
80
+ /** The sheet, or the first line of why it is not one. */
81
+ const compile = async (path: string): Promise<GuardStylesheet | string> => {
74
82
  try {
75
83
  const source = await textOf(path);
76
84
  // Imported here, not at the top: Sass loads on the first compile, and a gate run whose
@@ -78,11 +86,24 @@ export function guardSources(
78
86
  const { compileStylesheet } = await import('@ultimat3/render/server');
79
87
  const { css, classes } = compileStylesheet(join(root, path), source);
80
88
  return { css, classes };
81
- } catch {
82
- return undefined;
89
+ } catch (error) {
90
+ // The compiler's own words: render's `X_PRERENDER_FAILED` carries them in its cause behind
91
+ // the absolute path, which names a temp root in a test and a different checkout in CI.
92
+ const absolute = join(root, path);
93
+ const said = (stringField(error, 'cause') ?? renderThrowable(error)).split('\n')[0] ?? '';
94
+ return said.replace(`${absolute} did not compile: `, '').replaceAll(absolute, path);
83
95
  }
84
96
  };
85
97
 
98
+ const compiledOnce = (path: string): Promise<GuardStylesheet | string> => {
99
+ let sheet = sheets.get(path);
100
+ if (sheet === undefined) {
101
+ sheet = compile(path);
102
+ sheets.set(path, sheet);
103
+ }
104
+ return sheet;
105
+ };
106
+
86
107
  return {
87
108
  files(glob) {
88
109
  let found = walks.get(glob);
@@ -92,13 +113,13 @@ export function guardSources(
92
113
  }
93
114
  return found;
94
115
  },
95
- compiled(path) {
96
- let sheet = sheets.get(path);
97
- if (sheet === undefined) {
98
- sheet = compile(path);
99
- sheets.set(path, sheet);
100
- }
101
- return sheet;
116
+ async compiled(path) {
117
+ const sheet = await compiledOnce(path);
118
+ return typeof sheet === 'string' ? undefined : sheet;
119
+ },
120
+ async compileError(path) {
121
+ const sheet = await compiledOnce(path);
122
+ return typeof sheet === 'string' ? sheet : undefined;
102
123
  },
103
124
  };
104
125
  }
@@ -59,7 +59,7 @@ export function bareThrows(files: readonly SourceFile[]): readonly Finding[] {
59
59
  findings.push({
60
60
  code: CODE,
61
61
  cause: \`\${file.path}:\${line} throws a bare \${thrown} — it reaches its reader as a stack trace with no code, no cause and nothing to run\`,
62
- fix: \`declare the failure in \${file.path} with defineError({ code, title, status, cause, fix }) from @ultimat3/core — an X_SCREAMING_SNAKE code and a fix naming a command — and throw its class, then: x verify\`,
62
+ fix: \`declare the failure in \${file.path} with defineError({ code, title, status, cause, fix }) from @ultimat3/core/page — an X_SCREAMING_SNAKE code and a fix naming a command — and throw its class, then: x verify\`,
63
63
  at: file.path,
64
64
  });
65
65
  }
@@ -1,7 +1,7 @@
1
- // The `error-declared` guard `x new` ships: an app code is declared with `defineError`, never a
2
- // handwritten `UltimateError` subclass or a literal-coded `new UltimateError`. Those forms take a
3
- // title, a status and a class in three places, and nothing made the status get written — so the
4
- // reference app's "post not found" answered 500, hid its cause and paged the error monitor.
1
+ // The `error-declared` guard `x new` ships: an app code is declared with `defineError` from
2
+ // `@ultimat3/core/page`, never a handwritten `UltimateError` subclass or a literal-coded `new
3
+ // UltimateError` (the reference app's "post not found" answered 500), and never from the barrel,
4
+ // which carried both framework titles tables into every island that threw (+11 kB on three routes).
5
5
 
6
6
  import { guardCode } from './guard';
7
7
  import type { GeneratedFile } from './naming';
@@ -14,6 +14,8 @@ const source =
14
14
  (): string => `// error-declared: an app code is declared once, with defineError — its title, its status and its class.
15
15
  // \`x verify\` discovers every file in \`guards/\` and runs its \`guard\` inside the \`boundaries\`
16
16
  // step — nothing registers this file, so nothing can forget to. Delete it to drop the rule.
17
+ // defineError is imported from @ultimat3/core/page: an errors module is shared by actions and
18
+ // islands, and the barrel carries the framework's titles tables into every island that throws.
17
19
  //
18
20
  // Known limits, both read by nothing short of a type checker: an alias by assignment
19
21
  // (const Base = UltimateError) and a shorthand key whose value is a literal elsewhere
@@ -31,6 +33,12 @@ const NAMESPACE_IMPORT =
31
33
  /\\bimport\\s+\\*\\s+as\\s+([A-Za-z_$][\\w$]*)\\s+from\\s*['"]@ultimat3\\/core(?:\\/page)?['"]/g;
32
34
  const ALIAS = /^\\s*UltimateError\\s+as\\s+([A-Za-z_$][\\w$]*)\\s*$/;
33
35
 
36
+ /** The barrel alone — never its page subpath — and defineError in a named list, aliased or not. */
37
+ const BARREL_NAMED = /\\bimport\\s+\\{([^}]*)\\}\\s*from\\s*['"]@ultimat3\\/core['"]/g;
38
+ const BARREL_NAMESPACE =
39
+ /\\bimport\\s+\\*\\s+as\\s+([A-Za-z_$][\\w$]*)\\s+from\\s*['"]@ultimat3\\/core['"]/g;
40
+ const DEFINE_ERROR = /^\\s*defineError(?:\\s+as\\s+[A-Za-z_$][\\w$]*)?\\s*$/;
41
+
34
42
  /** A literal code as the object's own key — bare or quoted — read where the walk below stands. */
35
43
  const LITERAL_CODE = /^(?:code|'code'|"code")\\s*:\\s*['"\`]/;
36
44
 
@@ -108,10 +116,34 @@ const literalCodeIn = (text: string, open: number): boolean => {
108
116
  const finding = (file: SourceFile, line: number, what: string): Finding => ({
109
117
  code: CODE,
110
118
  cause: \`\${file.path}:\${line} \${what} — the title, the HTTP status and the class are then declared apart, and a code with no status answers 500 and hides its cause\`,
111
- fix: \`rewrite it in \${file.path} as defineError({ code, title, status, cause, fix }) from @ultimat3/core (offSocket: true for a code no response carries), then: x verify\`,
119
+ fix: \`rewrite it in \${file.path} as defineError({ code, title, status, cause, fix }) from @ultimat3/core/page (offSocket: true for a code no response carries), then: x verify\`,
120
+ at: file.path,
121
+ });
122
+
123
+ const barrelFinding = (file: SourceFile, line: number): Finding => ({
124
+ code: CODE,
125
+ cause: \`\${file.path}:\${line} takes defineError from the @ultimat3/core barrel — every island that throws the code then carries the framework's titles table, ~5.5 kB it never reads\`,
126
+ fix: \`import { defineError } from '@ultimat3/core/page' in \${file.path} — the same function, without the table — then: x verify\`,
112
127
  at: file.path,
113
128
  });
114
129
 
130
+ /** Each line that reaches defineError through the barrel: a named import, or a namespace's member. */
131
+ const barrelDefineErrorLines = (text: string): readonly number[] => {
132
+ const lines: number[] = [];
133
+ for (const match of text.matchAll(BARREL_NAMED)) {
134
+ if ((match[1] ?? '').split(',').some((part) => DEFINE_ERROR.test(part))) {
135
+ lines.push(lineOf(text, match.index));
136
+ }
137
+ }
138
+ for (const match of text.matchAll(BARREL_NAMESPACE)) {
139
+ const member = nameSource([\`\${match[1] ?? ''}.defineError\`]);
140
+ for (const use of text.matchAll(new RegExp(\`\\\\b\${member}\\\\b\`, 'g'))) {
141
+ lines.push(lineOf(text, use.index));
142
+ }
143
+ }
144
+ return lines;
145
+ };
146
+
115
147
  /** Pure — the caller does the I/O — so the rule is testable without a filesystem. */
116
148
  export function undeclaredErrors(files: readonly SourceFile[]): readonly Finding[] {
117
149
  const found: { readonly path: string; readonly line: number; readonly finding: Finding }[] = [];
@@ -122,6 +154,9 @@ export function undeclaredErrors(files: readonly SourceFile[]): readonly Finding
122
154
  const line = lineOf(text, index);
123
155
  found.push({ path: file.path, line, finding: finding(file, line, what) });
124
156
  };
157
+ for (const line of barrelDefineErrorLines(text)) {
158
+ found.push({ path: file.path, line, finding: barrelFinding(file, line) });
159
+ }
125
160
  for (const match of text.matchAll(new RegExp(\`\\\\bextends\\\\s+(?:\${names})\\\\b\`, 'g'))) {
126
161
  push(match.index, 'subclasses UltimateError by hand');
127
162
  }
@@ -241,6 +276,17 @@ unitTest(
241
276
  },
242
277
  );
243
278
 
279
+ unitTest('defineError from the barrel is refused; from the page subpath it is the rule', () => {
280
+ const declared =
281
+ "defineError({ code: 'X_NOT_FOUND', title: 't', status: 404, cause: 'c', fix: 'x' });";
282
+ expect(
283
+ undeclaredErrors(file(\`import { defineError } from '@ultimat3/core';\\n\${declared}\`)),
284
+ ).toHaveLength(1);
285
+ expect(
286
+ undeclaredErrors(file(\`import { defineError } from '@ultimat3/core/page';\\n\${declared}\`)),
287
+ ).toEqual([]);
288
+ });
289
+
244
290
  unitTest('an alias from the page subpath and a quoted code key are the same rule', () => {
245
291
  const paged = "import { UltimateError as PageError } from '@ultimat3/core/page';\\n";
246
292
  expect(
@@ -148,8 +148,9 @@ export const guard: Guard = {
148
148
  // \`{apps/web,packages/ui}/**/*.tsx\` each match ZERO files, where \`apps/*/{site,app}/**/*.tsx\`
149
149
  // matches 17 — so folding these into one line silently turns the guard off, which is worse than
150
150
  // the hole it closes. A LEADING group is fine and the stylesheet guards here rely on it:
151
- // \`{apps,packages}/**/*.scss\` matches all 15.
152
- for (const pattern of ['apps/*/{site,app}/**/*.tsx', 'packages/*/src/**/*.tsx']) {
151
+ // \`{apps,packages}/**/*.scss\` matches all 15. \`shared/\` is read too: a component there renders
152
+ // on every page that imports it, and leaving it out was a directory the rule never saw.
153
+ for (const pattern of ['apps/*/{site,app,shared}/**/*.tsx', 'packages/*/src/**/*.tsx']) {
153
154
  // The run's ONE read: every guard asking for these two globs shares the walk.
154
155
  for (const file of await sources.files(pattern)) {
155
156
  if (/\\.test\\.tsx?$/.test(file.path)) continue;
@@ -0,0 +1,74 @@
1
+ // The source text of `bindsLocally()`, spliced into each shipped guard that refuses a call to a
2
+ // global by name (`confirm(`, `fetch(`, `setInterval(`): a file that declares its own binding of
3
+ // that name calls its own function, never the global. One copy here, so the three guards read a
4
+ // binding the same way. `String.raw` keeps the regexes as written; the text holds no backtick.
5
+
6
+ export const LOCAL_BINDING_SOURCE = String.raw`const DECLARED = /\b(?:const|let|var|class|function\s*\*?)\s+([A-Za-z_$][\w$]*)/g;
7
+ const ARROW_PARAMETER = /(?<![\w$.])([A-Za-z_$][\w$]*)\s*=>/g;
8
+ const IMPORT_CLAUSE = /\bimport\s+([^;]*?)\bfrom\b/g;
9
+ /** A name an import clause binds: 'a', '{ a }', '* as a', '{ b as a }' — never the 'b' of 'b as a'. */
10
+ const IMPORTED = /(?<![\w$])([A-Za-z_$][\w$]*)(?![\w$])(?!\s+as\b)/g;
11
+ const IDENTIFIER = /(?<![\w$.])[A-Za-z_$][\w$]*(?![\w$])/g;
12
+ /** After a pattern's closing bracket: '=' closes a destructuring, '=>' or a body a parameter list. */
13
+ const PATTERN_END = /^\s*(?::[^=;{}()]*?)?\s*(=>|=(?!=)|\{)/;
14
+ const CONDITION = /\b(?:if|for|while|switch|with)\s*$/;
15
+ const OPENERS = '([{';
16
+ const CLOSERS = ')]}';
17
+
18
+ /** The index of the bracket closing the one at 'open', or the end of the text. */
19
+ const closing = (text: string, open: number): number => {
20
+ let depth = 0;
21
+ for (let index = open; index < text.length; index += 1) {
22
+ if (OPENERS.includes(text[index] ?? '')) depth += 1;
23
+ if (CLOSERS.includes(text[index] ?? '') && --depth === 0) return index;
24
+ }
25
+ return text.length;
26
+ };
27
+
28
+ /** The brackets enclosing 'at', innermost first, up to and including the first parenthesis. */
29
+ const enclosing = (text: string, at: number): readonly number[] => {
30
+ const opens: number[] = [];
31
+ let depth = 0;
32
+ for (let index = at - 1; index >= 0; index -= 1) {
33
+ const char = text[index] ?? '';
34
+ if (CLOSERS.includes(char)) depth += 1;
35
+ else if (OPENERS.includes(char) && depth > 0) depth -= 1;
36
+ else if (OPENERS.includes(char)) {
37
+ opens.push(index);
38
+ if (char === '(') break;
39
+ }
40
+ }
41
+ return opens;
42
+ };
43
+
44
+ /** Whether the occurrence at 'at' sits in a parameter list or a destructuring pattern. */
45
+ const inPattern = (text: string, at: number, name: string): boolean => {
46
+ const opens = enclosing(text, at);
47
+ // '{ name: other }' binds 'other', and '(name: Type)' is a parameter: a key only in braces.
48
+ if (text[opens[0] ?? -1] === '{' && /^\s*:/.test(text.slice(at + name.length))) return false;
49
+ for (const open of opens) {
50
+ const close = closing(text, open);
51
+ const end = PATTERN_END.exec(text.slice(close + 1, close + 200))?.[1];
52
+ if (end === undefined) continue;
53
+ if (text[open] !== '(') return end === '=';
54
+ return end !== '=' && !CONDITION.test(text.slice(Math.max(0, open - 10), open));
55
+ }
56
+ return false;
57
+ };
58
+
59
+ /**
60
+ * Whether the file binds 'name' itself — declared, imported, a parameter or destructured — so a
61
+ * bare 'name(' is its own function and not the global. File-wide, not scoped: a guard is a regex.
62
+ */
63
+ const bindsLocally = (text: string, name: string): boolean => {
64
+ for (const match of text.matchAll(DECLARED)) if (match[1] === name) return true;
65
+ for (const match of text.matchAll(ARROW_PARAMETER)) if (match[1] === name) return true;
66
+ for (const clause of text.matchAll(IMPORT_CLAUSE)) {
67
+ for (const match of (clause[1] ?? '').matchAll(IMPORTED)) if (match[1] === name) return true;
68
+ }
69
+ for (const match of text.matchAll(IDENTIFIER)) {
70
+ if (match[0] !== name || /^\s*\(/.test(text.slice(match.index + name.length))) continue;
71
+ if (inPattern(text, match.index, name)) return true;
72
+ }
73
+ return false;
74
+ };`;
@@ -4,6 +4,7 @@
4
4
  // one way. A `// why:` on the call's line, or the line above it, admits a call that is not that.
5
5
 
6
6
  import { guardCode } from './guard';
7
+ import { LOCAL_BINDING_SOURCE } from './guard-local-binding';
7
8
  import type { GeneratedFile } from './naming';
8
9
 
9
10
  /** Derived from the guard's name, never a literal: an `X_*` literal here is a FRAMEWORK code. */
@@ -19,7 +20,8 @@ const source =
19
20
  // translated, styled or refused, and it blocks the page while it is up. \`ConfirmDialog\` from
20
21
  // \`@ultimat3/ui\` focuses Cancel, posts natively with scripting off and stays open on a refusal.
21
22
  // Read: a bare, \`window.\`, \`self.\` or \`globalThis.\` \`confirm(\` in a \`*.island.tsx\` or anywhere
22
- // under \`apps/web/\`. Admitted: a \`// why:\` on the call's line or the line above it.
23
+ // under \`apps/web/\`. Not read: a bare \`confirm(\` in a file that binds its own \`confirm\`
24
+ // (declared, imported, a parameter, destructured). Admitted: a \`// why:\` on the line or above it.
23
25
 
24
26
  import type { Finding, Guard } from '@ultimat3/cli';
25
27
 
@@ -35,6 +37,8 @@ export interface SourceFile {
35
37
  const CALL = /(?<![\\w$.])(?<!function\\s+)(?:(?:globalThis|window|self)\\s*\\.\\s*)?confirm\\s*\\(/g;
36
38
  const WHY = /\\/\\/\\s*why:/;
37
39
 
40
+ ${LOCAL_BINDING_SOURCE}
41
+
38
42
  /** Comments and string bodies blanked IN PLACE, so a line number still points at the source. */
39
43
  const blank = (text: string): string =>
40
44
  text
@@ -50,7 +54,10 @@ export function nativeConfirms(files: readonly SourceFile[]): readonly Finding[]
50
54
  for (const file of files) {
51
55
  const lines = file.source.split('\\n');
52
56
  const text = blank(file.source);
57
+ const local = bindsLocally(text, 'confirm');
53
58
  for (const match of text.matchAll(CALL)) {
59
+ // A bare call to the file's own \`confirm\` is not the dialog; \`window.confirm(\` always is.
60
+ if (local && match[0].startsWith('confirm')) continue;
54
61
  const line = text.slice(0, match.index).split('\\n').length;
55
62
  if (WHY.test(lines[line - 1] ?? '') || WHY.test(lines[line - 2] ?? '')) continue;
56
63
  const at = \`\${file.path}:\${line}\`;
@@ -117,6 +124,14 @@ unitTest('a comment, a string, a method and a definition are not calls', () => {
117
124
  expect(nativeConfirms(file('function confirm(input) { return input; }'))).toEqual([]);
118
125
  });
119
126
 
127
+ unitTest('a confirm the file binds itself is its own; window.confirm( never is', () => {
128
+ expect(nativeConfirms(file('const confirm = async () => {};\\nvoid confirm();'))).toEqual([]);
129
+ expect(nativeConfirms(file('const ask = (confirm) => confirm();'))).toEqual([]);
130
+ expect(nativeConfirms(file("import { confirm } from './x';\\nconfirm('Delete?');"))).toEqual([]);
131
+ expect(nativeConfirms(file("let confirm;\\nwindow.confirm('Delete?');"))).toHaveLength(1);
132
+ expect(nativeConfirms(file("const { confirm: ask } = deps;\\nconfirm('x');"))).toHaveLength(1);
133
+ });
134
+
120
135
  unitTest('islands and apps/web are read; tests and other packages are not', () => {
121
136
  expect(readsFile('apps/web/app/posts/page.tsx')).toBe(true);
122
137
  expect(readsFile('packages/ui/src/delete.island.tsx')).toBe(true);
@@ -4,6 +4,7 @@
4
4
  // signal it stays legal: the guard cannot prove the other properties, and outbound() is the way.
5
5
 
6
6
  import { guardCode } from './guard';
7
+ import { LOCAL_BINDING_SOURCE } from './guard-local-binding';
7
8
  import type { GeneratedFile } from './naming';
8
9
 
9
10
  /** Derived from the guard's name, never a literal: an `X_*` literal here is a FRAMEWORK code. */
@@ -15,9 +16,11 @@ const source =
15
16
  // \`x verify\` discovers every file in \`guards/\` and runs its \`guard\` inside the \`boundaries\`
16
17
  // step — nothing registers this file, so nothing can forget to. Delete it to drop the rule.
17
18
  //
18
- // Read: a bare or \`globalThis.\` \`fetch(\` call. Not read: an injected \`deps.fetch(\`, a method
19
- // DEFINITION (\`fetch(request) {\`, Bun.serve's handler), a test, or an island (a browser has no
20
- // request to outlive). Options passed as a variable read as unsignalled: spread them and add the key.
19
+ // Read: a bare or \`globalThis.\` \`fetch(\` call. Not read: an injected \`deps.fetch(\`, a bare
20
+ // \`fetch(\` in a file that binds its own \`fetch\` (declared, imported, a parameter, destructured),
21
+ // a method DEFINITION (\`fetch(request) {\`, Bun.serve's handler), a test, or an island (a browser
22
+ // has no request to outlive). Options passed as a variable read as unsignalled: spread them and add
23
+ // the key.
21
24
 
22
25
  import type { Finding, Guard } from '@ultimat3/cli';
23
26
 
@@ -33,6 +36,8 @@ export interface SourceFile {
33
36
  const CALL = /(?<![\\w$.])(?:globalThis\\s*\\.\\s*)?fetch\\s*\\(/g;
34
37
  const SIGNAL = /(?<![\\w$.])signal\\s*[:,}]/g;
35
38
 
39
+ ${LOCAL_BINDING_SOURCE}
40
+
36
41
  /** Comments and string bodies blanked IN PLACE, so a line number still points at the source. */
37
42
  const blank = (text: string): string =>
38
43
  text
@@ -72,7 +77,10 @@ export function rawFetches(files: readonly SourceFile[]): readonly Finding[] {
72
77
  const findings: Finding[] = [];
73
78
  for (const file of files) {
74
79
  const text = blank(file.source);
80
+ const local = bindsLocally(text, 'fetch');
75
81
  for (const match of text.matchAll(CALL)) {
82
+ // A bare call to the file's own \`fetch\` is an injected client; \`globalThis.fetch(\` never is.
83
+ if (local && match[0].startsWith('fetch')) continue;
76
84
  const open = match.index + match[0].length - 1;
77
85
  const close = closeOf(text, open);
78
86
  const after = text.slice(close + 1).trimStart();
@@ -4,6 +4,7 @@
4
4
  // A `// why:` on the call's line, or the line above it, admits a tick that is not a read.
5
5
 
6
6
  import { guardCode } from './guard';
7
+ import { LOCAL_BINDING_SOURCE } from './guard-local-binding';
7
8
  import type { GeneratedFile } from './naming';
8
9
 
9
10
  /** Derived from the guard's name, never a literal: an `X_*` literal here is a FRAMEWORK code. */
@@ -19,7 +20,8 @@ const source =
19
20
  // for a 401 forever. \`visibleInterval(run, ms)\` from \`@ultimat3/core/page\` makes no call while the
20
21
  // tab is hidden, one when it is shown, and stops at the first lost session. Read: a bare,
21
22
  // \`window.\`, \`self.\` or \`globalThis.\` \`setInterval(\` in a \`*.island.tsx\`. Admitted: a \`// why:\` on
22
- // the call's line or the line above it — an animation tick is not a read.
23
+ // the call's line or the line above it — an animation tick is not a read. Not read: a bare
24
+ // \`setInterval(\` in a file that binds its own (declared, imported, a parameter, destructured).
23
25
 
24
26
  import type { Finding, Guard } from '@ultimat3/cli';
25
27
 
@@ -35,6 +37,8 @@ export interface SourceFile {
35
37
  const CALL = /(?<![\\w$.])(?:(?:globalThis|window|self)\\s*\\.\\s*)?setInterval\\s*\\(/g;
36
38
  const WHY = /\\/\\/\\s*why:/;
37
39
 
40
+ ${LOCAL_BINDING_SOURCE}
41
+
38
42
  /** Comments and string bodies blanked IN PLACE, so a line number still points at the source. */
39
43
  const blank = (text: string): string =>
40
44
  text
@@ -50,7 +54,10 @@ export function rawIntervals(files: readonly SourceFile[]): readonly Finding[] {
50
54
  for (const file of files) {
51
55
  const lines = file.source.split('\\n');
52
56
  const text = blank(file.source);
57
+ const local = bindsLocally(text, 'setInterval');
53
58
  for (const match of text.matchAll(CALL)) {
59
+ // A bare call to the file's own \`setInterval\` is not the timer; \`window.\` always is.
60
+ if (local && match[0].startsWith('setInterval')) continue;
54
61
  const line = text.slice(0, match.index).split('\\n').length;
55
62
  if (WHY.test(lines[line - 1] ?? '') || WHY.test(lines[line - 2] ?? '')) continue;
56
63
  const at = \`\${file.path}:\${line}\`;
@@ -15,7 +15,9 @@ const source =
15
15
  // step — nothing registers this file, so nothing can forget to. Delete it to drop the rule.
16
16
  //
17
17
  // A keyword is not a literal: \`linear\`, \`ease\`, \`infinite\` and \`0s\` are never reported, and a
18
- // multiple of a token is still the token — \`calc(#{tokens.duration(slower)} * 2)\`.
18
+ // multiple of a token is still the token — \`calc(#{tokens.duration(slower)} * 2)\`. A custom
19
+ // property is read too: \`--ease: cubic-bezier(…)\` is a second scale that every \`var(--ease)\` then
20
+ // moves at. The scale's own properties come from \`@ultimat3/ui\`, which this never scans.
19
21
 
20
22
  import type { Finding, Guard } from '@ultimat3/cli';
21
23
 
@@ -58,7 +60,8 @@ const namespaceOf = (scss: string): string =>
58
60
 
59
61
  /** A declaration; a Sass \`#{…}\` interpolation is a value that carries braces. */
60
62
  const DECLARATION = /(?<![\\w$-])([\\w-]+)\\s*:\\s*((?:#\\{[^}]*\\}|[^;{}])+)/g;
61
- const MOTION_PROPERTY = /^(?:transition|animation)(?:-|$)/;
63
+ /** A motion property, or a custom property — whose value Sass does not evaluate, hence \`#{…}\`. */
64
+ const MOTION_PROPERTY = /^(?:transition|animation)(?:-|$)|^--/;
62
65
  /** A token read, with its argument list: \`tokens.duration(fast)\`, \`var(--duration-fast)\`. */
63
66
  const TOKEN_CALL = /(?<![\\w-])(?:var|(?:[\\w-]+\\.)[\\w-]+|duration|easing)\\([^()]*\\)/g;
64
67
  const TIME = /(?<![\\w.#-])(\\d*\\.?\\d+)(ms|s)\\b/g;
@@ -85,6 +88,8 @@ export function rawMotion(files: readonly StyleFile[]): readonly Finding[] {
85
88
  const property = match[1] ?? '';
86
89
  if (!MOTION_PROPERTY.test(property)) continue;
87
90
  const value = (match[2] ?? '').trim().replaceAll(/\\s+/g, ' ');
91
+ const custom = property.startsWith('--');
92
+ const token = (call: string): string => (custom ? \`#{\${call}}\` : call);
88
93
  const read = value.replaceAll(TOKEN_CALL, (call) => ' '.repeat(call.length));
89
94
  const literals: string[] = [];
90
95
  let written = '';
@@ -98,14 +103,18 @@ export function rawMotion(files: readonly StyleFile[]): readonly Finding[] {
98
103
  ...[...read.matchAll(CURVE)].map((curve) => ({
99
104
  index: curve.index,
100
105
  text: curve[0],
101
- token: \`\${ns}.easing(\${EASINGS[(curve[1] ?? '').replaceAll(/\\s+/g, '')] ?? 'out'})\`,
106
+ token: token(
107
+ \`\${ns}.easing(\${EASINGS[(curve[1] ?? '').replaceAll(/\\s+/g, '')] ?? 'out'})\`,
108
+ ),
102
109
  })),
103
110
  ...[...read.replaceAll(CURVE, (curve) => ' '.repeat(curve.length)).matchAll(TIME)]
104
111
  .filter((time) => Number(time[1]) !== 0)
105
112
  .map((time) => ({
106
113
  index: time.index,
107
114
  text: time[0],
108
- token: \`\${ns}.duration(\${durationFor(Number(time[1]) * (time[2] === 's' ? 1000 : 1))})\`,
115
+ token: token(
116
+ \`\${ns}.duration(\${durationFor(Number(time[1]) * (time[2] === 's' ? 1000 : 1))})\`,
117
+ ),
109
118
  })),
110
119
  ].sort((a, b) => a.index - b.index);
111
120
  for (const hit of hits) {
@@ -184,6 +193,13 @@ unitTest('one declaration is one finding, with every literal in it rewritten', (
184
193
  );
185
194
  });
186
195
 
196
+ unitTest('a custom property holding a raw curve or time is refused, the fix interpolated', () => {
197
+ expect(fixes(':root { --ease: cubic-bezier(0, 0, 1, 1); }')[0]).toStartWith(
198
+ '--ease: #{tokens.easing(out)} — ',
199
+ );
200
+ expect(fixes(':root { --wait: 0.4s; --gap: 12px; --ok: var(--duration-fast); }')).toHaveLength(1);
201
+ });
202
+
187
203
  unitTest('the fix speaks the namespace the sheet uses the tokens under', () => {
188
204
  const scss = "@use '../shared/tokens' as t;\\n.a { transition-duration: 120ms; }";
189
205
  expect(fixes(scss)[0]).toStartWith('transition-duration: t.duration(fast) — ');