@sssb/eslint-plugin 0.0.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/package.json +40 -5
- package/src/app-config.js +401 -0
- package/src/check-fences.d.ts +20 -0
- package/src/check-fences.js +269 -0
- package/src/import-ban.js +150 -0
- package/src/index.d.ts +22 -0
- package/src/index.js +31 -0
- package/src/patterns.js +318 -0
- package/src/probes.js +129 -0
- package/src/rules.js +611 -0
- package/README.md +0 -3
package/src/rules.js
ADDED
|
@@ -0,0 +1,611 @@
|
|
|
1
|
+
// EVERY sssb/* RULE, app-side and SSSB-internal alike (ADR-0014, part 4). Flat config throws `Cannot redefine
|
|
2
|
+
// plugin "sssb"` when two blocks matching one file bind `sssb` to different objects, and SSSB's own repository
|
|
3
|
+
// binds it both in its internal blocks and through the app preset, so there is one plugin object and it carries
|
|
4
|
+
// every rule; the preset enables only the app-side ones.
|
|
5
|
+
//
|
|
6
|
+
// No rule reads a file when this module loads. The internal rules that need SSSB's repository (the package's
|
|
7
|
+
// manifest, the repo root) take it as an option and read it when they run, so importing the plugin works in any
|
|
8
|
+
// adopter's config.
|
|
9
|
+
import { existsSync, readFileSync, realpathSync, statSync } from 'node:fs'
|
|
10
|
+
import { basename, dirname, join, relative, resolve } from 'node:path'
|
|
11
|
+
import { fileURLToPath } from 'node:url'
|
|
12
|
+
import reactPlugin from 'eslint-plugin-react'
|
|
13
|
+
import {
|
|
14
|
+
declarationImportBan,
|
|
15
|
+
declarationlessImportBan,
|
|
16
|
+
declarationlessVisitors,
|
|
17
|
+
declarationVisitors,
|
|
18
|
+
literalSpecifier,
|
|
19
|
+
matchesPatterns,
|
|
20
|
+
syntaxBan,
|
|
21
|
+
} from './import-ban.js'
|
|
22
|
+
import {
|
|
23
|
+
a11yLiteralSelector,
|
|
24
|
+
appCodePatterns,
|
|
25
|
+
appRealAdapterDynamicSelector,
|
|
26
|
+
appRealAdapterPattern,
|
|
27
|
+
appRealAdapterStaticPattern,
|
|
28
|
+
coreFrameworkPattern,
|
|
29
|
+
getDbComputedSelector,
|
|
30
|
+
getDbDestructureSelector,
|
|
31
|
+
getDbSelector,
|
|
32
|
+
getDbStringSelector,
|
|
33
|
+
kitRealAdapterPattern,
|
|
34
|
+
nextFontPattern,
|
|
35
|
+
nodeModulesPathPattern,
|
|
36
|
+
processEnvSelector,
|
|
37
|
+
runModeEnvDestructureSelector,
|
|
38
|
+
runModeEnvSelector,
|
|
39
|
+
vendorSdkPattern,
|
|
40
|
+
} from './patterns.js'
|
|
41
|
+
|
|
42
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
43
|
+
// THE APP-SIDE FENCES. Each was a no-restricted-imports pattern or a no-restricted-syntax selector until
|
|
44
|
+
// ADR-0014's P6, and is now a rule of its own, so a later block that sets either core rule cannot drop it.
|
|
45
|
+
|
|
46
|
+
// The vendor list is SSSB's, and an app adds its own adapters' SDKs to it in its package.json (`sssb.vendors`), which
|
|
47
|
+
// the preset passes to both halves as this option. SSSB's list is always part of the group, and the schema refuses a
|
|
48
|
+
// leading `!` (a gitignore negation), so the option adds patterns and cannot remove one of SSSB's. `sssb check-fences`
|
|
49
|
+
// still compares it exactly with the app's package.json, so a later block cannot swap the app's list for another.
|
|
50
|
+
const vendorsOption = {
|
|
51
|
+
type: 'object',
|
|
52
|
+
// A leading `!` is a gitignore negation: it would take a vendor OFF the list, so the schema refuses it.
|
|
53
|
+
properties: { vendors: { type: 'array', items: { type: 'string', minLength: 1, pattern: '^[^!\\s]' } } },
|
|
54
|
+
additionalProperties: false,
|
|
55
|
+
}
|
|
56
|
+
const vendorGroupOf = (context) => [...vendorSdkPattern.group, ...(context.options[0]?.vendors ?? [])]
|
|
57
|
+
// One rule module per distinct vendor list, built once: `build(group)` makes the rule that fences that group.
|
|
58
|
+
const withAppVendors = (build) => {
|
|
59
|
+
const built = new Map()
|
|
60
|
+
const ruleFor = (group) => {
|
|
61
|
+
const key = JSON.stringify(group)
|
|
62
|
+
if (!built.has(key)) built.set(key, build(group))
|
|
63
|
+
return built.get(key)
|
|
64
|
+
}
|
|
65
|
+
const { meta } = ruleFor(vendorSdkPattern.group)
|
|
66
|
+
return {
|
|
67
|
+
meta: { ...meta, schema: [vendorsOption] },
|
|
68
|
+
create: (context) => ruleFor(vendorGroupOf(context)).create(context),
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const vendorStatic = withAppVendors((group) =>
|
|
73
|
+
declarationImportBan({
|
|
74
|
+
description: 'Vendor SDKs are imported only inside an adapters directory.',
|
|
75
|
+
patterns: [{ ...vendorSdkPattern, group }],
|
|
76
|
+
}),
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
// The dynamic half keeps its OWN reading of the vendor list. The two disagree at the edges: the declaration half
|
|
80
|
+
// matches a bare name at any depth and ignores case, so its `pg` flags a local `./pg` and its `@clerk/*` flags
|
|
81
|
+
// `@CLERK/nextjs`; this rule flags neither. Bringing them together means anchoring the bare names in
|
|
82
|
+
// vendorSdkPattern first, which changes the declaration half, so it is left for its own change.
|
|
83
|
+
const isVendorSpecifier = (group, specifier) =>
|
|
84
|
+
group.some((pattern) =>
|
|
85
|
+
pattern.endsWith('/*')
|
|
86
|
+
? specifier.startsWith(pattern.slice(0, -1)) && specifier.length > pattern.length - 1
|
|
87
|
+
: specifier === pattern || specifier.startsWith(`${pattern}/`),
|
|
88
|
+
)
|
|
89
|
+
const vendorDeclarationlessRule =
|
|
90
|
+
"Vendor SDKs live only in packages/kit/src/adapters/ (SSSB's ports) or apps/<app>/src/adapters/real/ " +
|
|
91
|
+
'(a port the app owns) — code against the port instead (docs/recipes/app-owned-adapter.md).'
|
|
92
|
+
const vendorDynamic = withAppVendors((group) =>
|
|
93
|
+
declarationlessImportBan({
|
|
94
|
+
description: 'Vendor SDKs are not imported dynamically outside an adapters directory.',
|
|
95
|
+
what: 'a vendor SDK',
|
|
96
|
+
matches: (specifier) => (isVendorSpecifier(group, specifier) ? [vendorDeclarationlessRule] : []),
|
|
97
|
+
}),
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
const nextFontGoogle = declarationImportBan({
|
|
101
|
+
description: 'next/font/google phones home at build; dev stays hermetic.',
|
|
102
|
+
patterns: [nextFontPattern],
|
|
103
|
+
})
|
|
104
|
+
const realAdapterViaRegistry = declarationImportBan({
|
|
105
|
+
description: 'An app reaches its real adapters through its registry, never by a static import.',
|
|
106
|
+
patterns: [appRealAdapterPattern],
|
|
107
|
+
})
|
|
108
|
+
const staticRealAdapterInAdapters = declarationImportBan({
|
|
109
|
+
description: "Inside an app's adapters directory, real/ is loaded only with import().",
|
|
110
|
+
patterns: [appRealAdapterStaticPattern],
|
|
111
|
+
})
|
|
112
|
+
const kitRealAdapterInAdapters = declarationImportBan({
|
|
113
|
+
description: "Outside an app's own real adapters, SSSB's real adapters are loaded only with import().",
|
|
114
|
+
patterns: [kitRealAdapterPattern],
|
|
115
|
+
// What the fence guards is the vendor SDK LOADING, and a type-only declaration loads nothing.
|
|
116
|
+
allowTypeOnly: true,
|
|
117
|
+
})
|
|
118
|
+
const dynamicRealAdapter = syntaxBan({
|
|
119
|
+
description: "Only an app's registry loads real/.",
|
|
120
|
+
selectors: { dynamic: appRealAdapterDynamicSelector },
|
|
121
|
+
})
|
|
122
|
+
const processEnv = syntaxBan({
|
|
123
|
+
description: 'process.env is read only inside an adapters directory.',
|
|
124
|
+
selectors: { env: processEnvSelector },
|
|
125
|
+
})
|
|
126
|
+
const runModeEnv = syntaxBan({
|
|
127
|
+
description: "An app's real adapter never reads the run mode itself.",
|
|
128
|
+
selectors: { member: runModeEnvSelector, destructure: runModeEnvDestructureSelector },
|
|
129
|
+
})
|
|
130
|
+
const a11yLiteral = syntaxBan({
|
|
131
|
+
description: 'Accessible names, placeholders, titles and alt text come from the catalog, never a literal.',
|
|
132
|
+
selectors: { literal: a11yLiteralSelector },
|
|
133
|
+
})
|
|
134
|
+
|
|
135
|
+
// THE i18n LITERAL BAN (ADR-0008) under an id of its own: eslint-plugin-react's jsx-no-literals with the options
|
|
136
|
+
// SSSB requires, fixed. It was `react/jsx-no-literals` with those options in the repo's config, and an adopter's own
|
|
137
|
+
// block that configured that rule for their own reasons (or turned it off for a directory) replaced them. This rule
|
|
138
|
+
// takes no options; it runs react's rule with these.
|
|
139
|
+
const JSX_NO_LITERALS_OPTIONS = [{ noStrings: true, ignoreProps: true, allowedStrings: [] }]
|
|
140
|
+
const reactJsxNoLiterals = reactPlugin.rules['jsx-no-literals']
|
|
141
|
+
// Taken when the plugin loads: the rule object is eslint-plugin-react's, which an app's config can reach and rewrite.
|
|
142
|
+
const reactJsxNoLiteralsCreate = reactJsxNoLiterals.create
|
|
143
|
+
/** @type {import('eslint').Rule.RuleModule} */
|
|
144
|
+
const jsxLiterals = {
|
|
145
|
+
meta: {
|
|
146
|
+
type: 'problem',
|
|
147
|
+
docs: { description: 'UI code holds no hard-coded strings: all copy goes through next-intl (ADR-0008).' },
|
|
148
|
+
schema: [],
|
|
149
|
+
messages: reactJsxNoLiterals.meta.messages,
|
|
150
|
+
},
|
|
151
|
+
create(context) {
|
|
152
|
+
// Every other property (report, sourceCode, filename, …) is the real context's, through the prototype.
|
|
153
|
+
return reactJsxNoLiteralsCreate(Object.create(context, { options: { value: JSX_NO_LITERALS_OPTIONS } }))
|
|
154
|
+
},
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
158
|
+
// THE TENANCY BAN (ADR-0004): the getDb selectors, each with its message.
|
|
159
|
+
/** @type {import('eslint').Rule.RuleModule} */
|
|
160
|
+
const rawDbHandle = {
|
|
161
|
+
meta: {
|
|
162
|
+
type: 'problem',
|
|
163
|
+
docs: { description: "App code and SSSB's screens reach the database through db.withTenant()." },
|
|
164
|
+
schema: [],
|
|
165
|
+
messages: {
|
|
166
|
+
member: getDbSelector.message,
|
|
167
|
+
computed: getDbComputedSelector.message,
|
|
168
|
+
destructure: getDbDestructureSelector.message,
|
|
169
|
+
string: getDbStringSelector.message,
|
|
170
|
+
},
|
|
171
|
+
},
|
|
172
|
+
create(context) {
|
|
173
|
+
const report = (messageId) => (node) => context.report({ node, messageId })
|
|
174
|
+
// A spy's key in a test file is the one string left alone outside the selector (see getDbStringSelector).
|
|
175
|
+
const inTestFile = /\.test\.tsx?$/.test(context.filename)
|
|
176
|
+
const isSpyKey = (node) =>
|
|
177
|
+
node.parent?.type === 'CallExpression' &&
|
|
178
|
+
node.parent.arguments.includes(node) &&
|
|
179
|
+
node.parent.callee.type === 'MemberExpression' &&
|
|
180
|
+
/^(vi|jest)$/.test(node.parent.callee.object.name ?? '') &&
|
|
181
|
+
node.parent.callee.property.name === 'spyOn'
|
|
182
|
+
return {
|
|
183
|
+
[getDbSelector.selector]: report('member'),
|
|
184
|
+
[getDbComputedSelector.selector]: report('computed'),
|
|
185
|
+
[getDbDestructureSelector.selector]: report('destructure'),
|
|
186
|
+
[getDbStringSelector.selector]: (node) => {
|
|
187
|
+
if (inTestFile && isSpyKey(node)) return
|
|
188
|
+
report('string')(node)
|
|
189
|
+
},
|
|
190
|
+
}
|
|
191
|
+
},
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
// NO RAW mkdtemp IN TESTS. A test that calls `mkdtemp`/`mkdtempSync` itself leaves the directory behind on every
|
|
195
|
+
// run, and enough runs filled a dev machine's temp filesystem past 100GB. Tests make scratch directories through
|
|
196
|
+
// makeTestTmpDir() from @sssb/tools/testing/tmp-dir (the framework's own tests through its copy in
|
|
197
|
+
// packages/kit/src/testing/tmp-dir.ts), which queues the removal. Deliberately narrow: it matches the call by the NAME it is made under
|
|
198
|
+
// — bare `mkdtempSync(…)`, `fs.mkdtempSync(…)`, `fsp.mkdtemp(…)`, `await mkdtemp(…)` — and not a renamed import
|
|
199
|
+
// (`import { mkdtemp as m }`) or a computed key. `sssb check-tmpdir-leak`'s per-run TMPDIR sweep is what bounds the damage
|
|
200
|
+
// if one slips by.
|
|
201
|
+
/** @type {import('eslint').Rule.RuleModule} */
|
|
202
|
+
const directMkdtemp = {
|
|
203
|
+
meta: {
|
|
204
|
+
type: 'problem',
|
|
205
|
+
docs: { description: 'Tests make scratch directories through makeTestTmpDir(), never a raw mkdtemp.' },
|
|
206
|
+
schema: [],
|
|
207
|
+
messages: {
|
|
208
|
+
direct:
|
|
209
|
+
'`{{name}}()` leaves its directory behind on every test run. Use makeTestTmpDir() / ' +
|
|
210
|
+
'makeTestTmpDirAsync() from @sssb/tools/testing/tmp-dir (in the framework, makeTestTmpDir() from ' +
|
|
211
|
+
'packages/kit/src/testing/tmp-dir.ts), which removes the directory when the test file finishes — ' +
|
|
212
|
+
'or, in a Playwright spec, testInfo.outputPath(), which Playwright ' +
|
|
213
|
+
'clears at the start of every run.',
|
|
214
|
+
},
|
|
215
|
+
},
|
|
216
|
+
create(context) {
|
|
217
|
+
const report = (node, name) => context.report({ node, messageId: 'direct', data: { name } })
|
|
218
|
+
return {
|
|
219
|
+
'CallExpression[callee.type="Identifier"][callee.name=/^mkdtemp(Sync)?$/]': (node) =>
|
|
220
|
+
report(node, node.callee.name),
|
|
221
|
+
'CallExpression[callee.type="MemberExpression"][callee.computed=false][callee.property.name=/^mkdtemp(Sync)?$/]':
|
|
222
|
+
(node) => report(node, node.callee.property.name),
|
|
223
|
+
}
|
|
224
|
+
},
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
228
|
+
// SSSB-INTERNAL FENCES: rules SSSB's own repository enables over packages/kit. They ship in the same object (see
|
|
229
|
+
// the top of this file); no preset enables them.
|
|
230
|
+
|
|
231
|
+
// THE FRAMEWORK/APP FENCE and @sssb/kit/core's framework ban, in declarations and outside them.
|
|
232
|
+
const appImport = declarationImportBan({
|
|
233
|
+
description: 'Framework code reaches app content only through the @sssb/app-config/* seam.',
|
|
234
|
+
patterns: appCodePatterns,
|
|
235
|
+
})
|
|
236
|
+
const appImportDynamic = declarationlessImportBan({
|
|
237
|
+
description: 'Framework code does not reach app content by import(), require() or a type import().',
|
|
238
|
+
what: 'app content',
|
|
239
|
+
matches: matchesPatterns(appCodePatterns),
|
|
240
|
+
})
|
|
241
|
+
const coreFrameworkImport = declarationImportBan({
|
|
242
|
+
description: '@sssb/kit/core imports no framework.',
|
|
243
|
+
patterns: [coreFrameworkPattern],
|
|
244
|
+
})
|
|
245
|
+
const coreFrameworkImportDynamic = declarationlessImportBan({
|
|
246
|
+
description: '@sssb/kit/core does not reach a framework by import(), require() or a type import().',
|
|
247
|
+
what: 'a framework',
|
|
248
|
+
matches: matchesPatterns([coreFrameworkPattern]),
|
|
249
|
+
})
|
|
250
|
+
|
|
251
|
+
// JSX in @sssb/kit/core is a framework import nobody writes: with `"jsx": "react-jsx"` every element compiles to an
|
|
252
|
+
// import of `react/jsx-runtime`. Neither half of core's ban can see an import that is not in the source, so the JSX
|
|
253
|
+
// itself is the finding: each outermost element or fragment.
|
|
254
|
+
/** @type {import('eslint').Rule.RuleModule} */
|
|
255
|
+
const jsxInCore = {
|
|
256
|
+
meta: {
|
|
257
|
+
type: 'problem',
|
|
258
|
+
docs: { description: '@sssb/kit/core holds no JSX: it compiles to an import of react/jsx-runtime.' },
|
|
259
|
+
schema: [],
|
|
260
|
+
messages: {
|
|
261
|
+
jsx: `JSX compiles to an import of react/jsx-runtime ("jsx": "react-jsx" in tsconfig.json). ${coreFrameworkPattern.message}`,
|
|
262
|
+
},
|
|
263
|
+
},
|
|
264
|
+
create(context) {
|
|
265
|
+
// Each OUTERMOST element or fragment, so nested JSX is one finding and a disable comment on one element does
|
|
266
|
+
// not hide another.
|
|
267
|
+
const report = (node) => {
|
|
268
|
+
for (let up = node.parent; up; up = up.parent) {
|
|
269
|
+
if (up.type === 'JSXElement' || up.type === 'JSXFragment') return
|
|
270
|
+
}
|
|
271
|
+
context.report({ node, messageId: 'jsx' })
|
|
272
|
+
}
|
|
273
|
+
return { JSXElement: report, JSXFragment: report }
|
|
274
|
+
},
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
// Options naming a directory of SSSB's repository: absolute, so they never depend on where ESLint was started.
|
|
278
|
+
const rootOption = {
|
|
279
|
+
type: 'object',
|
|
280
|
+
properties: { root: { type: 'string' } },
|
|
281
|
+
required: ['root'],
|
|
282
|
+
additionalProperties: false,
|
|
283
|
+
}
|
|
284
|
+
const optionsOf = (context, rule) => {
|
|
285
|
+
const [options] = context.options
|
|
286
|
+
if (!options?.root || !/^([\\/]|[A-Za-z]:[\\/])/.test(options.root)) {
|
|
287
|
+
throw new Error(`sssb/${rule} needs { root }: the absolute path of SSSB's repository root`)
|
|
288
|
+
}
|
|
289
|
+
return options
|
|
290
|
+
}
|
|
291
|
+
// A JSON file read when a rule runs, kept until the file changes, so an editor's lint server sees an edit.
|
|
292
|
+
const jsonCache = new Map()
|
|
293
|
+
const readJson = (file) => {
|
|
294
|
+
const { mtimeMs } = statSync(file)
|
|
295
|
+
const cached = jsonCache.get(file)
|
|
296
|
+
if (cached?.mtimeMs === mtimeMs) return cached.value
|
|
297
|
+
const value = JSON.parse(readFileSync(file, 'utf8'))
|
|
298
|
+
jsonCache.set(file, { mtimeMs, value })
|
|
299
|
+
return value
|
|
300
|
+
}
|
|
301
|
+
const realRootOf = (root) => realpathSync(root).toLowerCase()
|
|
302
|
+
|
|
303
|
+
// NO BARE @sssb/kit IN ANY OTHER SSSB PACKAGE (ADR-0014, rule 4; P4). @sssb/tools (and every SSSB package after it
|
|
304
|
+
// but the framework) has no dependency on @sssb/kit, so a bare `@sssb/kit/…` resolved from the package's own location
|
|
305
|
+
// finds whichever copy pnpm hoisted into `.pnpm/node_modules`: in a workspace with two apps, the other app's
|
|
306
|
+
// instance on the other app's seam. ADR-0014's independent review reproduced exactly that. Those packages reach the
|
|
307
|
+
// framework only through the shared resolver (packages/tools/src/kit.js), which resolves from the APP's directory
|
|
308
|
+
// and checks the real path, and whose specifiers are built at run time, never written as a literal. It sees a
|
|
309
|
+
// declaration, `export … from`, import(), a type import('…'), require(), `import x = require(…)`, any `.resolve('…')`
|
|
310
|
+
// call (require.resolve, createRequire(…).resolve, import.meta.resolve), and vitest's loaders: every way the slip can
|
|
311
|
+
// be written with a literal.
|
|
312
|
+
const isBareKitSpecifier = (specifier) => typeof specifier === 'string' && /^@sssb\/kit(\/|$)/.test(specifier.trim())
|
|
313
|
+
/** @type {import('eslint').Rule.RuleModule} */
|
|
314
|
+
const bareKitImport = {
|
|
315
|
+
meta: {
|
|
316
|
+
type: 'problem',
|
|
317
|
+
docs: { description: 'SSSB packages other than the framework never name @sssb/kit by a bare specifier.' },
|
|
318
|
+
schema: [],
|
|
319
|
+
messages: {
|
|
320
|
+
bare:
|
|
321
|
+
'`{{specifier}}` names the framework by a bare specifier, which resolves from this package, not from ' +
|
|
322
|
+
"the app, and can load another app's @sssb/kit (ADR-0014, rule 4). Reach it through the shared resolver " +
|
|
323
|
+
'(packages/tools/src/kit.js: resolveAppsKit(appDir, subpath)).',
|
|
324
|
+
},
|
|
325
|
+
},
|
|
326
|
+
create(context) {
|
|
327
|
+
const check = (node) => {
|
|
328
|
+
const specifier = literalSpecifier(node)
|
|
329
|
+
if (isBareKitSpecifier(specifier)) context.report({ node, messageId: 'bare', data: { specifier } })
|
|
330
|
+
}
|
|
331
|
+
return {
|
|
332
|
+
...declarationlessVisitors(check),
|
|
333
|
+
...declarationVisitors((_node, source) => check(source)),
|
|
334
|
+
'CallExpression[callee.type="MemberExpression"][callee.property.name="resolve"]': (node) =>
|
|
335
|
+
check(node.arguments[0]),
|
|
336
|
+
'CallExpression[callee.object.name=/^(vi|jest)$/][callee.property.name=/^(mock|doMock|unmock)$/]': (node) =>
|
|
337
|
+
check(node.arguments[0]),
|
|
338
|
+
}
|
|
339
|
+
},
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
// SSSB's PUBLIC SURFACE (ADR-0012). packages/kit/package.json's `exports` map names the subpaths an app may import;
|
|
343
|
+
// the rest of the package is internal, reachable only by relative import inside packages/kit. SSSB's repository
|
|
344
|
+
// ALIASES `@sssb/kit` to source in tsconfig paths, both vitest configs and each app's vite build, and an alias
|
|
345
|
+
// bypasses the exports map entirely — so on its own the map is a comment, not a boundary. This rule is the
|
|
346
|
+
// boundary: it reads the SAME map (`{ root }/packages/kit/package.json`, when it runs) and fails any
|
|
347
|
+
// `@sssb/kit/<subpath>` specifier the map does not publish. An adopter does not need it: TypeScript's resolution
|
|
348
|
+
// already refuses an unpublished subpath of a real installed package (ADR-0014, part 4).
|
|
349
|
+
const KIT_MANIFEST = 'packages/kit/package.json'
|
|
350
|
+
const publicSurfaceOf = (manifest) => {
|
|
351
|
+
const subpaths = new Set()
|
|
352
|
+
const patterns = []
|
|
353
|
+
for (const [key, target] of Object.entries(readJson(manifest).exports ?? {})) {
|
|
354
|
+
// `null` targets are explicit denials, and `.`/`./package.json` are not module subpaths.
|
|
355
|
+
if (target === null || key === '.' || key === './package.json') continue
|
|
356
|
+
const subpath = key.replace(/^\.\//, '')
|
|
357
|
+
if (subpath.includes('*')) {
|
|
358
|
+
const [prefix, suffix] = subpath.split('*')
|
|
359
|
+
patterns.push({ prefix, suffix })
|
|
360
|
+
} else {
|
|
361
|
+
subpaths.add(subpath)
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
return (specifier) => {
|
|
365
|
+
const subpath = specifier.slice('@sssb/kit/'.length)
|
|
366
|
+
if (subpaths.has(subpath)) return true
|
|
367
|
+
return patterns.some(
|
|
368
|
+
({ prefix, suffix }) =>
|
|
369
|
+
subpath.length >= prefix.length + suffix.length &&
|
|
370
|
+
subpath.startsWith(prefix) &&
|
|
371
|
+
subpath.endsWith(suffix),
|
|
372
|
+
)
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
/** @type {import('eslint').Rule.RuleModule} */
|
|
376
|
+
const publicSurface = {
|
|
377
|
+
meta: {
|
|
378
|
+
type: 'problem',
|
|
379
|
+
docs: {
|
|
380
|
+
description: "Only SSSB's published subpaths (packages/kit/package.json `exports`) may be imported.",
|
|
381
|
+
},
|
|
382
|
+
schema: [rootOption],
|
|
383
|
+
messages: {
|
|
384
|
+
private:
|
|
385
|
+
"`{{specifier}}` is not part of SSSB's public surface — it is an internal of packages/kit, " +
|
|
386
|
+
'reachable only by relative import inside the package. Import a published subpath ' +
|
|
387
|
+
'(packages/kit/package.json `exports`) instead, or promote this module by adding it there ' +
|
|
388
|
+
'if it is genuinely part of the contract (ADR-0012).',
|
|
389
|
+
},
|
|
390
|
+
},
|
|
391
|
+
create(context) {
|
|
392
|
+
const isPublic = publicSurfaceOf(join(optionsOf(context, 'public-surface').root, KIT_MANIFEST))
|
|
393
|
+
const check = (node) => {
|
|
394
|
+
const value = node?.value
|
|
395
|
+
if (typeof value !== 'string' || !value.startsWith('@sssb/kit/')) return
|
|
396
|
+
if (isPublic(value)) return
|
|
397
|
+
context.report({ node, messageId: 'private', data: { specifier: value } })
|
|
398
|
+
}
|
|
399
|
+
return {
|
|
400
|
+
ImportDeclaration: (node) => check(node.source),
|
|
401
|
+
ImportExpression: (node) => check(node.source),
|
|
402
|
+
ExportAllDeclaration: (node) => check(node.source),
|
|
403
|
+
ExportNamedDeclaration: (node) => check(node.source),
|
|
404
|
+
'CallExpression[callee.name="require"]': (node) => check(node.arguments[0]),
|
|
405
|
+
// vitest/jest mock a module by specifier, which resolves exactly like an import.
|
|
406
|
+
'CallExpression[callee.object.name=/^(vi|jest)$/][callee.property.name=/^(mock|doMock|unmock|importActual|importMock)$/]':
|
|
407
|
+
(node) => check(node.arguments[0]),
|
|
408
|
+
}
|
|
409
|
+
},
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
// THE FENCE BY PATH. A relative or absolute specifier, or a `file:` URL, names a FILE, so what matters is where it
|
|
413
|
+
// lands, not how it is spelled: `../../../../apps/showcase/src/domain/tickets` from SSSB's server-lib, the same with
|
|
414
|
+
// `//` or `\` separators, or `../../../../packages/seed/src/index`. Each names app content with no alias for a
|
|
415
|
+
// pattern to see. sssb/no-path-to-app-code resolves the path against the importing file and reports it if it lands
|
|
416
|
+
// in an app (`apps/`) or the app's seed package (`packages/seed/`, which `@app/seed` names); any other path out of
|
|
417
|
+
// packages/kit is sssb/no-path-out-of-package's finding. Matching ignores case, as macOS's file system does, and
|
|
418
|
+
// follows symlinks: the path is judged by where it really lands, so neither a symlink into app code nor a checkout
|
|
419
|
+
// opened through a symlinked directory (an editor's workspace, say) moves it out of reach. A specifier that is not a
|
|
420
|
+
// path is the pattern fence's, and so is a path through node_modules, which these rules leave alone: one finding,
|
|
421
|
+
// not two.
|
|
422
|
+
const APP_CODE_DIRS = ['apps', 'packages/seed']
|
|
423
|
+
const throughNodeModules = new RegExp(nodeModulesPathPattern.regex, 'iu')
|
|
424
|
+
// Where `target` really is: symlinks resolved through its deepest existing ancestor, because a specifier names a
|
|
425
|
+
// module without its extension, or one that does not exist yet.
|
|
426
|
+
const realPathOf = (target) => {
|
|
427
|
+
const missing = []
|
|
428
|
+
let existing = target
|
|
429
|
+
while (!existsSync(existing) && dirname(existing) !== existing) {
|
|
430
|
+
missing.unshift(basename(existing))
|
|
431
|
+
existing = dirname(existing)
|
|
432
|
+
}
|
|
433
|
+
return join(realpathSync(existing), ...missing)
|
|
434
|
+
}
|
|
435
|
+
// The file a path specifier names: a `file:` URL's (Node loads one as the absolute path it names), or a relative or
|
|
436
|
+
// absolute path resolved against the importer. Anything else is not a path.
|
|
437
|
+
const pathTarget = (filename, specifier) => {
|
|
438
|
+
if (/^file:/i.test(specifier)) {
|
|
439
|
+
try {
|
|
440
|
+
return fileURLToPath(specifier)
|
|
441
|
+
} catch {
|
|
442
|
+
return undefined // a remote host, an encoded slash or a malformed URL: Node loads no file from it
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
if (!/^(\.{1,2}([\\/]|$)|[\\/])/.test(specifier)) return undefined
|
|
446
|
+
return resolve(dirname(filename), specifier.replaceAll('\\', '/'))
|
|
447
|
+
}
|
|
448
|
+
// Where a path specifier really lands, relative to the repo root and `/`-separated; undefined for a specifier that
|
|
449
|
+
// is not a path, or a path through node_modules (the pattern fence's).
|
|
450
|
+
const landingOfPath = (repoRoot, filename, specifier) => {
|
|
451
|
+
const target = throughNodeModules.test(specifier) ? undefined : pathTarget(filename, specifier)
|
|
452
|
+
if (!target) return undefined
|
|
453
|
+
return relative(repoRoot, realPathOf(target).toLowerCase()).replaceAll('\\', '/')
|
|
454
|
+
}
|
|
455
|
+
const isUnder = (fromRoot, dir) => fromRoot === dir || fromRoot.startsWith(`${dir}/`)
|
|
456
|
+
|
|
457
|
+
/** @type {import('eslint').Rule.RuleModule} */
|
|
458
|
+
const pathToAppCode = {
|
|
459
|
+
meta: {
|
|
460
|
+
type: 'problem',
|
|
461
|
+
docs: { description: 'Framework code does not reach app content by a relative or absolute path.' },
|
|
462
|
+
schema: [rootOption],
|
|
463
|
+
messages: {
|
|
464
|
+
path:
|
|
465
|
+
'`{{specifier}}` is a path into {{dir}}/: app content under another name. Framework code ' +
|
|
466
|
+
'(packages/kit) reaches app content only through the @sssb/app-config/* seam (ADR-0012).',
|
|
467
|
+
},
|
|
468
|
+
},
|
|
469
|
+
create(context) {
|
|
470
|
+
const repoRoot = realRootOf(optionsOf(context, 'no-path-to-app-code').root)
|
|
471
|
+
const check = (node) => {
|
|
472
|
+
const specifier = literalSpecifier(node)
|
|
473
|
+
if (typeof specifier !== 'string') return
|
|
474
|
+
const fromRoot = landingOfPath(repoRoot, context.filename, specifier.trim())
|
|
475
|
+
const dir = fromRoot === undefined ? undefined : APP_CODE_DIRS.find((d) => isUnder(fromRoot, d))
|
|
476
|
+
if (dir) context.report({ node, messageId: 'path', data: { specifier, dir } })
|
|
477
|
+
}
|
|
478
|
+
return {
|
|
479
|
+
...declarationVisitors((_node, source) => check(source)),
|
|
480
|
+
...declarationlessVisitors(check),
|
|
481
|
+
}
|
|
482
|
+
},
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
// THE PACKAGE'S EDGE (ADR-0014 P3). @sssb/kit is installed from a tarball of packages/kit's `files` alone, so a path
|
|
486
|
+
// to anything else names a file an adopter does not have: until P3, 23 of SSSB's tests and one shipped conformance
|
|
487
|
+
// suite reached the repo's tests/support/tmp-dir.ts that way, and the suite could not run from the tarball. A path is
|
|
488
|
+
// judged where it really lands, exactly as sssb/no-path-to-app-code judges one, and a landing in app code is that
|
|
489
|
+
// rule's finding, not this one's. This rule reports, from any file in packages/kit (fixture included):
|
|
490
|
+
// - a path that lands outside packages/kit;
|
|
491
|
+
// - an absolute path or a `file:` URL, wherever it lands: it names this checkout, which an adopter's machine has not;
|
|
492
|
+
// - from a SHIPPED file, a path to a file the tarball leaves out (a test, a story, the fixture, a config), which
|
|
493
|
+
// exists here, so it typechecks and runs here and fails only once installed.
|
|
494
|
+
// "Shipped" reads packages/kit/package.json's `files` when the rule runs: `src`, minus every test and story, plus the
|
|
495
|
+
// files it names back, and package.json and LICENSE, which ship whatever `files` says. A `/// <reference path=…>` or
|
|
496
|
+
// relative `types=…` counts as a path too.
|
|
497
|
+
const KIT_DIR = 'packages/kit'
|
|
498
|
+
const SCRIPT_EXT = /\.[cm]?[jt]sx?$/
|
|
499
|
+
const TEST_OR_STORY = /\.(test|stories)(\.[cm]?[jt]sx?)?$/
|
|
500
|
+
// npm and pnpm ship a package's own package.json (and its LICENSE) whatever `files` says.
|
|
501
|
+
const ALWAYS_SHIPPED = new Set([`${KIT_DIR}/package.json`, `${KIT_DIR}/license`])
|
|
502
|
+
const shippedKitFiles = (manifest) => {
|
|
503
|
+
const reincluded = new Set(
|
|
504
|
+
(readJson(manifest).files ?? [])
|
|
505
|
+
.filter((entry) => !entry.startsWith('!') && entry !== 'src')
|
|
506
|
+
.map((entry) => `${KIT_DIR}/${entry}`.toLowerCase()),
|
|
507
|
+
)
|
|
508
|
+
// A suite named back is shipped by its exact name, or by its name less the extension when a specifier omits it.
|
|
509
|
+
const isReincluded = (fromRoot) =>
|
|
510
|
+
reincluded.has(fromRoot) ||
|
|
511
|
+
(!SCRIPT_EXT.test(fromRoot) && [...reincluded].some((file) => file.replace(SCRIPT_EXT, '') === fromRoot))
|
|
512
|
+
return (fromRoot) =>
|
|
513
|
+
ALWAYS_SHIPPED.has(fromRoot) ||
|
|
514
|
+
(isUnder(fromRoot, `${KIT_DIR}/src`) && (!TEST_OR_STORY.test(fromRoot) || isReincluded(fromRoot)))
|
|
515
|
+
}
|
|
516
|
+
const isAbsoluteSpecifier = (specifier) => /^file:/i.test(specifier) || /^[\\/]/.test(specifier)
|
|
517
|
+
// A triple-slash `path=` or `types=` reference, in any case and with its attributes in any order; a `types=` that
|
|
518
|
+
// names a package is not a path, and pathTarget leaves it alone.
|
|
519
|
+
const REFERENCE_PATH = /^\/\s*<reference\s[^>]*?\b(?:path|types)\s*=\s*(["'])(.+?)\1/i
|
|
520
|
+
/** @type {import('eslint').Rule.RuleModule} */
|
|
521
|
+
const pathOutOfPackage = {
|
|
522
|
+
meta: {
|
|
523
|
+
type: 'problem',
|
|
524
|
+
docs: {
|
|
525
|
+
description: "Framework code reaches only what @sssb/kit's tarball holds, and only by a relative path.",
|
|
526
|
+
},
|
|
527
|
+
schema: [rootOption],
|
|
528
|
+
messages: {
|
|
529
|
+
outside:
|
|
530
|
+
'`{{specifier}}` leaves packages/kit (it lands in {{landing}}): @sssb/kit is installed from a ' +
|
|
531
|
+
'tarball of packages/kit alone, so an adopter has nothing there. Move what it needs into the ' +
|
|
532
|
+
'package (ADR-0014 P3).',
|
|
533
|
+
absolute:
|
|
534
|
+
'`{{specifier}}` is an absolute path or a `file:` URL: it names this checkout ({{landing}}), which ' +
|
|
535
|
+
"an adopter's machine does not have. Use a relative path (ADR-0014 P3).",
|
|
536
|
+
unshipped:
|
|
537
|
+
"`{{specifier}}` reaches {{landing}}, which packages/kit/package.json's `files` leaves out of the " +
|
|
538
|
+
'tarball, from a file that ships: it resolves here and fails once installed. Ship it, or move ' +
|
|
539
|
+
'what this file needs into shipped source (ADR-0014 P3).',
|
|
540
|
+
},
|
|
541
|
+
},
|
|
542
|
+
create(context) {
|
|
543
|
+
const { root } = optionsOf(context, 'no-path-out-of-package')
|
|
544
|
+
const repoRoot = realRootOf(root)
|
|
545
|
+
const isShipped = shippedKitFiles(join(root, KIT_DIR, 'package.json'))
|
|
546
|
+
// The message id and landing for a specifier that crosses the package's edge, or undefined when it does not. A
|
|
547
|
+
// relative path's `?query` or `#hash` is dropped first: Vite and Vitest load the file it names (a `file:` URL's
|
|
548
|
+
// are URL syntax, which fileURLToPath reads).
|
|
549
|
+
const finding = (rawSpecifier) => {
|
|
550
|
+
// Cut at the first `?` or `#` by index: `/[?#].*$/` retried from every `?` in a long run, which a
|
|
551
|
+
// linted file controls, and took time quadratic in it.
|
|
552
|
+
const cut = /^file:/i.test(rawSpecifier) ? -1 : rawSpecifier.search(/[?#]/)
|
|
553
|
+
const specifier = cut < 0 ? rawSpecifier : rawSpecifier.slice(0, cut)
|
|
554
|
+
const landing = landingOfPath(repoRoot, context.filename, specifier)
|
|
555
|
+
if (landing === undefined || APP_CODE_DIRS.some((dir) => isUnder(landing, dir))) return undefined
|
|
556
|
+
if (!isUnder(landing, KIT_DIR)) return { messageId: 'outside', landing: landing || '.' }
|
|
557
|
+
if (isAbsoluteSpecifier(specifier)) return { messageId: 'absolute', landing }
|
|
558
|
+
const importer = relative(repoRoot, realPathOf(context.filename).toLowerCase()).replaceAll('\\', '/')
|
|
559
|
+
if (isShipped(importer) && !isShipped(landing)) return { messageId: 'unshipped', landing }
|
|
560
|
+
return undefined
|
|
561
|
+
}
|
|
562
|
+
const report = (loc, specifier) => {
|
|
563
|
+
const found = finding(specifier.trim())
|
|
564
|
+
if (found)
|
|
565
|
+
context.report({ ...loc, messageId: found.messageId, data: { specifier, landing: found.landing } })
|
|
566
|
+
}
|
|
567
|
+
const check = (node) => {
|
|
568
|
+
const specifier = literalSpecifier(node)
|
|
569
|
+
if (typeof specifier === 'string') report({ node }, specifier)
|
|
570
|
+
}
|
|
571
|
+
return {
|
|
572
|
+
...declarationVisitors((_node, source) => check(source)),
|
|
573
|
+
...declarationlessVisitors(check),
|
|
574
|
+
// `/// <reference path="…" />` makes the compiler load a file just as an import does.
|
|
575
|
+
Program: () => {
|
|
576
|
+
for (const comment of context.sourceCode.getAllComments()) {
|
|
577
|
+
const match = comment.type === 'Line' ? REFERENCE_PATH.exec(comment.value) : null
|
|
578
|
+
if (match?.[2]) report({ loc: comment.loc }, match[2])
|
|
579
|
+
}
|
|
580
|
+
},
|
|
581
|
+
}
|
|
582
|
+
},
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
/** Every sssb/* rule, by its id without the prefix. */
|
|
586
|
+
export const rules = {
|
|
587
|
+
// app-side: the preset enables these (./app-config.js)
|
|
588
|
+
'no-vendor-import': vendorStatic,
|
|
589
|
+
'no-dynamic-vendor-import': vendorDynamic,
|
|
590
|
+
'no-next-font-google': nextFontGoogle,
|
|
591
|
+
'no-real-adapter-import': realAdapterViaRegistry,
|
|
592
|
+
'no-static-real-adapter-import': staticRealAdapterInAdapters,
|
|
593
|
+
'no-kit-real-adapter-import': kitRealAdapterInAdapters,
|
|
594
|
+
'no-dynamic-real-adapter-import': dynamicRealAdapter,
|
|
595
|
+
'no-process-env': processEnv,
|
|
596
|
+
'no-run-mode-env': runModeEnv,
|
|
597
|
+
'no-literal-a11y-copy': a11yLiteral,
|
|
598
|
+
'no-jsx-literals': jsxLiterals,
|
|
599
|
+
'no-raw-db-handle': rawDbHandle,
|
|
600
|
+
'no-direct-mkdtemp': directMkdtemp,
|
|
601
|
+
// SSSB-internal: SSSB's own repository enables these over packages/kit
|
|
602
|
+
'no-app-import': appImport,
|
|
603
|
+
'no-dynamic-app-import': appImportDynamic,
|
|
604
|
+
'no-path-to-app-code': pathToAppCode,
|
|
605
|
+
'no-path-out-of-package': pathOutOfPackage,
|
|
606
|
+
'no-framework-import-in-core': coreFrameworkImport,
|
|
607
|
+
'no-dynamic-framework-import-in-core': coreFrameworkImportDynamic,
|
|
608
|
+
'no-jsx-in-core': jsxInCore,
|
|
609
|
+
'no-bare-kit-import': bareKitImport,
|
|
610
|
+
'public-surface': publicSurface,
|
|
611
|
+
}
|
package/README.md
DELETED