@ultimat3/cli 31.38.1 → 31.40.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.
Files changed (55) hide show
  1. package/README.md +1 -1
  2. package/package.json +29 -29
  3. package/src/cmd-errors-guards.ts +69 -0
  4. package/src/cmd-errors.ts +11 -4
  5. package/src/cmd-exercise.ts +3 -2
  6. package/src/cmd-new-spec.ts +6 -1
  7. package/src/cmd-new-target.ts +73 -0
  8. package/src/cmd-new.ts +21 -21
  9. package/src/cmd-repro.ts +2 -1
  10. package/src/codemods/ci-e2e-browser.ts +7 -1
  11. package/src/codemods/ci-services-env.ts +25 -0
  12. package/src/codemods/docs-env-guard.ts +31 -0
  13. package/src/codemods/index.ts +4 -0
  14. package/src/dev-boot.ts +3 -0
  15. package/src/dev-rebuild-isr.ts +17 -0
  16. package/src/dev-rebuild.ts +14 -5
  17. package/src/error-contract.ts +25 -5
  18. package/src/exercise-findings-unreached.ts +94 -0
  19. package/src/exercise-findings.ts +9 -57
  20. package/src/exercise-route-api.ts +3 -4
  21. package/src/fix-sequence.ts +28 -3
  22. package/src/framework-schema-wait.ts +41 -2
  23. package/src/generate-feature-required.ts +40 -3
  24. package/src/generate-kinds.ts +23 -2
  25. package/src/guards-shipped-names.ts +1 -0
  26. package/src/messages.ts +5 -0
  27. package/src/serve-boot.ts +4 -0
  28. package/src/templates/action.ts +7 -2
  29. package/src/templates/github/ci.yml.ts +3 -2
  30. package/src/templates/guard-raw-colour.ts +88 -13
  31. package/src/templates/guard-released-forms.ts +9 -3
  32. package/src/templates/guard-undeclared-env.ts +192 -0
  33. package/src/templates/guard-untranslated-string.ts +29 -1
  34. package/src/templates/policy.ts +7 -1
  35. package/src/templates/query.ts +8 -6
  36. package/src/templates/scaffold-docs.ts +1 -0
  37. package/src/templates/scaffold-guards.ts +4 -1
  38. package/src/templates/scaffold-i18n.ts +1 -1
  39. package/src/templates/scaffold-repo.ts +26 -24
  40. package/src/templates/shapes/agent.ts +2 -2
  41. package/src/templates/shapes/offline.ts +1 -1
  42. package/src/templates/shapes/realtime.ts +2 -2
  43. package/src/templates/shapes/saas.ts +5 -4
  44. package/src/templates/slice-foundation.ts +29 -9
  45. package/src/test-workers.ts +3 -1
  46. package/src/workspace-checks.ts +4 -1
  47. package/wiki/Actions.md +1 -1
  48. package/wiki/CLI-Reference.md +1 -1
  49. package/wiki/Getting-Started.md +1 -1
  50. package/wiki/Installation.md +2 -2
  51. package/wiki/Money.md +19 -4
  52. package/wiki/Queries-And-Live-Queries.md +4 -4
  53. package/wiki/Realtime.md +2 -2
  54. package/wiki/Tutorial-04-Jobs-And-Realtime.md +3 -2
  55. package/wiki/Upgrading.md +2 -1
@@ -16,7 +16,8 @@ const NAME = 'raw-colour';
16
16
  const CODE = guardCode(NAME);
17
17
 
18
18
  const source =
19
- (): string => `// raw-colour: every colour in this app is a semantic token, so dark theme is not a later project.
19
+ (): string => `// raw-colour: every colour in this app is a semantic token, so dark theme is not a later project —
20
+ // in a stylesheet and in a component's inline \`style\` alike.
20
21
  // \`x verify\` discovers every file in \`guards/\` and runs its \`guard\` inside the \`boundaries\`
21
22
  // step — nothing registers this file, so nothing can forget to. Delete it to drop the rule.
22
23
 
@@ -67,16 +68,18 @@ const unquote = (value: string): string => value.replaceAll(/'[^']*'|"[^"]*"/g,
67
68
  const lineOf = (text: string, index: number): number => text.slice(0, index).split('\\n').length;
68
69
 
69
70
  /**
70
- * The BALANCED argument list of the call whose \`(\` sits at \`open\`. \`var(--x)\` nests, so reading
71
- * to the first \`)\` cuts \`rgb(var(--color-bg) / 1)\` in half and every rule below reads the wrong
72
- * text. \`undefined\` when the call is never closed — a value the declaration scan truncated.
71
+ * The BALANCED group whose \`(\` or \`{\` sits at \`open\`. \`var(--x)\` nests, so reading to the
72
+ * first \`)\` cuts \`rgb(var(--color-bg) / 1)\` in half and every rule below reads the wrong text.
73
+ * \`undefined\` when the group is never closed — a value the declaration scan truncated.
73
74
  */
