@rexezuge/tooling 1.12.0 → 1.14.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 (130) hide show
  1. package/README.md +149 -18
  2. package/dist/eslint-manifest.d.ts +25 -0
  3. package/dist/eslint-manifest.d.ts.map +1 -0
  4. package/dist/eslint-manifest.js +1 -0
  5. package/dist/eslint-manifest.js.map +7 -0
  6. package/dist/eslint-options.d.ts +54 -0
  7. package/dist/eslint-options.d.ts.map +1 -0
  8. package/dist/eslint-options.js +0 -0
  9. package/dist/eslint-options.js.map +7 -0
  10. package/dist/eslint-strict.d.ts +45 -0
  11. package/dist/eslint-strict.d.ts.map +1 -0
  12. package/dist/eslint-strict.js +1 -0
  13. package/dist/eslint-strict.js.map +7 -0
  14. package/dist/eslint.d.ts +2 -36
  15. package/dist/eslint.d.ts.map +1 -1
  16. package/dist/eslint.js +1 -1
  17. package/dist/eslint.js.map +3 -3
  18. package/dist/index.d.ts +5 -2
  19. package/dist/index.d.ts.map +1 -1
  20. package/dist/index.js +1 -1
  21. package/dist/index.js.map +3 -3
  22. package/dist/manifest-validate.d.ts +14 -0
  23. package/dist/manifest-validate.d.ts.map +1 -0
  24. package/dist/manifest-validate.js +1 -0
  25. package/dist/manifest-validate.js.map +7 -0
  26. package/dist/manifest.d.ts +159 -0
  27. package/dist/manifest.d.ts.map +1 -0
  28. package/dist/manifest.js +3 -0
  29. package/dist/manifest.js.map +7 -0
  30. package/dist/pages-proxy.d.ts +2 -0
  31. package/dist/pages-proxy.d.ts.map +1 -0
  32. package/dist/pages-proxy.js +1 -0
  33. package/dist/pages-proxy.js.map +7 -0
  34. package/dist/plugin-option.d.ts +15 -0
  35. package/dist/plugin-option.d.ts.map +1 -0
  36. package/dist/plugin-option.js +1 -0
  37. package/dist/plugin-option.js.map +7 -0
  38. package/dist/scripts/check-god-files.d.ts.map +1 -1
  39. package/dist/scripts/check-god-files.js +2 -2
  40. package/dist/scripts/check-god-files.js.map +3 -3
  41. package/dist/scripts/ensure-spa-shell-stub.d.ts +4 -2
  42. package/dist/scripts/ensure-spa-shell-stub.d.ts.map +1 -1
  43. package/dist/scripts/ensure-spa-shell-stub.js +1 -2
  44. package/dist/scripts/ensure-spa-shell-stub.js.map +3 -3
  45. package/dist/scripts/init-secrets.d.ts +1 -2
  46. package/dist/scripts/init-secrets.d.ts.map +1 -1
  47. package/dist/scripts/init-secrets.js +2 -3
  48. package/dist/scripts/init-secrets.js.map +3 -3
  49. package/dist/scripts/migrations-lock.d.ts +6 -2
  50. package/dist/scripts/migrations-lock.d.ts.map +1 -1
  51. package/dist/scripts/migrations-lock.js +1 -2
  52. package/dist/scripts/migrations-lock.js.map +3 -3
  53. package/dist/scripts/prepare-wrangler-config.d.ts +6 -2
  54. package/dist/scripts/prepare-wrangler-config.d.ts.map +1 -1
  55. package/dist/scripts/prepare-wrangler-config.js +1 -2
  56. package/dist/scripts/prepare-wrangler-config.js.map +3 -3
  57. package/dist/scripts/validate-locales.d.ts +20 -2
  58. package/dist/scripts/validate-locales.d.ts.map +1 -1
  59. package/dist/scripts/validate-locales.js +5 -5
  60. package/dist/scripts/validate-locales.js.map +3 -3
  61. package/dist/scripts/verify-spa-shell.d.ts +7 -2
  62. package/dist/scripts/verify-spa-shell.d.ts.map +1 -1
  63. package/dist/scripts/verify-spa-shell.js +1 -2
  64. package/dist/scripts/verify-spa-shell.js.map +3 -3
  65. package/dist/test/mocks/cloudflare-workers.d.ts +6 -103
  66. package/dist/test/mocks/cloudflare-workers.d.ts.map +1 -1
  67. package/dist/test/mocks/cloudflare-workers.js +1 -1
  68. package/dist/test/mocks/cloudflare-workers.js.map +3 -3
  69. package/dist/vite.d.ts +2 -1
  70. package/dist/vite.d.ts.map +1 -1
  71. package/dist/vite.js +3 -3
  72. package/dist/vite.js.map +3 -3
  73. package/dist/vitest-aliases.d.ts +3 -0
  74. package/dist/vitest-aliases.d.ts.map +1 -1
  75. package/dist/vitest-aliases.js +1 -1
  76. package/dist/vitest-aliases.js.map +3 -3
  77. package/dist/vitest-integration.d.ts +3 -2
  78. package/dist/vitest-integration.d.ts.map +1 -1
  79. package/dist/vitest-integration.js +1 -1
  80. package/dist/vitest-integration.js.map +3 -3
  81. package/dist/vitest-repo.d.ts +5 -3
  82. package/dist/vitest-repo.d.ts.map +1 -1
  83. package/dist/vitest-repo.js +1 -1
  84. package/dist/vitest-repo.js.map +3 -3
  85. package/dist/vitest-web.d.ts +3 -2
  86. package/dist/vitest-web.d.ts.map +1 -1
  87. package/dist/vitest-web.js +1 -1
  88. package/dist/vitest-web.js.map +3 -3
  89. package/dist/vitest.d.ts +5 -3
  90. package/dist/vitest.d.ts.map +1 -1
  91. package/dist/vitest.js +1 -1
  92. package/dist/vitest.js.map +3 -3
  93. package/package.json +14 -3
  94. package/presets/prettier.d.mts +4 -0
  95. package/presets/prettier.mjs +16 -0
  96. package/presets/tsconfig/base.json +19 -0
  97. package/presets/tsconfig/web.json +10 -0
  98. package/presets/tsconfig/worker.json +9 -0
  99. package/schema/manifest.schema.json +105 -0
  100. package/src/eslint-manifest.ts +71 -0
  101. package/src/eslint-options.ts +54 -0
  102. package/src/eslint-strict.test.ts +106 -0
  103. package/src/eslint-strict.ts +191 -0
  104. package/src/eslint.ts +18 -41
  105. package/src/index.ts +15 -2
  106. package/src/manifest-validate.ts +202 -0
  107. package/src/manifest.test.ts +228 -0
  108. package/src/manifest.ts +194 -0
  109. package/src/pages-proxy.test.ts +8 -0
  110. package/src/pages-proxy.ts +13 -0
  111. package/src/plugin-option.test.ts +13 -0
  112. package/src/plugin-option.ts +18 -0
  113. package/src/presets.test.ts +63 -0
  114. package/src/scripts/check-god-files.ts +3 -0
  115. package/src/scripts/ensure-spa-shell-stub.ts +18 -10
  116. package/src/scripts/entrypoints.test.ts +55 -0
  117. package/src/scripts/init-secrets.ts +8 -6
  118. package/src/scripts/migrations-lock.ts +22 -17
  119. package/src/scripts/prepare-wrangler-config.ts +26 -14
  120. package/src/scripts/validate-locales.ts +39 -17
  121. package/src/scripts/verify-spa-shell.ts +21 -20
  122. package/src/test/mocks/cloudflare-workers.ts +6 -113
  123. package/src/vite.ts +6 -3
  124. package/src/vitest-aliases.test.ts +23 -0
  125. package/src/vitest-aliases.ts +22 -1
  126. package/src/vitest-factories.test.ts +30 -1
  127. package/src/vitest-integration.ts +5 -3
  128. package/src/vitest-repo.ts +10 -5
  129. package/src/vitest-web.ts +5 -3
  130. package/src/vitest.ts +10 -5
