@rexezuge/tooling 1.0.0 → 1.0.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.
@@ -0,0 +1,169 @@
1
+ import type tseslint from 'typescript-eslint';
2
+
3
+ /**
4
+ * The layer table behind the repo lint config's import boundaries.
5
+ *
6
+ * Provenance: the seven `no-restricted-imports` blocks in Durable-DAV's
7
+ * `eslint.config.mjs`, with `@durable-dav/` replaced by the caller's scope.
8
+ * Extracted from `eslint.ts` so the boundary rules — the part a repo actually
9
+ * argues about — are their own module rather than the tail of a 640-line
10
+ * config file.
11
+ *
12
+ * The table is data rather than inline blocks so the dynamic-`import()` guard
13
+ * is generated from the same list: a rule that derived its banned set from
14
+ * another rule's configuration would be a second source of truth for the layer
15
+ * table, and that table is what the docs describe.
16
+ */
17
+
18
+ /**
19
+ * The directories the boundary rules cover, in the canonical layout.
20
+ *
21
+ * Kept here, beside the table it scopes: `defineRepoLintConfig` filters the
22
+ * canonical layers by `projectDirs`, and a reader of the layer table should not
23
+ * have to open the config assembly to learn which directories it covers.
24
+ */
25
+ export const DEFAULT_PROJECT_DIRS: readonly string[] = [
26
+ 'packages/shared',
27
+ 'packages/backend-errors',
28
+ 'packages/backend-runtime',
29
+ 'packages/backend-data',
30
+ 'packages/backend-services',
31
+ 'apps/api',
32
+ 'apps/background',
33
+ 'apps/web',
34
+ ];
35
+
36
+ /**
37
+ * One layer's ban list, as the repo-relative package suffixes it may not import.
38
+ *
39
+ * Converged from the four source stacks. `backend-data` and `backend-services`
40
+ * appear in all four; `webdav`/`dav-store` are Durable-DAV's, `provider-clients`
41
+ * is Mail-Meow's and AWS's. A layer only bans what exists in its repo, so the
42
+ * union is safe: a repo without `provider-clients` simply never imports it.
43
+ */
44
+ export interface LayerBan {
45
+ /** Directory the rule is scoped to. */
46
+ readonly dir: string;
47
+ /** Package suffixes (relative to `scope`) that may not be imported from here. */
48
+ readonly ban: readonly string[];
49
+ /** Message shown when the rule fires. */
50
+ readonly message: string;
51
+ /** Type-only imports are allowed, for the DAO boundary in `apps/api`. */
52
+ readonly allowTypeImports?: boolean;
53
+ }
54
+
55
+ /**
56
+ * The layer table, parameterized by `scope`.
57
+ */
58
+ export function layerBans(scope: string): readonly LayerBan[] {
59
+ const at = (name: string): string => `${scope}/${name}`;
60
+ return [
61
+ {
62
+ dir: 'packages/shared',
63
+ ban: [at('*')],
64
+ message: `${scope} packages must not import from other ${scope} packages — this is a zero-dependency base layer`,
65
+ },
66
+ {
67
+ dir: 'packages/backend-errors',
68
+ ban: [at('*')],
69
+ message: `${scope} packages must not import from other ${scope} packages — this is a zero-dependency base layer`,
70
+ },
71
+ {
72
+ dir: 'packages/backend-runtime',
73
+ ban: [at('backend-data'), at('webdav'), at('backend-services'), at('api'), at('background')],
74
+ message: 'backend-runtime must not import from a higher layer',
75
+ },
76
+ {
77
+ dir: 'packages/backend-data',
78
+ ban: [at('backend-runtime'), at('webdav'), at('backend-services'), at('api'), at('background')],
79
+ message: 'backend-data must not import from a higher layer',
80
+ },
81
+ {
82
+ dir: 'packages/backend-services',
83
+ ban: [at('api'), at('background')],
84
+ message: 'backend-services must not import from apps',
85
+ },
86
+ {
87
+ dir: 'apps/api',
88
+ ban: [at('backend-data/dao'), at('backend-data')],
89
+ allowTypeImports: true,
90
+ message: 'apps/api must not import DAOs or backend-data values directly; use backend-services instead',
91
+ },
92
+ {
93
+ dir: 'apps/background',
94
+ ban: [at('api')],
95
+ message: 'apps/background must not import from apps/api',
96
+ },
97
+ // The browser half, and the only layer that bans the namespace wholesale
98
+ // rather than a list of siblings: a backend package imported by the SPA
99
+ // typechecks and then fails at bundle time, with the error pointing at the
100
+ // bundler rather than at the boundary. Edge-Sonic is the source; the others had
101
+ // no block for it at all, which is how their layer table's "may import: the
102
+ // browser" was a convention instead of a gate.
103
+ {
104
+ dir: 'apps/web',
105
+ ban: [at('*')],
106
+ message: `${at('apps/web')} ships zero backend dependencies — this module is the SPA's own copy`,
107
+ },
108
+ ];
109
+ }
110
+
111
+ /**
112
+ * One argument to `tseslint.config()`, named here so the boundary builders
113
+ * return the assembled type rather than a lookalike the assembly then has to
114
+ * be argued into accepting.
115
+ */
116
+ type ConfigInput = Parameters<typeof tseslint.config>[number];
117
+
118
+ /**
119
+ * The `no-restricted-imports` entries for one layer.
120
+ *
121
+ * Written as `group` patterns rather than exact `paths`, so `@myapp/backend-data`
122
+ * and `@myapp/backend-data/dao` are both caught by one entry. `allowTypeImports`
123
+ * is passed through only where the source repos set it, because `apps/api`
124
+ * legitimately types its filters and models against DAO shapes.
125
+ */
126
+ export function restrictedImports(bans: readonly LayerBan[]): ConfigInput[] {
127
+ return bans.map(({ dir, ban, message, allowTypeImports }) => ({
128
+ files: [`${dir}/**/*.{ts,js,mts,cts,mjs,cjs}`],
129
+ rules: {
130
+ 'no-restricted-imports': [
131
+ 'error',
132
+ {
133
+ patterns: ban.map((group) => ({
134
+ group: [group, `${group}/*`],
135
+ message,
136
+ ...(allowTypeImports === true && { allowTypeImports: true }),
137
+ })),
138
+ },
139
+ ],
140
+ },
141
+ }));
142
+ }
143
+
144
+ /**
145
+ * The dynamic-`import()` guard, generated from the same table.
146
+ *
147
+ * `no-restricted-imports` reads `ImportDeclaration` nodes only; a dynamic
148
+ * `import()` is an `ImportExpression`, and this ESLint version does not report it
149
+ * under that rule at all. Edge-Sonic verified this rather than assumed it — a
150
+ * static import of a restricted specifier from the same file is an `error`, and
151
+ * the identical specifier reached through `await import(...)` is silent. That
152
+ * hole was load-bearing there: the credential path reached a banned module
153
+ * through it. `no-restricted-syntax` sees `ImportExpression`, so the boundary is
154
+ * stated a second way.
155
+ */
156
+ export function restrictedDynamicImports(bans: readonly LayerBan[]): ConfigInput[] {
157
+ return bans.map(({ dir, ban, message }) => ({
158
+ files: [`${dir}/**/*.{ts,js,mts,cts,mjs,cjs}`],
159
+ rules: {
160
+ 'no-restricted-syntax': [
161
+ 'error',
162
+ ...ban.map((specifier) => ({
163
+ selector: `ImportExpression[source.type='Literal'][source.value=/^${specifier.replaceAll('/', '\\/')}/]`,
164
+ message: `A dynamic import() is not covered by no-restricted-imports, so this layer reaches \`${specifier}\` through the one syntax that gate does not see. Both say no: ${message}`,
165
+ })),
166
+ ],
167
+ },
168
+ }));
169
+ }
@@ -0,0 +1,276 @@
1
+ /**
2
+ * The rule-override blocks of the repo lint config.
3
+ *
4
+ * Extracted from `eslint.ts` with the boundary rules: each block is a plain
5
+ * rules object with the provenance comment that says *why* it is set to this
6
+ * value, because a per-rule decision with no reason attached is a decision the
7
+ * next reader re-litigates. `eslint.ts` composes these; this file is where a
8
+ * rule's story lives.
9
+ */
10
+
11
+ /**
12
+ * TypeScript rules, identical in all four source stacks.
13
+ */
14
+ export const TYPESCRIPT_RULES: Readonly<Record<string, unknown>> = {
15
+ '@typescript-eslint/no-unused-vars': ['error', { argsIgnorePattern: '^_', varsIgnorePattern: '^_' }],
16
+ // Allow `void expr` for intentional fire-and-forget in Workers.
17
+ '@typescript-eslint/no-floating-promises': ['error', { ignoreVoid: true }],
18
+ // Relax the unsafe-any rules to warn: the external API boundaries (Cloudflare
19
+ // bindings, provider SDKs) are typed `any` upstream, and the alternative is a
20
+ // config that cannot be adopted.
21
+ '@typescript-eslint/no-explicit-any': 'warn',
22
+ '@typescript-eslint/no-unsafe-assignment': 'warn',
23
+ '@typescript-eslint/no-unsafe-member-access': 'warn',
24
+ '@typescript-eslint/no-unsafe-call': 'warn',
25
+ '@typescript-eslint/no-unsafe-return': 'warn',
26
+ '@typescript-eslint/no-unsafe-argument': 'warn',
27
+ // JSX event handlers and hook callback objects commonly use async functions
28
+ // where void is expected.
29
+ '@typescript-eslint/no-misused-promises': ['error', { checksVoidReturn: { attributes: false, properties: false } }],
30
+ // An `async` function with no `await`: every handler and DAO method is
31
+ // `async` by shape so a future `await` does not change its signature.
32
+ '@typescript-eslint/require-await': 'off',
33
+ // `await` on a value the types say is not thenable, where the value is a
34
+ // `PromiseLike` from an interface declared that way.
35
+ '@typescript-eslint/await-thenable': 'off',
36
+ };
37
+
38
+ /**
39
+ * Unicorn and SonarJS rules carried from the source repos, each off for a
40
+ * stated reason.
41
+ *
42
+ * This is the family's "deliberately does not follow" block: every entry is
43
+ * off because complying would make the code worse for what the project is,
44
+ * and each is listed rather than dropped so the decision stays reviewable.
45
+ */
46
+ export const UNICORN_RULES: Readonly<Record<string, unknown>> = {
47
+ // Codebase uses ctx, req, res, env, err, util, db, dao, etc. — too invasive
48
+ // to rename.
49
+ 'unicorn/prevent-abbreviations': 'off',
50
+ // D1/DAO layer returns null; disabling this avoids mass rewrites.
51
+ 'unicorn/no-null': 'off',
52
+ // Monorepo uses CommonJS-compatible module style in some configs.
53
+ 'unicorn/prefer-module': 'off',
54
+ // Top-level await not available in all Workers entry points.
55
+ 'unicorn/prefer-top-level-await': 'off',
56
+ // Error subclassing via `new MyError()` is intentional in backend-errors.
57
+ 'unicorn/custom-error-definition': 'off',
58
+ // Allow process.exit in build/script files.
59
+ 'unicorn/no-process-exit': 'off',
60
+ // Array reduce is used intentionally in analytics/data transformation.
61
+ 'unicorn/no-array-reduce': 'off',
62
+ // Allow Number() — parseInt/parseFloat are used in some cases intentionally.
63
+ 'unicorn/prefer-number-properties': ['error', { checkInfinity: false }],
64
+ // Allow nested ternaries in JSX (React render patterns).
65
+ 'unicorn/no-nested-ternary': 'off',
66
+ // Allow Array.from — codebase uses it for iterables.
67
+ 'unicorn/prefer-spread': 'off',
68
+ // Entire codebase uses PascalCase for TS files; kebab-case would require
69
+ // mass renames.
70
+ 'unicorn/filename-case': 'off',
71
+ // Established names should not be force-renamed.
72
+ 'unicorn/name-replacements': 'off',
73
+ // Zod schema builder chains and other deep method chains are intentional.
74
+ 'unicorn/max-nested-calls': 'off',
75
+ // import.meta.dirname is not available in all test environments.
76
+ 'unicorn/prefer-import-meta-properties': 'off',
77
+ // Codebase uses `err` as catch parameter name throughout.
78
+ 'unicorn/catch-error-name': 'off',
79
+ // Established boolean param names (retryable, enabled, etc.).
80
+ 'unicorn/consistent-boolean-name': 'off',
81
+ // Uint8Array#toBase64 / fromBase64 are not in all Workers runtime versions.
82
+ 'unicorn/prefer-uint8array-base64': 'off',
83
+ // Class member ordering would require extensive restructuring.
84
+ 'unicorn/consistent-class-member-order': 'off',
85
+ // API response fields use verb prefixes by convention.
86
+ 'unicorn/no-non-function-verb-prefix': 'off',
87
+ // forEach is used intentionally throughout the provider and utility layers.
88
+ 'unicorn/no-for-each': 'off',
89
+ // .then() chains in DAO and provider layers are often intentional.
90
+ 'unicorn/prefer-await': 'warn',
91
+ // Callback references (e.g. .map(Number)) are sometimes intentional.
92
+ 'unicorn/no-array-callback-reference': 'warn',
93
+ // toSorted() is ES2023 and may not be in all tsconfig lib targets.
94
+ 'unicorn/no-array-sort': 'warn',
95
+ // Early-return guard clauses are the established style; the rule only
96
+ // rewrites the final guard of a ladder, which yields asymmetric mixed style
97
+ // and long inline ternaries. Off in Mail-Meow and Edge-Sonic; canonical here
98
+ // because it is the family's established style.
99
+ 'unicorn/prefer-ternary': 'off',
100
+ // `(await x).y` -> a named intermediate. Fires constantly in the tests,
101
+ // where destructuring beside the assertion it serves is clearer.
102
+ 'unicorn/no-await-expression-member': 'off',
103
+ // `Number(x)` over `+x`: the `+` form is used where an explicit typeof check
104
+ // has already narrowed the operand.
105
+ 'unicorn/prefer-number-coercion': 'off',
106
+ // Code-point iteration: the byte-level readers index deliberately, because
107
+ // the offset *is* what they are reading.
108
+ 'unicorn/prefer-code-point': 'off',
109
+ // `if (!x) return;` over a compound condition: one guard per line, each with
110
+ // its own comment, is what keeps endpoint guards readable.
111
+ 'unicorn/prefer-simple-condition-first': 'off',
112
+ // Module-scope `let` assigned from `beforeEach` in the test harnesses.
113
+ 'unicorn/no-top-level-assignment-in-function': 'off',
114
+ // Sequential `for...of` with `await` in the DAOs — D1's subrequest budget is
115
+ // the scarce resource.
116
+ 'unicorn/no-unreadable-for-of-expression': 'off',
117
+ // `Object.hasOwn` over `in`: used where a prototype-chain hit is harmless.
118
+ 'unicorn/no-computed-property-existence-check': 'off',
119
+ // A labeled `break` out of two loops.
120
+ 'unicorn/no-break-in-nested-loop': 'off',
121
+ // `this` outside a class body: the module-level cache singletons document
122
+ // their `this` contract in prose.
123
+ 'unicorn/no-this-outside-of-class': 'off',
124
+ // A class named inside its own static method.
125
+ 'unicorn/class-reference-in-static-methods': 'off',
126
+ // Assigning `globalThis.fetch` in a test — the only way to intercept the
127
+ // ambient fetch in Node without a module mock.
128
+ 'unicorn/no-global-object-property-assignment': 'off',
129
+ // `(a ? b : c) && d`: written longhand so each precedence decision is
130
+ // visible.
131
+ 'unicorn/prefer-logical-operator-over-ternary': 'off',
132
+ // `children[0]` in the XML helpers, which index a child list positionally.
133
+ 'unicorn/better-dom-traversing': 'off',
134
+ // `entries()` -> `keys()`/`values()`: the full entry is destructured.
135
+ 'unicorn/prefer-iterator-to-array': 'off',
136
+ // `.map(fn, thisArg)`: rejected on purpose.
137
+ 'unicorn/no-array-method-this-argument': 'off',
138
+ // A module-scope function that closes over nothing.
139
+ 'unicorn/consistent-function-scoping': 'off',
140
+ // `foo[0] === 'a' || foo[0] === 'b'` written longhand where the
141
+ // alternatives are not adjacent.
142
+ 'unicorn/prefer-includes-over-repeated-comparisons': 'off',
143
+ // A `type` alias over an inline union, where the name is what makes the
144
+ // signature and its doc comment readable.
145
+ 'sonarjs/use-type-alias': 'off',
146
+ // A short local alias for a type imported from a protocol package.
147
+ 'sonarjs/redundant-type-aliases': 'off',
148
+ // `type: value` narrowing the other way, where both spellings appear in the
149
+ // same schema and the code follows whichever the spec uses there.
150
+ 'sonarjs/no-nested-assignment': 'off',
151
+ // `Number.isInteger` plus a separate range check, where the bounds come from
152
+ // the caller's own options in one place.
153
+ 'unicorn/prefer-number-is-safe-integer': 'off',
154
+ // `\u{...}` over a `\xNN` escape: the table is written in the byte form the
155
+ // spec prints.
156
+ 'unicorn/prefer-unicode-code-point-escapes': 'off',
157
+ // `self.x = this.x` in an entry model: the alias makes the verbatim
158
+ // round-trip explicit.
159
+ 'unicorn/no-this-assignment': 'off',
160
+ // Building a `Set` at module scope from a constant list, for O(1) membership
161
+ // on a path that runs per parameter.
162
+ 'unicorn/no-top-level-side-effects': 'off',
163
+ // A conditional whose branches are identical, kept where the two branches
164
+ // are named separately to document that they are meant to diverge.
165
+ 'sonarjs/no-all-duplicated-branches': 'off',
166
+ // An `else` after a `return`: the flat form keeps the remaining cases at one
167
+ // indent level in the dispatch tables.
168
+ 'unicorn/prefer-else-if': 'off',
169
+ // A nested ternary in a sort comparator, where the three-way order is the
170
+ // point.
171
+ 'unicorn/prefer-minimal-ternary': 'off',
172
+ // `void promise` where initiating the call is the point and the rejection is
173
+ // handled at a named site elsewhere.
174
+ 'sonarjs/void-use': 'off',
175
+ // `x === undefined` reported as always-true/false. With
176
+ // `noUncheckedIndexedAccess` on, the guard is exactly right.
177
+ 'sonarjs/different-types-comparison': 'off',
178
+ // An accumulating loop with a sequential `await` in it, over D1 writes.
179
+ 'unicorn/prefer-array-from-async': 'off',
180
+ };
181
+
182
+ /**
183
+ * SonarJS rules the sources turned from errors into advisories, with the
184
+ * threshold raised to a value that has actually held.
185
+ */
186
+ export const SONARJS_RULES: Readonly<Record<string, unknown>> = {
187
+ // Raise duplicate-string threshold to avoid flagging intentional repeated
188
+ // literals like provider IDs.
189
+ 'sonarjs/no-duplicate-string': ['warn', { threshold: 5 }],
190
+ // Cognitive complexity — warn rather than error, so the ratchet can move
191
+ // without a red build. Raise the number only as files are decomposed.
192
+ 'sonarjs/cognitive-complexity': ['warn', 20],
193
+ // False positives: connection method names like 'imap-password' and field
194
+ // names like 'password_hash'.
195
+ 'sonarjs/no-hardcoded-passwords': 'off',
196
+ // Third-party deprecations are warnings, not errors.
197
+ 'sonarjs/deprecation': 'warn',
198
+ // Nested ternaries in complex data-mapping code.
199
+ 'sonarjs/no-nested-conditional': 'warn',
200
+ // React component props are commonly not marked Readonly<>.
201
+ 'sonarjs/prefer-read-only-props': 'warn',
202
+ // Static readonly properties require invasive refactoring.
203
+ 'sonarjs/public-static-readonly': 'warn',
204
+ // Nested template literals in SQL queries and prompt construction.
205
+ 'sonarjs/no-nested-template-literals': 'warn',
206
+ };
207
+
208
+ /**
209
+ * Test-suite overrides.
210
+ *
211
+ * `test/**` is deliberately *not* in the config's ignores list. Durable-DAV,
212
+ * AWS and Mail-Meow all ignored it, and ~200 KB of test code had accumulated
213
+ * violations that nothing reported. This block puts the suite back under the
214
+ * same rules as the rest of the workspace and switches off only the handful
215
+ * whose findings are structural artefacts of test code rather than defects.
216
+ * It does not disable correctness rules: the unused-variable, dead-store,
217
+ * regex and sorting findings in the suite are real and are fixed, not
218
+ * suppressed.
219
+ */
220
+ export const TEST_RULES: Readonly<Record<string, unknown>> = {
221
+ // `it('…', async () => …)` is the Vitest idiom.
222
+ '@typescript-eslint/no-misused-promises': ['error', { checksVoidReturn: { arguments: false, attributes: false } }],
223
+ // Unbound method is a common false positive in mock assertions like
224
+ // expect(fn).toHaveBeenCalledWith(...).
225
+ '@typescript-eslint/unbound-method': 'off',
226
+ // Test helpers and stubs routinely use async functions without await.
227
+ '@typescript-eslint/require-await': 'off',
228
+ // Redundant type constituents appear in typed mock stubs.
229
+ '@typescript-eslint/no-redundant-type-constituents': 'off',
230
+ // `as never` casts are the standard fake-DB double pattern in tests.
231
+ '@typescript-eslint/no-unnecessary-type-assertion': 'off',
232
+ // Promise.withResolvers() and function-scoping refactors are cosmetic.
233
+ 'unicorn/prefer-promise-with-resolvers': 'off',
234
+ 'unicorn/consistent-function-scoping': 'off',
235
+ // Fake-DB builders push-then-return and sort without comparators.
236
+ 'unicorn/no-return-array-push': 'off',
237
+ 'unicorn/require-array-sort-compare': 'off',
238
+ // Iterator-helper rewrites churn test fakes with no runtime benefit.
239
+ 'unicorn/prefer-iterator-helpers': 'off',
240
+ 'unicorn/prefer-iterator-to-array': 'off',
241
+ // String replacement with test-driven values is intentional in assertions.
242
+ 'unicorn/no-unsafe-string-replacement': 'off',
243
+ // Fake-D1 doubles await a DAO thunk and call straight onto the result.
244
+ 'unicorn/no-await-expression-member': 'off',
245
+ // `void promise` marks a deliberately unawaited promise in a test.
246
+ 'sonarjs/void-use': 'off',
247
+ // A test asserting request routing has to name `http://` hosts, and a proxy
248
+ // test has to name a loopback upstream. Both are the subject matter, not
249
+ // leaked configuration. `unicorn/prefer-https` must stay off here and this
250
+ // is not a style preference: it rewrites `http://` to `https://` *inside
251
+ // string literals*, and `--fix` applies it silently.
252
+ 'sonarjs/no-clear-text-protocols': 'off',
253
+ 'sonarjs/no-hardcoded-ip': 'off',
254
+ 'unicorn/prefer-https': 'off',
255
+ // sonarjs/assertions-in-tests fires false positives when test helpers handle
256
+ // assertions indirectly.
257
+ 'sonarjs/assertions-in-tests': 'off',
258
+ // sonarjs/no-extra-arguments fires incorrectly on Vitest mock overloads.
259
+ 'sonarjs/no-extra-arguments': 'off',
260
+ // Union/inline types in test fakes are more readable than aliases.
261
+ 'sonarjs/use-type-alias': 'off',
262
+ // Alphabetical-sort rule fights deterministic fixture ordering.
263
+ 'sonarjs/no-alphabetical-sort': 'off',
264
+ // Repeated string literals in fixtures/assertions are clearer inline.
265
+ 'sonarjs/no-duplicate-string': 'off',
266
+ // Fake-D1 doubles break out of a nested loop to model a statement miss.
267
+ 'unicorn/no-break-in-nested-loop': 'off',
268
+ // Fixtures are naturally built with sort()/for…of over composed expressions.
269
+ 'unicorn/no-array-sort': 'off',
270
+ 'unicorn/no-unreadable-for-of-expression': 'off',
271
+ 'unicorn/no-useless-template-literals': 'off',
272
+ 'unicorn/no-declarations-before-early-exit': 'off',
273
+ 'unicorn/prefer-includes-over-repeated-comparisons': 'off',
274
+ 'sonarjs/prefer-specific-assertions': 'off',
275
+ 'sonarjs/no-inverted-boolean-check': 'off',
276
+ };