74
75
  const argumentsAt = (value: string, open: number): string | undefined => {
76
+ const opener = value.charAt(open);
77
+ const closer = opener === '{' ? '}' : ')';
75
78
  let depth = 0;
76
79
  for (let index = open; index < value.length; index += 1) {
77
80
  const character = value.charAt(index);
78
- if (character === '(') depth += 1;
79
- else if (character === ')') {
81
+ if (character === opener) depth += 1;
82
+ else if (character === closer) {
80
83
  depth -= 1;
81
84
  if (depth === 0) return value.slice(open + 1, index);
82
85
  }
@@ -130,19 +133,29 @@ const literalChannelCall = (value: string): string | undefined => {
130
133
  return undefined;
131
134
  };
132
135
 
136
+ /** The raw colour a value names, rendered whole for the finding, or \`undefined\`. */
137
+ const rawLiteral = (value: string): string | undefined =>
138
+ HEX.exec(value)?.[0] ?? literalChannelCall(value) ?? NAMED.exec(value)?.[0];
139
+
140
+ /** Every \`property: value\` declaration of a CSS text, quoted text masked, with its offset. */
141
+ const declarations = (css: string) =>
142
+ [...css.matchAll(DECLARATION)].map((match) => ({
143
+ property: match[1] ?? '',
144
+ value: unquote(match[2] ?? ''),
145
+ index: match.index,
146
+ }));
147
+
133
148
  /** Pure — the caller does the I/O — so the rule is testable without a filesystem. */
134
149
  export function rawColours(files: readonly StyleFile[]): readonly Finding[] {
135
150
  const findings: Finding[] = [];
136
151
  for (const file of files) {
137
152
  const scss = blankComments(file.scss);
138
- for (const match of scss.matchAll(DECLARATION)) {
139
- const property = match[1] ?? '';
140
- const value = unquote(match[2] ?? '');
141
- const literal = HEX.exec(value)?.[0] ?? literalChannelCall(value) ?? NAMED.exec(value)?.[0];
153
+ for (const { property, value, index } of declarations(scss)) {
154
+ const literal = rawLiteral(value);
142
155
  if (literal === undefined) continue;
143
156
  findings.push({
144
157
  code: CODE,
145
- cause: \`\${file.path}:\${lineOf(scss, match.index)} sets \${property} to the raw colour \${literal} — a value no theme can restate, so dark theme renders it unchanged\`,
158
+ cause: \`\${file.path}:\${lineOf(scss, index)} sets \${property} to the raw colour \${literal} — a value no theme can restate, so dark theme renders it unchanged\`,
146
159
  fix: \`replace \${literal} in \${file.path} with tokens.role('fg'), tokens.role('bg') or the role this element means, then: x verify\`,
147
160
  at: file.path,
148
161
  });
@@ -151,12 +164,65 @@ export function rawColours(files: readonly StyleFile[]): readonly Finding[] {
151
164
  return findings;
152
165
  }
153
166
 
167
+ /** A JSX \`style\` attribute: a quoted CSS string, or an expression the brace scan reads whole. */
168
+ const STYLE_ATTRIBUTE = /(?<![\\w-])style=(?:"([^"]*)"|'([^']*)'|(?=\\{))/g;
169
+ /** One \`key: 'value'\` of a style object; a value that is not a string literal is not typed. */
170
+ const STYLE_ENTRY = /['"]?([\\w-]+)['"]?\\s*:\\s*(['"\`])((?:(?!\\2).)*)\\2/g;
171
+
172
+ /** What a \`style\` attribute sets: a CSS string's declarations, or a style object's entries. */
173
+ const styleEntries = (text: string, attribute: RegExpMatchArray) => {
174
+ const css = attribute[1] ?? attribute[2];
175
+ if (css !== undefined) return declarations(css);
176
+ const expression = argumentsAt(text, attribute.index + attribute[0].length)?.trim() ?? '';
177
+ // \`style={'color: red'}\` is the string form behind braces.
178
+ if (/^['"].*['"]$/s.test(expression)) return declarations(expression.slice(1, -1));
179
+ return [...expression.matchAll(STYLE_ENTRY)].map((entry) => ({
180
+ property: entry[1] ?? '',
181
+ value: entry[2] === '\`' ? (entry[3] ?? '').replaceAll(/\\$\\{[^}]*\\}/g, ' ') : (entry[3] ?? ''),
182
+ index: 0,
183
+ }));
184
+ };
185
+
186
+ /** The same rule over a component's inline \`style\`, the colour a stylesheet would have held. */
187
+ export function inlineColours(
188
+ files: readonly { readonly path: string; readonly source: string }[],
189
+ ): readonly Finding[] {
190
+ const findings: Finding[] = [];
191
+ for (const file of files) {
192
+ const text = blankComments(file.source);
193
+ for (const attribute of text.matchAll(STYLE_ATTRIBUTE)) {
194
+ for (const { property, value } of styleEntries(text, attribute)) {
195
+ const literal = rawLiteral(value);
196
+ if (literal === undefined) continue;
197
+ findings.push({
198
+ code: CODE,
199
+ cause: \`\${file.path}:\${lineOf(text, attribute.index)} sets \${property} to the raw colour \${literal} in an inline style — a value no theme can restate, so dark theme renders it unchanged\`,
200
+ fix: \`replace \${literal} in \${file.path} with rgb(var(--color-fg)), rgb(var(--color-bg)) or the role this element means — or a class whose stylesheet sets tokens.role('fg') — then: x verify\`,
201
+ at: file.path,
202
+ });
203
+ }
204
+ }
205
+ }
206
+ return findings;
207
+ }
208
+
154
209
  export const guard: Guard = {
155
210
  summary: 'a stylesheet names a semantic token, never a colour',
156
211
  async check(_root, sources) {
157
212
  // The run's ONE read of the stylesheets: every guard asking for this glob shares the walk.
158
213
  const sheets = await sources.files('{apps,packages}/**/*.scss');
159
- return rawColours(sheets.map((file) => ({ path: file.path, scss: file.text })));
214
+ const components: { path: string; source: string }[] = [];
215
+ // The surfaces \`untranslated-string\` reads, the same two globs, so the walk is shared.
216
+ for (const pattern of ['apps/*/{site,app,shared}/**/*.tsx', 'packages/*/src/**/*.tsx']) {
217
+ for (const file of await sources.files(pattern)) {
218
+ if (/\\.test\\.tsx?$/.test(file.path)) continue;
219
+ components.push({ path: file.path, source: file.text });
220
+ }
221
+ }
222
+ return [
223
+ ...rawColours(sheets.map((file) => ({ path: file.path, scss: file.text }))),
224
+ ...inlineColours(components),
225
+ ];
160
226
  },
161
227
  };
162
228
  `;
@@ -166,7 +232,7 @@ const test =
166
232
  // a green gate over the convention it was written to enforce.
167
233
 
168
234
  import { expect, unitTest } from '@ultimat3/testing';
169
- import { rawColours } from './raw-colour';
235
+ import { inlineColours, rawColours } from './raw-colour';
170
236
 
171
237
  const sheet = (scss: string) => [{ path: 'apps/web/site/page.module.scss', scss }];
172
238
 
@@ -222,6 +288,15 @@ unitTest('a token, a selector and a quoted filename are not colours', () => {
222
288
  expect(rawColours(sheet(".a { background: url('red-hero.png'); }"))).toEqual([]);
223
289
  });
224
290
 
291
+ // A component's inline style is a stylesheet by another name: the same colour, the same rule.
292
+ unitTest('an inline style colour is refused, and a token reference in one is not', () => {
293
+ const component = (source: string) => [{ path: 'apps/web/site/page.tsx', source }];
294
+ expect(inlineColours(component("<b style={{ color: '#ff0000' }} />"))).toHaveLength(1);
295
+ expect(inlineColours(component('<b style="background: red" />'))).toHaveLength(1);
296
+ expect(inlineColours(component("<b style={{ color: 'rgb(var(--color-fg))' }} />"))).toEqual([]);
297
+ expect(inlineColours(component("<b style={{ display: 'block' }} />"))).toEqual([]);
298
+ });
299
+
225
300
  unitTest('a commented-out colour is a note, not a declaration', () => {
226
301
  expect(rawColours(sheet('// color: #ff0000;\\n.a { padding: 0; }'))).toEqual([]);
227
302
  expect(rawColours(sheet('/* color: #ff0000; */\\n.a { padding: 0; }'))).toEqual([]);
@@ -28,7 +28,10 @@ export const RELEASED_GUARD_FORMS: Readonly<
28
28
  ['2eb7ld3hg0tpb', 'error'],
29
29
  ],
30
30
  'raw-breakpoint': [['wdo3lsqmvsya', 'error']],
31
- 'raw-colour': [['3onnbx54g9zmd', 'error']],
31
+ 'raw-colour': [
32
+ ['1e2pkqnmrjt44', 'error'],
33
+ ['3onnbx54g9zmd', 'error'],
34
+ ],
32
35
  'raw-fetch': [
33
36
  ['17xdeprvzx5v2', 'error'],
34
37
  ['1hgdwthi7j353', 'error'],
@@ -67,12 +70,14 @@ export const RELEASED_GUARD_FORMS: Readonly<
67
70
  ['2xnl4zuy9xv6f', 'error'],
68
71
  ['3b0u9i8hze00x', 'error'],
69
72
  ],
73
+ 'undeclared-env': [['3gsy96z8bgrrl', 'error']],
70
74
  'undefined-style-class': [
71
75
  ['3food9t4vrzv8', 'error'],
72
76
  ['w7as1ib1ido8', 'error'],
73
77
  ],
74
78
  'untranslated-string': [
75
79
  ['2x85ib5eqdxzi', 'error'],
80
+ ['3j5e8t1k120u3', 'error'],
76
81
  ['h57qtdwn7inz', 'error'],
77
82
  ],
78
83
  'unzoned-date': [
@@ -92,7 +97,7 @@ export const RELEASED_GUARD_TEST_FORMS: Readonly<Record<string, readonly string[
92
97
  'island-without-states': ['vls0ujdd16gw'],
93
98
  'native-confirm': ['1c7vps5wn37uv', 'qwyn1mzn9ace'],
94
99
  'raw-breakpoint': ['w356i8dreh7j'],
95
- 'raw-colour': ['1tc7cambk8byr'],
100
+ 'raw-colour': ['1tc7cambk8byr', '319l3wictp9lf'],
96
101
  'raw-fetch': ['2lips924uo00f'],
97
102
  'raw-interval': ['1z55givy4sst0'],
98
103
  'raw-length': ['1hpgz9jowk5qu'],
@@ -106,7 +111,8 @@ export const RELEASED_GUARD_TEST_FORMS: Readonly<Record<string, readonly string[
106
111
  'semantic-interactive': ['2uh0p6xoh996t', '393msxyy1bz36'],
107
112
  'unbounded-fanout': ['key86lol3wnh'],
108
113
  'undeclared-custom-property': ['30bi2v92swukf', 'svuf8sm14fm8'],
114
+ 'undeclared-env': ['38run3rew6y0c'],
109
115
  'undefined-style-class': ['1uy88gpk5k8p8', '2sy8me3i3bmzw'],
110
- 'untranslated-string': ['30q3u45cey2eq'],
116
+ 'untranslated-string': ['30q3u45cey2eq', 'cgvfv231gnvg'],
111
117
  'unzoned-date': ['1siep3fqscks4', '20x6l238r09jk'],
112
118
  };
@@ -0,0 +1,192 @@
1
+ // The `undeclared-env` guard `x new` ships: an app reads an environment variable its env schema
2
+ // declares. `env.STRIPE_KEY` off `defineEnv` fails tsc when the key is undeclared, but the raw
3
+ // `process.env.STRIPE_KEY ?? ''` beside it passed typecheck, lint, boundaries and errors, and
4
+ // `x env check` never named it — so a deploy without it booted and failed at the first read.
5
+
6
+ import { FRAMEWORK_ENV } from '@ultimat3/core';
7
+ import { guardCode } from './guard';
8
+ import type { GeneratedFile } from './naming';
9
+
10
+ /** Derived from the guard's name, never a literal: an `X_*` literal here is a FRAMEWORK code. */
11
+ const NAME = 'undeclared-env';
12
+ const CODE = guardCode(NAME);
13
+
14
+ /**
15
+ * The names the framework reads itself (`@ultimat3/core`'s `FRAMEWORK_ENV`), written INTO the rule
16
+ * rather than imported by it: a guard is a dependency-free text rule, and the list moves with the
17
+ * framework the guard ships in. Space-joined rows of at most ~90 columns, so the list stays a
18
+ * screenful rather than a name per line.
19
+ */
20
+ const frameworkRows = (): string => {
21
+ const heads = FRAMEWORK_ENV.filter((entry) => entry.prefix === true).map((entry) => entry.name);
22
+ // A name its head already admits (\`ULTIMATE_ENV\` under \`ULTIMATE_\`) is not written twice.
23
+ const names = FRAMEWORK_ENV.filter(
24
+ (entry) => entry.prefix !== true && !heads.some((head) => entry.name.startsWith(head)),
25
+ ).map((entry) => entry.name);
26
+ const rows: string[] = [];
27
+ for (const name of [...new Set(names)].sort()) {
28
+ const last = rows.length - 1;
29
+ const row = rows[last];
30
+ if (row !== undefined && row.length + name.length < 86) rows[last] = `${row} ${name}`;
31
+ else rows.push(name);
32
+ }
33
+ return rows.map((row) => ` '${row}',`).join('\n');
34
+ };
35
+
36
+ /** The heads every `ULTIMATE_*`-style name under them shares, quoted for the rule. */
37
+ const frameworkPrefixes = (): string =>
38
+ FRAMEWORK_ENV.filter((entry) => entry.prefix === true)
39
+ .map((entry) => `'${entry.name}'`)
40
+ .join(', ');
41
+
42
+ const source =
43
+ (): string => `// undeclared-env: every environment variable this app reads is declared in app.config.ts.
44
+ // \`x verify\` discovers every file in \`guards/\` and runs its \`guard\` inside the \`boundaries\`
45
+ // step — nothing registers this file, so nothing can forget to.
46
+ //
47
+ // Read: \`process.env.X\`, \`Bun.env.X\`, \`import.meta.env.X\` and the \`['X']\` forms, in app source
48
+ // (\`apps/**\`, \`packages/**\`; never a test). Declared: a key of \`envSchema\` or of the object
49
+ // \`defineEnv({ … })\` is handed, in \`app.config.ts\` — the declaration \`x env check\` reads.
50
+ // Allowed: every name the framework reads itself, \`NODE_ENV\` among them.
51
+
52
+ import type { Finding, Guard } from '@ultimat3/cli';
53
+
54
+ /** The app owns the codes its own conventions raise — this one is named for the guard. */
55
+ const CODE = '${CODE}';
56
+
57
+ /** The framework's own names, exact, then the heads every name under them shares. */
58
+ const FRAMEWORK = new Set(
59
+ [
60
+ ${frameworkRows()}
61
+ ]
62
+ .join(' ')
63
+ .split(' '),
64
+ );
65
+ const FRAMEWORK_PREFIXES = [${frameworkPrefixes()}];
66
+
67
+ /** A literal read: \`process.env.X\` / \`Bun.env['X']\`. A computed key names nothing to check. */
68
+ const READ =
69
+ /\\b(?:process\\.env|Bun\\.env|import\\.meta\\.env)(?:\\.([A-Za-z_$][\\w$]*)|\\[\\s*(['"\`])([A-Za-z_$][\\w$]*)\\2\\s*\\])/g;
70
+ /** Where the declaration opens: the \`envSchema\` export, or an object handed to \`defineEnv(\`. */
71
+ const OPENS = /\\bexport\\s+const\\s+envSchema\\b[^=]*=\\s*\\{|\\bdefineEnv\\(\\s*\\{/g;
72
+ /** A key at the declaration's top level, once every nested group is emptied. */
73
+ const KEY = /(?:^|[{,\\s])['"]?([A-Za-z_$][\\w$]*)['"]?\\s*:/g;
74
+
75
+ export interface SourceFile {
76
+ /** App-root-relative POSIX path, so the finding names the file an author opens. */
77
+ readonly path: string;
78
+ readonly source: string;
79
+ }
80
+
81
+ /** Comments blanked IN PLACE — not deleted — so a reported line number still points at the source. */
82
+ const blank = (text: string): string =>
83
+ text
84
+ .replaceAll(/\\/\\*[\\s\\S]*?\\*\\//g, (match) => match.replaceAll(/[^\\n]/g, ' '))
85
+ .replaceAll(/(?<![:\\w])\\/\\/[^\\n]*/g, (match) => ' '.repeat(match.length));
86
+
87
+ const lineOf = (text: string, index: number): number => text.slice(0, index).split('\\n').length;
88
+
89
+ /** The body of the brace group opening at \`open\`, or what is left of the text if it never closes. */
90
+ const groupAt = (text: string, open: number): string => {
91
+ let depth = 0;
92
+ for (let index = open; index < text.length; index += 1) {
93
+ const character = text.charAt(index);
94
+ if (character === '{') depth += 1;
95
+ else if (character === '}' && --depth === 0) return text.slice(open + 1, index);
96
+ }
97
+ return text.slice(open + 1);
98
+ };
99
+
100
+ /** Every name \`app.config.ts\` declares: the top-level keys of each declaration it opens. */
101
+ export function declaredNames(config: string): ReadonlySet<string> {
102
+ const names = new Set<string>();
103
+ const text = blank(config);
104
+ for (const open of text.matchAll(OPENS)) {
105
+ let body = groupAt(text, open.index + open[0].length - 1);
106
+ // Innermost first, until none is left: a declaration's own \`{ type: … }\` keys are not names.
107
+ for (let before = ''; before !== body; ) {
108
+ before = body;
109
+ body = body.replaceAll(/\\{[^{}]*\\}|\\[[^[\\]]*\\]/g, ' ');
110
+ }
111
+ for (const key of body.matchAll(KEY)) names.add(key[1] ?? '');
112
+ }
113
+ return names;
114
+ }
115
+
116
+ const isFramework = (name: string): boolean =>
117
+ FRAMEWORK.has(name) || FRAMEWORK_PREFIXES.some((head) => name.startsWith(head));
118
+
119
+ /** Pure — the caller does the I/O — so the rule is testable without a filesystem. */
120
+ export function undeclaredEnv(files: readonly SourceFile[], config: string): readonly Finding[] {
121
+ const declared = declaredNames(config);
122
+ const findings: Finding[] = [];
123
+ for (const file of files) {
124
+ const text = blank(file.source);
125
+ for (const match of text.matchAll(READ)) {
126
+ const name = match[1] ?? match[3] ?? '';
127
+ if (declared.has(name) || isFramework(name)) continue;
128
+ findings.push({
129
+ code: CODE,
130
+ cause: \`\${file.path}:\${lineOf(text, match.index)} reads \${match[0]}, which app.config.ts does not declare — x env check never asks for it, so a deploy without it boots and fails at the first read\`,
131
+ fix: \`add \${name}: { type: 'string', description: '…' } to envSchema in app.config.ts, read it as env.\${name} in \${file.path}, then: x env example\`,
132
+ at: file.path,
133
+ });
134
+ }
135
+ }
136
+ return findings;
137
+ }
138
+
139
+ export const guard: Guard = {
140
+ summary: 'an environment variable is read only once app.config.ts declares it',
141
+ async check(_root, sources) {
142
+ const config = (await sources.files('app.config.ts'))[0]?.text ?? '';
143
+ const files: SourceFile[] = [];
144
+ for (const pattern of ['{apps,packages}/**/*.ts', '{apps,packages}/**/*.tsx']) {
145
+ for (const file of await sources.files(pattern)) {
146
+ if (/\\.test\\.tsx?$|\\.d\\.ts$|(?:^|\\/)e2e\\//.test(file.path)) continue;
147
+ files.push({ path: file.path, source: file.text });
148
+ }
149
+ }
150
+ return undeclaredEnv(files, config);
151
+ },
152
+ };
153
+ `;
154
+
155
+ const test =
156
+ (): string => `// The rule, driven directly. Failure case first: a guard whose rule silently stopped matching is
157
+ // a green gate over the convention it was written to enforce.
158
+
159
+ import { expect, unitTest } from '@ultimat3/testing';
160
+ import { declaredNames, undeclaredEnv } from './undeclared-env';
161
+
162
+ const CONFIG = "export const envSchema = {\\n STRIPE_KEY: { type: 'string', values: ['A'] },\\n};\\n";
163
+ const file = (source: string) => [{ path: 'apps/web/app/billing/service.ts', source }];
164
+
165
+ unitTest('a read of an undeclared name is refused, and the fix is the declaration', () => {
166
+ const findings = undeclaredEnv(file("export const key = process.env.SENTRY_KEY ?? '';"), CONFIG);
167
+ expect(findings).toHaveLength(1);
168
+ expect(findings[0]?.code).toBe('${CODE}');
169
+ expect(findings[0]?.fix).toContain('SENTRY_KEY: {');
170
+ expect(undeclaredEnv(file("Bun.env['SENTRY_KEY'];"), CONFIG)).toHaveLength(1);
171
+ });
172
+
173
+ unitTest('a declared name, a framework name and a computed key are not reported', () => {
174
+ expect(undeclaredEnv(file('process.env.STRIPE_KEY;'), CONFIG)).toEqual([]);
175
+ expect(undeclaredEnv(file('Bun.env.NODE_ENV; Bun.env.DATABASE_URL;'), CONFIG)).toEqual([]);
176
+ expect(undeclaredEnv(file('Bun.env[name];'), CONFIG)).toEqual([]);
177
+ });
178
+
179
+ // A declaration's own keys (\\\`type\\\`, \\\`values\\\`) are not names it declares.
180
+ unitTest('only the top-level keys of the declaration are declared', () => {
181
+ expect([...declaredNames(CONFIG)]).toEqual(['STRIPE_KEY']);
182
+ expect([...declaredNames("export const env = defineEnv({ PORT: { type: 'port' } });")]).toEqual([
183
+ 'PORT',
184
+ ]);
185
+ });
186
+ `;
187
+
188
+ /** `guards/undeclared-env.ts` and its test. The directory is the registration. */
189
+ export const undeclaredEnvGuardFiles = (): readonly GeneratedFile[] => [
190
+ { path: 'guards/undeclared-env.ts', contents: source() },
191
+ { path: 'guards/undeclared-env.test.ts', contents: test() },
192
+ ];
@@ -16,7 +16,8 @@ const NAME = 'untranslated-string';
16
16
  const CODE = guardCode(NAME);
17
17
 
18
18
  const source =
19
- (): string => `// untranslated-string: every user-facing string on a rendered surface goes through \`t()\`.
19
+ (): string => `// untranslated-string: every user-facing string on a rendered surface goes through \`t()\` —
20
+ // a text node, and an attribute a user reads or hears (\`aria-label\`, \`title\`, \`alt\`, …).
20
21
  // \`x verify\` discovers every file in \`guards/\` and runs its \`guard\` inside the \`boundaries\`
21
22
  // step — nothing registers this file, so nothing can forget to.
22
23
 
@@ -38,6 +39,13 @@ const CODE = '${CODE}';
38
39
  const ELEMENT = /<([A-Za-z][\\w.:-]*)(?:\\s[^<>]*)?>([^<>]*?)<\\/\\1>/g;
39
40
  /** Two word characters in a row. One is \`&\`, \`×\`, an initial — never a sentence. */
40
41
  const PROSE = /[\\p{L}\\p{N}]{2,}/u;
42
+ /**
43
+ * An attribute a user reads or hears, holding a typed string: \`aria-label="…"\`, \`{'…'}\`. Biome
44
+ * writes JSX attributes with no space around \`=\`, so \`const title = '…'\` is never one, and the
45
+ * look-behind keeps \`data-title\` out. \`{t('…')}\` and \`{props.label}\` are expressions, not text.
46
+ */
47
+ const ATTRIBUTE =
48
+ /(?<=\\s)(aria-label|aria-description|aria-placeholder|aria-roledescription|aria-valuetext|title|placeholder|alt|label)=(?:"([^"]*)"|'([^']*)'|\\{\\s*(?:"([^"]*)"|'([^']*)')\\s*\\})/g;
41
49
 
42
50
  export interface SourceFile {
43
51
  /** App-root-relative POSIX path, so the finding names the file an author opens. */
@@ -98,6 +106,17 @@ export function untranslatedStrings(files: readonly SourceFile[]): readonly Find
98
106
  at: file.path,
99
107
  });
100
108
  }
109
+ for (const match of text.matchAll(ATTRIBUTE)) {
110
+ const name = match[1] ?? 'title';
111
+ const typed = (match[2] ?? match[3] ?? match[4] ?? match[5] ?? '').trim();
112
+ if (!PROSE.test(typed)) continue;
113
+ findings.push({
114
+ code: CODE,
115
+ cause: \`\${file.path}:\${lineOf(text, match.index)} renders the typed string "\${typed}" as its \${name} — it is in no catalog, so every locale but the one it was typed in reads it verbatim\`,
116
+ fix: \`add a key for "\${typed}" to packages/i18n/catalogs/en.json, write it as \${name}={t('…')} in \${file.path}, then: x i18n check\`,
117
+ at: file.path,
118
+ });
119
+ }
101
120
  }
102
121
  return findings;
103
122
  }
@@ -175,6 +194,15 @@ unitTest('a generic type argument is not a JSX text node', () => {
175
194
  expect(untranslatedStrings(file(generic))).toEqual([]);
176
195
  });
177
196
 
197
+ // An attribute a screen reader speaks is a rendered string; an expression in one is not typed.
198
+ unitTest('a typed aria-label is refused, and a t() call in one is not', () => {
199
+ const findings = untranslatedStrings(file('<button aria-label="Download report" />'));
200
+ expect(findings).toHaveLength(1);
201
+ expect(findings[0]?.cause).toContain('aria-label');
202
+ expect(untranslatedStrings(file("<button aria-label={t('app.report.download')} />"))).toEqual([]);
203
+ expect(untranslatedStrings(file("const title = 'Not an attribute';"))).toEqual([]);
204
+ });
205
+
178
206
  unitTest('one word character is a symbol, not a sentence', () => {
179
207
  expect(untranslatedStrings(file('<span>&</span>'))).toEqual([]);
180
208
  });
@@ -6,6 +6,12 @@ import type { GeneratedFile, NameSet } from './naming';
6
6
  import { names } from './naming';
7
7
  import { wrapImport, wrapList } from './wrap';
8
8
 
9
+ /**
10
+ * The org rule `can<Feature>Write` decides — written here, read back by `grantOf`
11
+ * (`slice-foundation.ts`), so an action generated into this slice knows a writer in the org passes.
12
+ */
13
+ export const ORG_WRITE_RULE = '({ actor, input }) => actor !== null && actor.orgId === input.orgId';
14
+
9
15
  /** Biome would rewrap this itself, so the generator emits the already-formatted form. */
10
16
  const permissionSet = (feature: NameSet): string =>
11
17
  wrapList(
@@ -67,7 +73,7 @@ export const can${feature.pascal}Read = can(
67
73
  /** Write compares the org the action's input names with the actor's — grant it apart from read. */
68
74
  export const can${feature.pascal}Write = can<${feature.pascal}Scope>(
69
75
  '${feature.kebab}:write',
70
- ({ actor, input }) => actor !== null && actor.orgId === input.orgId,
76
+ ${ORG_WRITE_RULE},
71
77
  );
72
78
 
73
79
  /**
@@ -50,8 +50,9 @@ export const ${name.camel} = query({
50
50
  live: ${String(live)},${cacheLine(feature, live)}
51
51
  // The refusals a caller may branch on, closed: add each code this read comes to throw.
52
52
  errors: [],
53
- // Opt-in, unlike an action's tool: a read hands rows to an agent, so silence exposes nothing.
54
- mcp: { expose: true, description: '${name.raw} — edit this description' },
53
+ // No \`mcp\`, as an action writes none: a tool's description is what an agent reads to decide to
54
+ // call it, and a placeholder there is worse than no tool. A read hands rows to an agent, so
55
+ // silence exposes nothing. Write one, then \`mcp: { expose: true, description: '…' }\`.
55
56
  sql: ({ limit, sort, dir }) =>
56
57
  // \`feature.table\`, not the kebab plural: \`from()\` quotes the identifier into the SQL text,
57
58
  // and the entity created the table as snake_case.
@@ -157,11 +158,12 @@ ${wrapper}('${name.camel} denies an orgless actor before a read', async () => {
157
158
  expect(denied).toBeUltimateError('X_FORBIDDEN');
158
159
  });
159
160
 
160
- ${wrapper}('${name.camel} is offered to agents as a read', () => {
161
- // \`@ultimat3/mcp\`'s \`toolFrom\` serves this block as a read (\`mutates: false\`), through
162
- // \`.as()\` under this same policy — an agent cannot reach a different authz path.
161
+ ${wrapper}('the read is offered to no agent until its tool is described', () => {
162
+ // A tool's description is what an agent reads to decide to call it, so the read ships none.
163
+ // Declare \`mcp: { expose: true, description: '…' }\` and \`@ultimat3/mcp\`'s \`toolFrom\` serves
164
+ // it as a read (\`mutates: false\`), through \`.as()\` under this same policy; then flip this.
163
165
  expect(target.kind).toBe('query');
164
- expect(target.mcp?.expose).toBe(true);
166
+ expect(target.mcp).toBeUndefined();
165
167
  });
166
168
  ${subscribes ? subscribeTest(name, feature) : ''}`;
167
169
  };
@@ -47,6 +47,7 @@ queries, jobs, MCP tools, published operations and tests it touches, each with p
47
47
  | Fan-out | a database call per element of a list runs through \`mapBounded(rows, fn, { width })\` from \`@ultimat3/core\` — never \`Promise.all(rows.map(async …))\`, one statement per row at once; a \`// why:\` on the line admits a list bounded where it is built | \`unbounded-fanout\` |
48
48
  | Vendors | a server \`fetch(\` carries a \`signal\` in its own options — better, it is \`outbound()\` from \`@ultimat3/core/outbound\`: a deadline, the caller's signal, safe-only retry | \`raw-fetch\` |
49
49
  | Runtime | every Bun pin — \`packageManager\`, \`.bun-version\`, CI's \`bun-version:\`, the image's \`FROM oven/bun:\` — names the version \`engines.bun\` declares, and an image builds on a digest | \`runtime-pin\` |
50
+ | Env | declared in \`envSchema\` | \`undeclared-env\` |
50
51
  | Polling | an island re-reads a query on a timer with \`useQuery(ref, input, { poll: pollEvery(ms) })\` (\`@ultimat3/realtime\`), anything else with \`visibleInterval(run, ms)\` from \`@ultimat3/core/page\` — no call while the tab is hidden, none after a lost session — never a bare \`setInterval(\`; a \`// why:\` on the line admits a tick that is not a read | \`raw-interval\` |
51
52
  | Confirmation | a destructive act asks through \`ConfirmDialog\` from \`@ultimat3/ui\` — Cancel focused, a native post, stays open on a refusal — never \`confirm(\`; a \`// why:\` on the line admits a call that is not that question | \`native-confirm\` |
52
53
  | Errors | never \`throw new Error\` — declare each code once, \`defineError({ code, title, status, cause, fix })\` from \`@ultimat3/core/page\`, and throw its class; never a handwritten \`UltimateError\` subclass | \`bare-error\`, \`error-declared\` |
@@ -27,7 +27,8 @@
27
27
  // One is about the POOL: a database call per row runs through `mapBounded`, never all at once.
28
28
  // Two more are about the REPO: an `await` per turn of a loop, REPORT ONLY (`severity: 'warning'`)
29
29
  // until the apps are clean of it, and a `.all()` that says no bound — failing the gate in an app
30
- // scaffolded from 31.23 on, while an older app keeps the report-only copy it was given.
30
+ // scaffolded from 31.23 on, while an older app keeps the report-only copy it was given. One is
31
+ // about the ENVIRONMENT: a variable is read only once `app.config.ts` declares it.
31
32
 
32
33
  import { SHIPPED_GUARD_NAMES as NAMES, type ShippedGuardName } from '../guards-shipped-names';
33
34
  import { animatedLayoutPropertyGuardFiles } from './guard-animated-layout-property';
@@ -53,6 +54,7 @@ import { runtimePinGuardFiles } from './guard-runtime-pin';
53
54
  import { semanticInteractiveGuardFiles } from './guard-semantic-interactive';
54
55
  import { unboundedFanoutGuardFiles } from './guard-unbounded-fanout';
55
56
  import { undeclaredCustomPropertyGuardFiles } from './guard-undeclared-custom-property';
57
+ import { undeclaredEnvGuardFiles } from './guard-undeclared-env';
56
58
  import { undefinedStyleClassGuardFiles } from './guard-undefined-style-class';
57
59
  import { untranslatedStringGuardFiles } from './guard-untranslated-string';
58
60
  import { unzonedDateGuardFiles } from './guard-unzoned-date';
@@ -88,6 +90,7 @@ const SHIPPED: Readonly<Record<ShippedGuardName, () => readonly GeneratedFile[]>
88
90
  'semantic-interactive': semanticInteractiveGuardFiles,
89
91
  'unbounded-fanout': unboundedFanoutGuardFiles,
90
92
  'undeclared-custom-property': undeclaredCustomPropertyGuardFiles,
93
+ 'undeclared-env': undeclaredEnvGuardFiles,
91
94
  'undefined-style-class': undefinedStyleClassGuardFiles,
92
95
  'untranslated-string': untranslatedStringGuardFiles,
93
96
  'unzoned-date': unzonedDateGuardFiles,
@@ -23,7 +23,7 @@ const i18nPackage = (app: NameSet, version: string): string => `{
23
23
  "typecheck": "tsc --noEmit -p ../../tsconfig.json"
24
24
  },
25
25
  "dependencies": {
26
- "@ultimat3/i18n": "^${version}"
26
+ "@ultimat3/i18n": "${version}"
27
27
  }
28
28
  }
29
29
  `;
@@ -60,7 +60,9 @@ const SOLID_VERSION = '1.9.18';
60
60
  // `github/ci.yml.ts` pins the workflow's Bun to the same constant.
61
61
  // `version` is not decoration: the manifest's app version IS the contract's compatibility gate, and
62
62
  // the manifest never fabricates one, so an app scaffolded without it failed `x manifest` and every
63
- // production boot with X_APP_PACKAGE_INVALID.
63
+ // production boot with X_APP_PACKAGE_INVALID. Every `@ultimat3/*` is pinned EXACT — what `x upgrade`
64
+ // writes and `x doctor` holds an app to (`X_FRAMEWORK_PIN_RANGE`): a caret let `bun update` move the
65
+ // framework without the hop's codemods. `doctor-pins.test.ts` holds every shape to it.
64
66
  const rootPackage = (app: NameSet, version: string): string => `{
65
67
  "name": "${app.kebab}",
66
68
  "version": "0.1.0",
@@ -84,32 +86,32 @@ const rootPackage = (app: NameSet, version: string): string => `{
84
86
  "@biomejs/biome": "${BIOME_VERSION}",
85
87
  "@electric-sql/pglite": "^0.5.4",
86
88
  "@types/bun": "^1.4.0",
87
- "@ultimat3/testing": "^${version}",
89
+ "@ultimat3/testing": "${version}",
88
90
  "typescript": "${TYPESCRIPT_VERSION}"
89
91
  },
90
92
  "dependencies": {
91
- "@ultimat3/action": "^${version}",
92
- "@ultimat3/admin": "^${version}",
93
- "@ultimat3/auth": "^${version}",
94
- "@ultimat3/cache": "^${version}",
95
- "@ultimat3/cli": "^${version}",
96
- "@ultimat3/core": "^${version}",
97
- "@ultimat3/db": "^${version}",
98
- "@ultimat3/entity": "^${version}",
99
- "@ultimat3/http": "^${version}",
100
- "@ultimat3/i18n": "^${version}",
101
- "@ultimat3/jobs": "^${version}",
102
- "@ultimat3/mail": "^${version}",
103
- "@ultimat3/mcp": "^${version}",
104
- "@ultimat3/money": "^${version}",
105
- "@ultimat3/policy": "^${version}",
106
- "@ultimat3/pwa": "^${version}",
107
- "@ultimat3/query": "^${version}",
108
- "@ultimat3/render": "^${version}",
109
- "@ultimat3/schema": "^${version}",
110
- "@ultimat3/seo": "^${version}",
111
- "@ultimat3/storage": "^${version}",
112
- "@ultimat3/ui": "^${version}",
93
+ "@ultimat3/action": "${version}",
94
+ "@ultimat3/admin": "${version}",
95
+ "@ultimat3/auth": "${version}",
96
+ "@ultimat3/cache": "${version}",
97
+ "@ultimat3/cli": "${version}",
98
+ "@ultimat3/core": "${version}",
99
+ "@ultimat3/db": "${version}",
100
+ "@ultimat3/entity": "${version}",
101
+ "@ultimat3/http": "${version}",
102
+ "@ultimat3/i18n": "${version}",
103
+ "@ultimat3/jobs": "${version}",
104
+ "@ultimat3/mail": "${version}",
105
+ "@ultimat3/mcp": "${version}",
106
+ "@ultimat3/money": "${version}",
107
+ "@ultimat3/policy": "${version}",
108
+ "@ultimat3/pwa": "${version}",
109
+ "@ultimat3/query": "${version}",
110
+ "@ultimat3/render": "${version}",
111
+ "@ultimat3/schema": "${version}",
112
+ "@ultimat3/seo": "${version}",
113
+ "@ultimat3/storage": "${version}",
114
+ "@ultimat3/ui": "${version}",
113
115
  "solid-js": "${SOLID_VERSION}"
114
116
  },
115
117
  "engines": {
@@ -103,11 +103,11 @@ unitTest('the agent and its tool are MCP tools; the keeper is not', () => {
103
103
  });
104
104
  `;
105
105
 
106
- /** `@ultimat3/ai` joins the app's dependencies at the release's range: the agent imports it. */
106
+ /** `@ultimat3/ai` joins the app's dependencies at the release's exact version: the agent imports it. */
107
107
  const dependencyEdit = (): ShapeEdit => ({
108
108
  path: 'package.json',
109
109
  find: ' "@ultimat3/auth": ',
110
- replace: ` "@ultimat3/ai": "^${loadVersion()}",\n "@ultimat3/auth": `,
110
+ replace: ` "@ultimat3/ai": "${loadVersion()}",\n "@ultimat3/auth": `,
111
111
  });
112
112
 
113
113
  const edits = (): readonly ShapeEdit[] => [
@@ -87,7 +87,7 @@ const edits = (): readonly ShapeEdit[] => [
87
87
  {
88
88
  path: 'package.json',
89
89
  find: ' "@ultimat3/render": ',
90
- replace: ` "@ultimat3/realtime": "^${loadVersion()}",\n "@ultimat3/render": `,
90
+ replace: ` "@ultimat3/realtime": "${loadVersion()}",\n "@ultimat3/render": `,
91
91
  },
92
92
  { path: 'README.md', find: README_LAYOUT, replace: `${lan()}${README_LAYOUT}` },
93
93
  ...shapeLines(