@@ -0,0 +1,54 @@
1
+ import type { LayerBan } from './eslint-boundaries.ts';
2
+ import type { FamilyManifest } from './manifest.ts';
3
+
4
+ /**
5
+ * What `defineRepoLintConfig` accepts.
6
+ */
7
+ export interface RepoLintConfigOptions {
8
+ /**
9
+ * The consuming repo's npm scope, e.g. `'@myapp'`. Every `no-restricted-imports`
10
+ * pattern in the boundary rules is derived from it, so the same factory serves
11
+ * all nine repos.
12
+ */
13
+ readonly scope?: string;
14
+ /**
15
+ * The family manifest. Omitted: `<tsconfigRootDir or cwd>/.rexezuge.jsonc` is
16
+ * loaded when it exists. Pass `false` to ignore the file. A manifest supplies
17
+ * `scope` (unless given here), replaces the canonical layer table with its own
18
+ * `layers` (when it declares any), and names the http and browser directories
19
+ * the strict rules exempt.
20
+ */
21
+ readonly manifest?: FamilyManifest | false;
22
+ /**
23
+ * Extra http-layer directories (may import `hono`/`chanfana`, hand-build the
24
+ * error envelope), beside `apps/api` and the manifest's `http: true` layers.
25
+ */
26
+ readonly httpDirs?: readonly string[];
27
+ /**
28
+ * The workspace directories the legacy canonical layer table is scoped to, as
29
+ * repo-relative globs. Only used when no manifest declares `layers`.
30
+ *
31
+ * @deprecated Declare `layers` in `.rexezuge.jsonc` instead: the canonical
32
+ * table encodes consumer package names.
33
+ */
34
+ readonly projectDirs?: readonly string[];
35
+ /**
36
+ * Extra ignore globs, merged with the canonical set.
37
+ */
38
+ readonly extraIgnores?: readonly string[];
39
+ /**
40
+ * Where `projectService` resolves the tsconfig from. Defaults to the directory
41
+ * ESLint is invoked in, which is the repo root in every CI job.
42
+ */
43
+ readonly tsconfigRootDir?: string;
44
+ /**
45
+ * Extra boundary layers, appended to the canonical table.
46
+ *
47
+ * The escape valve for a repo whose layout has a boundary the canonical table
48
+ * does not name — AWS-AccessBridge's `apps/api/src/endpoints/**` rule ("route
49
+ * classes must not import DAOs directly") and its `aws4fetch` ban are the shape.
50
+ * Same {@link LayerBan} form, so `extraLayers` flows through the
51
+ * `no-restricted-imports` and the `no-restricted-syntax` guard alike.
52
+ */
53
+ readonly extraLayers?: readonly LayerBan[];
54
+ }
@@ -0,0 +1,106 @@
1
+ import { Linter } from 'eslint';
2
+ import { describe, expect, it } from 'vitest';
3
+ import { strictConfigs } from './eslint-strict.ts';
4
+ import { defineRepoLintConfig } from './eslint.ts';
5
+
6
+ const linter = new Linter({ configType: 'flat' });
7
+ const config = strictConfigs({ httpDirs: ['packages/http'], browserDirs: ['apps/web'] }) as Linter.Config[];
8
+
9
+ /**
10
+ Messages for `code` linted as `filename` under the strict blocks only.
11
+ */
12
+ function lint(code: string, filename: string): string[] {
13
+ return linter.verify(code, config, { filename }).map((message) => `${message.ruleId ?? 'parse'}: ${message.message}`);
14
+ }
15
+
16
+ describe('strict: console', () => {
17
+ const code = "console.log('x');";
18
+ it('is refused in worker code, with the logger named', () => {
19
+ const [message] = lint(code, 'apps/api/src/a.ts');
20
+ expect(message).toContain('no-restricted-globals');
21
+ expect(message).toContain('createLogger from @rexezuge/runtime');
22
+ });
23
+ it('is allowed in apps/web, scripts and tests', () => {
24
+ expect(lint(code, 'apps/web/src/a.ts')).toEqual([]);
25
+ expect(lint(code, 'packages/x/scripts/a.ts')).toEqual([]);
26
+ expect(lint(code, 'test/a.test.ts')).toEqual([]);
27
+ expect(lint(code, 'packages/x/src/a.test.ts')).toEqual([]);
28
+ });
29
+ });
30
+
31
+ describe('strict: restricted imports', () => {
32
+ it.each([
33
+ "import { Hono } from 'hono';",
34
+ "import { cors } from 'hono/cors';",
35
+ "export * from 'chanfana';",
36
+ "const x = await import('hono');",
37
+ "const y = require('chanfana');",
38
+ ])('refuses the framework outside the http layer: %s', (code) => {
39
+ expect(lint(code, 'packages/backend-services/src/a.ts')[0]).toContain('rexezuge/restricted-import');
40
+ expect(lint(code, 'packages/backend-services/src/a.ts')[0]).toContain('createApiApp');
41
+ });
42
+ it('allows the framework in apps/api and declared http dirs', () => {
43
+ expect(lint("import { Hono } from 'hono';", 'apps/api/src/a.ts')).toEqual([]);
44
+ expect(lint("import { Hono } from 'hono';", 'packages/http/src/a.ts')).toEqual([]);
45
+ });
46
+ it('still refuses the framework in tests', () => {
47
+ expect(lint("import { Hono } from 'hono';", 'test/a.test.ts')).toHaveLength(1);
48
+ });
49
+ it('sends jose and uuid to the kit, outside tests and the http layer', () => {
50
+ expect(lint("import { jwtVerify } from 'jose';", 'apps/api/src/a.ts')[0]).toContain('accessAuth from @rexezuge/http');
51
+ expect(lint("import { v4 } from 'uuid';", 'packages/shared/src/a.ts')[0]).toContain('UUIDUtil');
52
+ expect(lint("import { jwtVerify } from 'jose';", 'test/a.test.ts')).toEqual([]);
53
+ expect(lint("import { jwtVerify } from 'jose';", 'packages/http/src/a.ts')).toEqual([]);
54
+ });
55
+ it('does not match lookalike specifiers or non-literal imports', () => {
56
+ expect(lint("import x from 'honor'; import y from 'jose-extra'; import(name); require(name); require();", 'apps/api/src/a.ts')).toEqual(
57
+ [],
58
+ );
59
+ });
60
+ });
61
+
62
+ describe('strict: hand-built envelope', () => {
63
+ it.each(["new Response(JSON.stringify({ Exception: { Type: 'X', Message: 'm' } }));", "c.json({ 'Exception': { Type: 'X' } });"])(
64
+ 'is refused: %s',
65
+ (code) => {
66
+ expect(lint(code, 'packages/backend-services/src/a.ts')[0]).toContain('@rexezuge/errors');
67
+ },
68
+ );
69
+ it('allows other Exception-shaped data, tests and the http layer', () => {
70
+ expect(lint('x({ Exception: 1 }); y({ Exception: { Name: 1 } }); z({ [k]: { Type: 1 } });', 'apps/api/src/a.ts')).toEqual([]);
71
+ expect(lint("x({ Exception: { Type: 'X' } });", 'test/a.test.ts')).toEqual([]);
72
+ expect(lint("x({ Exception: { Type: 'X' } });", 'packages/http/src/a.ts')).toEqual([]);
73
+ expect(lint("x({ Exception: { Type: 'X' } });", 'apps/api/src/a.ts')).toHaveLength(1);
74
+ });
75
+ });
76
+
77
+ describe('defineRepoLintConfig integration', () => {
78
+ const FLAT = defineRepoLintConfig({ scope: '@x', manifest: false });
79
+ const ruleNames = JSON.stringify(FLAT.map((entry) => Object.keys(entry.rules ?? {})));
80
+
81
+ it('carries the strict rules by default', () => {
82
+ expect(ruleNames).toContain('rexezuge/no-hand-built-envelope');
83
+ expect(ruleNames).toContain('no-restricted-globals');
84
+ });
85
+
86
+ it('takes the scope from a manifest and its layers replace the canonical table', () => {
87
+ const manifest = {
88
+ name: 'x',
89
+ scope: '@x',
90
+ layers: [{ name: 'core', dir: 'packages/core', mayImport: [] }],
91
+ };
92
+ const flat = defineRepoLintConfig({ manifest });
93
+ const files = flat.flatMap((entry) => entry.files ?? []).map(String);
94
+ expect(files).toContain('packages/core/**/*.{ts,js,mts,cts,mjs,cjs}');
95
+ expect(files).not.toContain('packages/shared/**/*.{ts,js,mts,cts,mjs,cjs}');
96
+ });
97
+
98
+ it('keeps the legacy canonical table when no manifest declares layers', () => {
99
+ const flat = defineRepoLintConfig({ scope: '@x', manifest: { name: 'x', scope: '@x' } });
100
+ expect(flat.flatMap((entry) => entry.files ?? []).map(String)).toContain('packages/shared/**/*.{ts,js,mts,cts,mjs,cjs}');
101
+ });
102
+
103
+ it('fails loudly without a scope', () => {
104
+ expect(() => defineRepoLintConfig({ manifest: false })).toThrow(/scope/);
105
+ });
106
+ });
@@ -0,0 +1,191 @@
1
+ import type { Rule } from 'eslint';
2
+ import type tseslint from 'typescript-eslint';
3
+
4
+ /**
5
+ * The family's **strict side** of the lint config: rules a repo cannot switch
6
+ * off wholesale, only waive per file with an `eslint-disable` comment.
7
+ *
8
+ * Every rule here exists because a family repo once re-implemented something the
9
+ * kit now owns; each message names the kit API to use instead. They use two
10
+ * kit-local rules (`rexezuge/restricted-import`, `rexezuge/no-hand-built-envelope`)
11
+ * and `no-restricted-globals` rather than `no-restricted-imports` /
12
+ * `no-restricted-syntax`: flat config replaces a rule's options per file instead
13
+ * of merging them, so a strict entry in those two would silently erase the layer
14
+ * boundaries (or be erased by them) wherever the globs overlap.
15
+ */
16
+
17
+ type ConfigInput = Parameters<typeof tseslint.config>[number];
18
+
19
+ interface ImportBan {
20
+ readonly names: readonly string[];
21
+ readonly message: string;
22
+ }
23
+
24
+ interface Node {
25
+ readonly type: string;
26
+ readonly [key: string]: unknown;
27
+ }
28
+
29
+ const asRecord = (value: unknown): Record<string, unknown> | null =>
30
+ typeof value === 'object' && value !== null ? (value as Record<string, unknown>) : null;
31
+
32
+ function keyName(property: Record<string, unknown>): string | null {
33
+ const key = asRecord(property.key);
34
+ if (key === null) return null;
35
+ if (key.type === 'Identifier' && typeof key.name === 'string') return key.name;
36
+ return key.type === 'Literal' && typeof key.value === 'string' ? key.value : null;
37
+ }
38
+
39
+ /**
40
+ * Flags a module specifier (static, re-export, dynamic `import()` or `require`)
41
+ * that equals, or is a subpath of, a banned name. Type-only imports are flagged
42
+ * too: a framework type leaking across a layer is the failure being prevented.
43
+ */
44
+ const restrictedImport: Rule.RuleModule = {
45
+ meta: {
46
+ type: 'problem',
47
+ schema: [{ type: 'object', properties: { bans: { type: 'array' } }, additionalProperties: false }],
48
+ messages: { banned: '`{{specifier}}` is not allowed here. {{message}}' },
49
+ },
50
+ create(context) {
51
+ const bans = ((context.options[0] as { bans?: ImportBan[] } | undefined)?.bans ?? []) as readonly ImportBan[];
52
+ const check = (node: Rule.Node, specifier: unknown): void => {
53
+ if (typeof specifier !== 'string') return;
54
+ const hit = bans.find((ban) => ban.names.some((name) => specifier === name || specifier.startsWith(`${name}/`)));
55
+ if (hit) context.report({ node, messageId: 'banned', data: { specifier, message: hit.message } });
56
+ };
57
+ const literal = (source: unknown): unknown => asRecord(source)?.value;
58
+ return {
59
+ ImportDeclaration: (node) => check(node, literal(node.source)),
60
+ ExportAllDeclaration: (node) => check(node, literal(node.source)),
61
+ ExportNamedDeclaration: (node) => check(node, literal(node.source)),
62
+ ImportExpression: (node) => check(node, literal(node.source)),
63
+ CallExpression: (node) => {
64
+ const callee = asRecord(node.callee);
65
+ if (callee?.type === 'Identifier' && callee.name === 'require') check(node, literal(node.arguments[0]));
66
+ },
67
+ };
68
+ },
69
+ };
70
+
71
+ /**
72
+ * Flags an object literal shaped `{ Exception: { Type, … } }`: the family error
73
+ * envelope, built by hand. The envelope is produced by the kit's error mapper
74
+ * from a thrown typed error, so a hand-built one skips redaction and the
75
+ * status/type mapping.
76
+ */
77
+ const noHandBuiltEnvelope: Rule.RuleModule = {
78
+ meta: {
79
+ type: 'problem',
80
+ schema: [],
81
+ messages: {
82
+ handBuilt:
83
+ 'Do not hand-build the `{ Exception: { Type, Message } }` envelope. Throw a typed error from @rexezuge/errors and let the @rexezuge/http error mapper (createErrorHandler / ErrorMapper) produce it.',
84
+ },
85
+ },
86
+ create(context) {
87
+ return {
88
+ Property(node) {
89
+ const property = node as unknown as Record<string, unknown>;
90
+ const value = asRecord(property.value);
91
+ if (keyName(property) !== 'Exception' || value?.type !== 'ObjectExpression') return;
92
+ const inner = Array.isArray(value.properties) ? (value.properties as Node[]) : [];
93
+ if (inner.some((entry) => entry.type === 'Property' && keyName(entry) === 'Type')) context.report({ node, messageId: 'handBuilt' });
94
+ },
95
+ };
96
+ },
97
+ };
98
+
99
+ export const REXEZUGE_PLUGIN = { rules: { 'restricted-import': restrictedImport, 'no-hand-built-envelope': noHandBuiltEnvelope } };
100
+
101
+ const TS_FILES = ['**/*.{ts,mts,cts,tsx}'];
102
+ const SOURCE_FILES = ['**/*.{js,mjs,cjs,ts,mts,cts,tsx,jsx}'];
103
+ /**
104
+ Tests, mocks and fixtures: they may spy on `console`, sign tokens, assert the envelope.
105
+ */
106
+ const TEST_GLOBS = ['test/**', '**/test/**', '**/*.test.*', '**/*.spec.*'];
107
+
108
+ const under = (dirs: readonly string[]): string[] => dirs.map((dir) => `${dir}/**`);
109
+
110
+ export const STRICT_IMPORT_BANS: readonly ImportBan[] = [
111
+ {
112
+ names: ['jose'],
113
+ message: 'Verify Cloudflare Access tokens with accessAuth from @rexezuge/http (and forgeAccessJwt from @rexezuge/testing in tests).',
114
+ },
115
+ {
116
+ names: ['uuid', 'nanoid'],
117
+ message: 'Use UUIDUtil / CryptoIdGenerator from @rexezuge/shared (inject an IdGenerator so tests can fix it).',
118
+ },
119
+ ];
120
+
121
+ export const FRAMEWORK_BAN: ImportBan = {
122
+ names: ['hono', 'chanfana'],
123
+ message:
124
+ 'The server framework lives in @rexezuge/http/hono and apps/api. Build the app with createApiApp; keep framework types out of other layers.',
125
+ };
126
+
127
+ export interface StrictOptions {
128
+ /**
129
+ * Directories that are the http layer: they may import hono/chanfana, jose and build envelopes
130
+ * themselves. `apps/api` may import the framework too, but never the rest: it uses the kit.
131
+ */
132
+ readonly httpDirs: readonly string[];
133
+ /**
134
+ Directories where `console` is allowed.
135
+ */
136
+ readonly browserDirs: readonly string[];
137
+ }
138
+
139
+ /**
140
+ * The strict rule blocks. Appended after the layer rules; a consumer's own later
141
+ * blocks (and per-file `eslint-disable` comments) are the only way to waive them.
142
+ */
143
+ export function strictConfigs(options: StrictOptions): ConfigInput[] {
144
+ const http = ['apps/api', ...options.httpDirs];
145
+ return [
146
+ {
147
+ files: SOURCE_FILES,
148
+ ignores: [...under(options.browserDirs), ...TEST_GLOBS, '**/scripts/**'],
149
+ rules: {
150
+ 'no-restricted-globals': [
151
+ 'error',
152
+ {
153
+ name: 'console',
154
+ message:
155
+ 'Log through createLogger from @rexezuge/runtime: it redacts, levels and correlates. console.* is for apps/web and scripts only.',
156
+ },
157
+ ],
158
+ },
159
+ },
160
+ {
161
+ files: TS_FILES,
162
+ plugins: { rexezuge: REXEZUGE_PLUGIN },
163
+ rules: {},
164
+ },
165
+ // Rules of one name replace each other per file, so each region states its
166
+ // whole ban list: framework + kit outside the http layer and apps/api (the
167
+ // framework is allowed there), kit only inside apps/api, framework only in
168
+ // tests.
169
+ {
170
+ files: TS_FILES,
171
+ ignores: under(http),
172
+ rules: { 'rexezuge/restricted-import': ['error', { bans: [FRAMEWORK_BAN] }] },
173
+ },
174
+ {
175
+ files: TS_FILES,
176
+ ignores: [...under(http), ...TEST_GLOBS],
177
+ rules: {
178
+ 'rexezuge/restricted-import': ['error', { bans: [FRAMEWORK_BAN, ...STRICT_IMPORT_BANS] }],
179
+ 'rexezuge/no-hand-built-envelope': 'error',
180
+ },
181
+ },
182
+ {
183
+ files: ['apps/api/**/*.{ts,mts,cts,tsx}'],
184
+ ignores: [...under(options.httpDirs), ...TEST_GLOBS],
185
+ rules: {
186
+ 'rexezuge/restricted-import': ['error', { bans: STRICT_IMPORT_BANS }],
187
+ 'rexezuge/no-hand-built-envelope': 'error',
188
+ },
189
+ },
190
+ ];
191
+ }
package/src/eslint.ts CHANGED
@@ -59,44 +59,13 @@ import eslintConfigPrettier from 'eslint-config-prettier';
59
59
  import prettier from 'eslint-plugin-prettier';
60
60
  import type { FlatConfig } from 'typescript-eslint';
61
61
  import { DEFAULT_PROJECT_DIRS, layerBans, restrictedDynamicImports, restrictedImports } from './eslint-boundaries.ts';
62
- import type { LayerBan } from './eslint-boundaries.ts';
62
+ import type { RepoLintConfigOptions } from './eslint-options.ts';
63
+ import { manifestBrowserDirs, manifestHttpDirs, manifestLayerBans } from './eslint-manifest.ts';
64
+ import { strictConfigs } from './eslint-strict.ts';
65
+ import { loadManifest } from './manifest.ts';
63
66
  import { SONARJS_RULES, TEST_RULES, TYPESCRIPT_RULES, UNICORN_RULES } from './eslint-rules.ts';
64
67
 
65
- /**
66
- * What `defineRepoLintConfig` accepts.
67
- */
68
- export interface RepoLintConfigOptions {
69
- /**
70
- * The consuming repo's npm scope, e.g. `'@myapp'`. Every `no-restricted-imports`
71
- * pattern in the boundary rules is derived from it, so the same factory serves
72
- * all nine repos.
73
- */
74
- readonly scope: string;
75
- /**
76
- * The workspace directories the layered boundary rules are scoped to, as repo-
77
- * relative globs. Defaults to the canonical layout the nine repos share.
78
- */
79
- readonly projectDirs?: readonly string[];
80
- /**
81
- * Extra ignore globs, merged with the canonical set.
82
- */
83
- readonly extraIgnores?: readonly string[];
84
- /**
85
- * Where `projectService` resolves the tsconfig from. Defaults to the directory
86
- * ESLint is invoked in, which is the repo root in every CI job.
87
- */
88
- readonly tsconfigRootDir?: string;
89
- /**
90
- * Extra boundary layers, appended to the canonical table.
91
- *
92
- * The escape valve for a repo whose layout has a boundary the canonical table
93
- * does not name — AWS-AccessBridge's `apps/api/src/endpoints/**` rule ("route
94
- * classes must not import DAOs directly") and its `aws4fetch` ban are the shape.
95
- * Same {@link LayerBan} form, so `extraLayers` flows through the
96
- * `no-restricted-imports` and the `no-restricted-syntax` guard alike.
97
- */
98
- readonly extraLayers?: readonly LayerBan[];
99
- }
68
+ export type { RepoLintConfigOptions } from './eslint-options.ts';
100
69
 
101
70
  /**
102
71
  * One argument to `tseslint.config()`.
@@ -146,11 +115,16 @@ function asRules(block: Readonly<Record<string, unknown>>): FlatConfig.Config['r
146
115
  * ```
147
116
  */
148
117
  export function defineRepoLintConfig(options: RepoLintConfigOptions): FlatConfig.ConfigArray {
149
- const { scope } = options;
118
+ const manifest = options.manifest === false ? null : (options.manifest ?? loadManifest(options.tsconfigRootDir ?? process.cwd()));
119
+ const scope = options.scope ?? manifest?.scope;
120
+ if (scope === undefined) throw new Error('defineRepoLintConfig: pass `scope`, or add a `.rexezuge.jsonc` manifest that declares it.');
150
121
  const projectDirs = options.projectDirs ?? DEFAULT_PROJECT_DIRS;
151
- const canonical = layerBans(scope).filter((layer) => projectDirs.some((dir) => layer.dir.startsWith(dir)));
152
- const extra = options.extraLayers ?? [];
153
- const bans = [...canonical, ...extra];
122
+ const layerRows =
123
+ manifest?.layers === undefined
124
+ ? layerBans(scope).filter((layer) => projectDirs.some((dir) => layer.dir.startsWith(dir)))
125
+ : manifestLayerBans(manifest);
126
+ const bans = [...layerRows, ...(options.extraLayers ?? [])];
127
+ const browserDirs = manifestBrowserDirs(manifest);
154
128
 
155
129
  return tseslint.config(
156
130
  {
@@ -254,6 +228,9 @@ export function defineRepoLintConfig(options: RepoLintConfigOptions): FlatConfig
254
228
  ...restrictedImports(bans),
255
229
  ...restrictedDynamicImports(bans),
256
230
 
231
+ // --- Strict side: family rules a repo waives per file, never wholesale ---
232
+ ...strictConfigs({ httpDirs: [...manifestHttpDirs(manifest), ...(options.httpDirs ?? [])], browserDirs }),
233
+
257
234
  // --- Web: browser globals, matching the jsdom test environment ---
258
235
  //
259
236
  // The sources linted `apps/web` under `globals.node` only, so `window`,
@@ -262,7 +239,7 @@ export function defineRepoLintConfig(options: RepoLintConfigOptions): FlatConfig
262
239
  // with the environment the code is executed in, or the rule is reporting
263
240
  // something untrue about how the file behaves.
264
241
  {
265
- files: ['apps/web/**/*.{ts,tsx,js,jsx,mts,cts,mjs,cjs}'],
242
+ files: browserDirs.map((dir) => `${dir}/**/*.{ts,tsx,js,jsx,mts,cts,mjs,cjs}`),
266
243
  languageOptions: {
267
244
  globals: { ...globals.node, ...globals.browser },
268
245
  },
package/src/index.ts CHANGED
@@ -7,8 +7,9 @@
7
7
  * the repository they run in, so they are run from disk with `tsx`, not imported.
8
8
  * See `README.md` for the copy-in recipe and the per-script usage.
9
9
  *
10
- * The zero-dependency rule: nothing here imports another `@rexezuge/*` package. The
11
- * one exception in the tree is `scripts/backup/encrypt-backup.ts`, which uses
10
+ * The near-zero-dependency rule: nothing here imports another `@rexezuge/*` package
11
+ * except `@rexezuge/testing` (the deprecated `cloudflare:workers` mock re-export). The
12
+ * one other exception in the tree is `scripts/backup/encrypt-backup.ts`, which uses
12
13
  * `@rexezuge/d1`'s AES-GCM so the backup and the workers share one definition of
13
14
  * "what an encryption key looks like"; that dependency is declared on the package
14
15
  * and is only ever resolved in the consumer's repo, where the kit is installed
@@ -18,6 +19,18 @@
18
19
  export { defineRepoLintConfig } from './eslint.ts';
19
20
  export type { RepoLintConfigOptions } from './eslint.ts';
20
21
 
22
+ export { FAMILY_GOD_FILE_LIMITS, loadManifest, MANIFEST_FILENAME, ManifestError, parseManifest, validateManifest } from './manifest.ts';
23
+ export type {
24
+ FamilyManifest,
25
+ ManifestCoverage,
26
+ ManifestD1,
27
+ ManifestFeatures,
28
+ ManifestLayer,
29
+ ManifestQuality,
30
+ ManifestValidation,
31
+ ManifestWeb,
32
+ } from './manifest.ts';
33
+
21
34
  export { defineUnitVitestConfig } from './vitest.ts';
22
35
  export type { CoverageThresholds, UnitVitestConfigOptions, VitestAlias } from './vitest.ts';
23
36
 
@@ -0,0 +1,202 @@
1
+ import type { FamilyManifest, ManifestValidation } from './manifest.ts';
2
+
3
+ /**
4
+ Family default god-file limits: a manifest may only lower them.
5
+ */
6
+ export const FAMILY_GOD_FILE_LIMITS = { soft: 300, hard: 400 } as const;
7
+
8
+ type Obj = Record<string, unknown>;
9
+
10
+ const isObj = (value: unknown): value is Obj => typeof value === 'object' && value !== null && !Array.isArray(value);
11
+ const SCOPE_RE = /^@[a-z0-9][a-z0-9-]*$/;
12
+ const NAME_RE = /^[a-z][a-z0-9-]*$/;
13
+ const COVERAGE_KEYS = ['lines', 'branches', 'functions', 'statements'] as const;
14
+
15
+ /**
16
+ Collects errors under a dotted path so every message names its field.
17
+ */
18
+ class Check {
19
+ readonly errors: string[] = [];
20
+ fail(at: string, message: string): void {
21
+ this.errors.push(`${at}: ${message}`);
22
+ }
23
+ /**
24
+ Refuse unknown keys: the closed side.
25
+ */
26
+ keys(at: string, value: Obj, allowed: readonly string[]): void {
27
+ for (const key of Object.keys(value)) {
28
+ if (!allowed.includes(key)) this.fail(`${at}.${key}`, `unknown key (allowed: ${allowed.join(', ')})`);
29
+ }
30
+ }
31
+ obj(at: string, value: unknown): Obj | null {
32
+ if (isObj(value)) return value;
33
+ this.fail(at, 'must be an object');
34
+ return null;
35
+ }
36
+ str(at: string, value: unknown, pattern?: RegExp, hint?: string): value is string {
37
+ if (typeof value !== 'string' || value === '') {
38
+ this.fail(at, 'must be a non-empty string');
39
+ return false;
40
+ }
41
+ if (pattern && !pattern.test(value)) {
42
+ this.fail(at, `${JSON.stringify(value)} is invalid${hint ? ` (${hint})` : ''}`);
43
+ return false;
44
+ }
45
+ return true;
46
+ }
47
+ bool(at: string, value: unknown): void {
48
+ if (typeof value !== 'boolean') this.fail(at, 'must be a boolean');
49
+ }
50
+ strings(at: string, value: unknown): value is string[] {
51
+ if (!Array.isArray(value) || value.some((item) => typeof item !== 'string' || item === '')) {
52
+ this.fail(at, 'must be an array of non-empty strings');
53
+ return false;
54
+ }
55
+ return true;
56
+ }
57
+ }
58
+
59
+ function checkFeatures(c: Check, value: unknown): void {
60
+ const features = c.obj('features', value);
61
+ if (!features) return;
62
+ c.keys('features', features, ['d1', 'web', 'background', 'backupD1', 'durableObjects', 'queues', 'workflows', 'email', 'android']);
63
+ if (features.d1 !== undefined) {
64
+ const d1 = c.obj('features.d1', features.d1);
65
+ if (d1) {
66
+ c.keys('features.d1', d1, ['binding', 'database', 'migrationsDir']);
67
+ c.str('features.d1.binding', d1.binding, /^[A-Z][A-Z0-9_]*$/, 'an UPPER_SNAKE binding name');
68
+ c.str('features.d1.database', d1.database);
69
+ if (d1.migrationsDir !== undefined) c.str('features.d1.migrationsDir', d1.migrationsDir);
70
+ }
71
+ }
72
+ if (features.web !== undefined) {
73
+ const web = c.obj('features.web', features.web);
74
+ if (web) {
75
+ c.keys('features.web', web, ['pages', 'spaShell']);
76
+ c.bool('features.web.pages', web.pages);
77
+ c.bool('features.web.spaShell', web.spaShell);
78
+ }
79
+ }
80
+ for (const flag of ['background', 'backupD1', 'email', 'android'] as const) {
81
+ if (features[flag] !== undefined) c.bool(`features.${flag}`, features[flag]);
82
+ }
83
+ for (const list of ['durableObjects', 'queues', 'workflows'] as const) {
84
+ if (features[list] !== undefined) c.strings(`features.${list}`, features[list]);
85
+ }
86
+ }
87
+
88
+ function checkLayer(c: Check, at: string, layer: Obj): void {
89
+ c.keys(at, layer, ['name', 'dir', 'package', 'mayImport', 'typeOnly', 'forbid', 'forbidMessage', 'http', 'browser']);
90
+ c.str(`${at}.name`, layer.name, NAME_RE, 'lower-case letters, digits and hyphens');
91
+ if (c.str(`${at}.dir`, layer.dir) && (/[*?{}]/.test(layer.dir) || layer.dir.startsWith('/') || layer.dir.split('/').includes('..'))) {
92
+ c.fail(`${at}.dir`, `${JSON.stringify(layer.dir)} must be a repo-relative directory without globs`);
93
+ }
94
+ if (layer.package !== undefined) c.str(`${at}.package`, layer.package);
95
+ if (layer.forbidMessage !== undefined) c.str(`${at}.forbidMessage`, layer.forbidMessage);
96
+ for (const list of ['mayImport', 'typeOnly', 'forbid'] as const) {
97
+ if (layer[list] !== undefined || list === 'mayImport') c.strings(`${at}.${list}`, layer[list]);
98
+ }
99
+ for (const flag of ['http', 'browser'] as const) if (layer[flag] !== undefined) c.bool(`${at}.${flag}`, layer[flag]);
100
+ }
101
+
102
+ function checkLayers(c: Check, value: unknown): void {
103
+ if (!Array.isArray(value)) {
104
+ c.fail('layers', 'must be an array of layers');
105
+ return;
106
+ }
107
+ const names = new Set<string>();
108
+ const dirs = new Set<string>();
109
+ value.forEach((entry: unknown, index) => {
110
+ const at = `layers[${index}]`;
111
+ const layer = c.obj(at, entry);
112
+ if (!layer) return;
113
+ checkLayer(c, at, layer);
114
+ if (typeof layer.name === 'string') {
115
+ if (names.has(layer.name)) c.fail(`${at}.name`, `duplicate layer name ${JSON.stringify(layer.name)}`);
116
+ names.add(layer.name);
117
+ }
118
+ if (typeof layer.dir !== 'string') {
119
+ return;
120
+ }
121
+
122
+ if (dirs.has(layer.dir)) c.fail(`${at}.dir`, `duplicate layer dir ${JSON.stringify(layer.dir)}`);
123
+ dirs.add(layer.dir);
124
+ });
125
+ value.forEach((entry: unknown, index) => {
126
+ if (!isObj(entry)) return;
127
+ for (const list of ['mayImport', 'typeOnly'] as const) {
128
+ const refs = entry[list];
129
+ if (!Array.isArray(refs)) continue;
130
+ for (const ref of refs) {
131
+ if (typeof ref === 'string' && !names.has(ref)) c.fail(`layers[${index}].${list}`, `unknown layer ${JSON.stringify(ref)}`);
132
+ if (list === 'typeOnly' && Array.isArray(entry.mayImport) && entry.mayImport.includes(ref)) {
133
+ c.fail(`layers[${index}].typeOnly`, `${JSON.stringify(ref)} is already in mayImport`);
134
+ }
135
+ }
136
+ }
137
+ });
138
+ }
139
+
140
+ function checkQuality(c: Check, value: unknown): void {
141
+ const quality = c.obj('quality', value);
142
+ if (!quality) return;
143
+ c.keys('quality', quality, ['coverage', 'godFiles']);
144
+ if (quality.coverage !== undefined) checkCoverage(c, quality.coverage);
145
+ if (quality.godFiles !== undefined) checkGodFiles(c, quality.godFiles);
146
+ }
147
+
148
+ function checkGodFiles(c: Check, value: unknown): void {
149
+ const god = c.obj('quality.godFiles', value);
150
+ if (!god) return;
151
+ c.keys('quality.godFiles', god, ['soft', 'hard']);
152
+ for (const key of ['soft', 'hard'] as const) {
153
+ const limit = god[key];
154
+ const ceiling = FAMILY_GOD_FILE_LIMITS[key];
155
+ if (!Number.isInteger(limit) || (limit as number) < 1) c.fail(`quality.godFiles.${key}`, 'must be a positive integer');
156
+ else if ((limit as number) > ceiling) {
157
+ c.fail(`quality.godFiles.${key}`, `${String(limit)} is above the family limit ${ceiling}: god-file limits may only be lowered`);
158
+ }
159
+ }
160
+ if (typeof god.soft === 'number' && typeof god.hard === 'number' && god.soft > god.hard) {
161
+ c.fail('quality.godFiles.soft', 'must not exceed quality.godFiles.hard');
162
+ }
163
+ }
164
+
165
+ function checkCoverage(c: Check, value: unknown): void {
166
+ const coverage = c.obj('quality.coverage', value);
167
+ if (!coverage) return;
168
+ c.keys('quality.coverage', coverage, COVERAGE_KEYS);
169
+ for (const key of COVERAGE_KEYS) {
170
+ const figure = coverage[key];
171
+ if (typeof figure !== 'number' || !(figure >= 0 && figure <= 100)) c.fail(`quality.coverage.${key}`, 'must be a number from 0 to 100');
172
+ }
173
+ }
174
+
175
+ function checkExtensions(c: Check, value: unknown): void {
176
+ const extensions = c.obj('extensions', value);
177
+ if (!extensions) return;
178
+ for (const [key, entry] of Object.entries(extensions)) {
179
+ if (!NAME_RE.test(key)) c.fail(`extensions.${key}`, 'namespace must be lower-case letters, digits and hyphens');
180
+ if (!isObj(entry)) c.fail(`extensions.${key}`, 'must be an object (extensions are namespaced: one object per owner)');
181
+ }
182
+ }
183
+
184
+ /**
185
+ * Validate an already-parsed value. Returns every problem found, not just the
186
+ * first, so one edit can fix them all.
187
+ */
188
+ export function validateManifest(input: unknown): ManifestValidation {
189
+ const c = new Check();
190
+ const root = c.obj('manifest', input);
191
+ if (root) {
192
+ c.keys('manifest', root, ['$schema', 'name', 'scope', 'features', 'layers', 'quality', 'extensions']);
193
+ if (root.$schema !== undefined) c.str('$schema', root.$schema);
194
+ c.str('name', root.name);
195
+ c.str('scope', root.scope, SCOPE_RE, 'an npm scope such as "@mail-meow"');
196
+ if (root.features !== undefined) checkFeatures(c, root.features);
197
+ if (root.layers !== undefined) checkLayers(c, root.layers);
198
+ if (root.quality !== undefined) checkQuality(c, root.quality);
199
+ if (root.extensions !== undefined) checkExtensions(c, root.extensions);
200
+ }
201
+ return c.errors.length > 0 ? { ok: false, errors: c.errors } : { ok: true, manifest: input as FamilyManifest };
202
+ }