@sssb/kit 0.3.0 → 0.4.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.
@@ -0,0 +1,296 @@
1
+ import { readdirSync, readFileSync, statSync } from 'node:fs'
2
+ import path from 'node:path'
3
+ import ts from 'typescript'
4
+ import { expect } from 'vitest'
5
+ import type { CheckImpl } from './types'
6
+
7
+ /**
8
+ * `real-auth-provider`: a page that renders one of SSSB's real-mode auth forms sits under a layout that mounts their
9
+ * provider. The forms (`@sssb/kit/adapters/real/sign-in-form`, `.../accept-invite-form`) call the auth vendor's client
10
+ * hooks, which throw outside its provider (`RealAuthProviders`, `@sssb/kit/adapters/real/providers`). In simulated mode
11
+ * neither the form nor the provider loads, so nothing but real mode shows the gap: a real sign-in page that fails to
12
+ * render. SSSB's own starter once shipped without the provider, and no gate saw it.
13
+ *
14
+ * How it reads the app: from each of Next's rendering files under `src/app` (`page`, `layout`, `template`, `default`,
15
+ * `not-found`, `error`, `global-error`, `loading`, `forbidden`, `unauthorized`), it follows the app's own imports
16
+ * (a relative path, `@/` for the app's `src/`, `@sssb/app-config/` for its seam) through import and export
17
+ * declarations and `import()` of a literal, and notes whether each file reaches a form or the provider. An import that
18
+ * loads nothing (`import type`, or every name marked `type`) is not followed, nor is a specifier it cannot resolve to
19
+ * a file; a comment or a string naming a module does not count. A rendering file that reaches a form passes when it
20
+ * is wrapped by one that reaches the provider: a layout or template that is itself that file, or one in a directory
21
+ * above it, or in its own directory, where a page is inside both, a template is inside the layout, and a layout is
22
+ * inside neither. `global-error` replaces the root layout, so only it can wrap itself.
23
+ *
24
+ * What it does not read: whether an import runs (an `isSimulated` branch is how it should be written, and a dead one
25
+ * would pass), a path alias other than those two, and anything behind a symbolic link, which it does not follow, as the
26
+ * authorization scan does not. It parses each file once and settles what every file reaches in one pass over the
27
+ * graph, so its cost grows with the app's size, not with its pages times its modules.
28
+ */
29
+
30
+ const FORMS: ReadonlySet<string> = new Set([
31
+ '@sssb/kit/adapters/real/sign-in-form',
32
+ '@sssb/kit/adapters/real/accept-invite-form',
33
+ ])
34
+ const PROVIDER = '@sssb/kit/adapters/real/providers'
35
+ /**
36
+ * The seam's specifiers, as a prefix. Built from the package name because a literal spelling of a seam module path in
37
+ * shipped kit source is what `seam-specifiers.test.ts` refuses as a specifier it cannot list.
38
+ */
39
+ const SEAM_PACKAGE = '@sssb/app-config'
40
+ const SEAM_PREFIX = `${SEAM_PACKAGE}/`
41
+ const EXTENSIONS = ['.tsx', '.ts', '.jsx', '.js', '.mts', '.cts', '.mjs', '.cjs']
42
+ /** What a written `.js`-style extension may stand for, as TypeScript's `bundler` resolution reads it. */
43
+ const SOURCE_FOR: Readonly<Record<string, readonly string[]>> = {
44
+ '.js': ['.ts', '.tsx', '.js', '.jsx'],
45
+ '.jsx': ['.tsx', '.jsx'],
46
+ '.mjs': ['.mts', '.mjs'],
47
+ '.cjs': ['.cts', '.cjs'],
48
+ }
49
+ const RENDERING =
50
+ /^(page|layout|template|default|not-found|error|global-error|loading|forbidden|unauthorized)\.(tsx?|jsx?)$/
51
+ const LAYOUT = /^layout\.(tsx?|jsx?)$/
52
+ const TEMPLATE = /^template\.(tsx?|jsx?)$/
53
+
54
+ /** Paths as the report prints them: relative to the app, with `/` on every platform. */
55
+ const relativeTo = (appDir: string, file: string) => path.relative(appDir, file).split(path.sep).join('/')
56
+
57
+ /** The entries of `dir`, or none when it cannot be read, which is then recorded. */
58
+ function entriesOf(dir: string, unreadable: Map<string, string>) {
59
+ try {
60
+ return readdirSync(dir, { withFileTypes: true })
61
+ } catch (error) {
62
+ unreadable.set(dir, (error as Error).message)
63
+ return []
64
+ }
65
+ }
66
+
67
+ /** Every rendering file under `dir`, recursively, as absolute paths. Symbolic links are not followed. */
68
+ function renderingFiles(dir: string, unreadable: Map<string, string>): string[] {
69
+ const files: string[] = []
70
+ for (const entry of entriesOf(dir, unreadable)) {
71
+ const full = path.join(dir, entry.name)
72
+ if (entry.isDirectory()) files.push(...renderingFiles(full, unreadable))
73
+ else if (entry.isFile() && RENDERING.test(entry.name)) files.push(full)
74
+ }
75
+ return files
76
+ }
77
+
78
+ /** True when an import or export declaration loads nothing at run time: all of it, or every name in it, is a type. */
79
+ function typeOnly(node: ts.ImportDeclaration | ts.ExportDeclaration): boolean {
80
+ if (ts.isImportDeclaration(node)) {
81
+ const clause = node.importClause
82
+ if (clause === undefined) return false // `import 'x'` runs the module
83
+ if (clause.isTypeOnly) return true
84
+ const named = clause.namedBindings
85
+ return (
86
+ clause.name === undefined &&
87
+ named !== undefined &&
88
+ ts.isNamedImports(named) &&
89
+ named.elements.length > 0 &&
90
+ named.elements.every((element) => element.isTypeOnly)
91
+ )
92
+ }
93
+ if (node.isTypeOnly) return true
94
+ const clause = node.exportClause
95
+ return (
96
+ clause !== undefined &&
97
+ ts.isNamedExports(clause) &&
98
+ clause.elements.length > 0 &&
99
+ clause.elements.every((element) => element.isTypeOnly)
100
+ )
101
+ }
102
+
103
+ /** The specifiers `file` loads at run time: value import and export declarations, and `import()` of a literal. */
104
+ function loadedSpecifiers(file: string): string[] {
105
+ const source = ts.createSourceFile(file, readFileSync(file, 'utf8'), ts.ScriptTarget.Latest, true)
106
+ const found: string[] = []
107
+ const visit = (node: ts.Node): void => {
108
+ if (ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) {
109
+ const specifier = node.moduleSpecifier
110
+ if (specifier && ts.isStringLiteral(specifier) && !typeOnly(node)) found.push(specifier.text)
111
+ } else if (
112
+ ts.isCallExpression(node) &&
113
+ node.expression.kind === ts.SyntaxKind.ImportKeyword &&
114
+ node.arguments[0] &&
115
+ ts.isStringLiteralLike(node.arguments[0])
116
+ ) {
117
+ found.push(node.arguments[0].text)
118
+ }
119
+ ts.forEachChild(node, visit)
120
+ }
121
+ visit(source)
122
+ return found
123
+ }
124
+
125
+ const isFile = (file: string) => {
126
+ try {
127
+ return statSync(file).isFile()
128
+ } catch {
129
+ return false
130
+ }
131
+ }
132
+
133
+ const isDirectory = (dir: string) => {
134
+ try {
135
+ return statSync(dir).isDirectory()
136
+ } catch {
137
+ return false
138
+ }
139
+ }
140
+
141
+ /** The app file a specifier names, through a relative path, `@/` or `@sssb/app-config/`; undefined for anything else. */
142
+ function resolverFor(srcDir: string): (specifier: string, from: string) => string | undefined {
143
+ const cache = new Map<string, string | undefined>()
144
+ return (specifier, from) => {
145
+ let base: string
146
+ if (specifier.startsWith('@/')) base = path.join(srcDir, specifier.slice(2))
147
+ else if (specifier.startsWith(SEAM_PREFIX)) {
148
+ base = path.join(srcDir, 'app-config', specifier.slice(SEAM_PREFIX.length))
149
+ } else if (specifier === '.' || specifier === '..' || /^\.\.?\//.test(specifier)) {
150
+ base = path.resolve(path.dirname(from), specifier)
151
+ } else return undefined
152
+ if (cache.has(base)) return cache.get(base)
153
+ const written = path.extname(base)
154
+ const stem = base.slice(0, base.length - written.length)
155
+ const candidates = [
156
+ base,
157
+ ...(SOURCE_FOR[written] ?? []).map((ext) => stem + ext),
158
+ ...EXTENSIONS.map((ext) => base + ext),
159
+ ...EXTENSIONS.map((ext) => path.join(base, `index${ext}`)),
160
+ ]
161
+ const found = candidates.find(isFile)
162
+ cache.set(base, found)
163
+ return found
164
+ }
165
+ }
166
+
167
+ interface Reach {
168
+ form: boolean
169
+ provider: boolean
170
+ }
171
+
172
+ /**
173
+ * What every file reachable from `roots` reaches, settled in one pass: each file is parsed once to learn what it
174
+ * loads directly and which app files it imports, and then each flag is carried backwards along the imports from the
175
+ * files that set it. Cycles need nothing special: a file is visited at most once per flag.
176
+ */
177
+ function reachOf(roots: readonly string[], srcDir: string, unreadable: Map<string, string>): Map<string, Reach> {
178
+ const resolve = resolverFor(srcDir)
179
+ const direct = new Map<string, Reach>()
180
+ const importers = new Map<string, string[]>()
181
+ const queue = [...roots]
182
+ const seen = new Set(roots)
183
+ while (queue.length > 0) {
184
+ const file = queue.shift() as string
185
+ const reach: Reach = { form: false, provider: false }
186
+ let specifiers: string[] = []
187
+ try {
188
+ specifiers = loadedSpecifiers(file)
189
+ } catch (error) {
190
+ unreadable.set(file, (error as Error).message)
191
+ }
192
+ for (const specifier of specifiers) {
193
+ if (FORMS.has(specifier)) reach.form = true
194
+ if (specifier === PROVIDER) reach.provider = true
195
+ const local = resolve(specifier, file)
196
+ if (local === undefined) continue
197
+ const list = importers.get(local) ?? []
198
+ list.push(file)
199
+ importers.set(local, list)
200
+ if (!seen.has(local)) {
201
+ seen.add(local)
202
+ queue.push(local)
203
+ }
204
+ }
205
+ direct.set(file, reach)
206
+ }
207
+ const result = new Map<string, Reach>([...seen].map((file) => [file, { form: false, provider: false }]))
208
+ for (const flag of ['form', 'provider'] as const) {
209
+ const pending = [...direct].filter(([, reach]) => reach[flag]).map(([file]) => file)
210
+ for (const file of pending) (result.get(file) as Reach)[flag] = true
211
+ while (pending.length > 0) {
212
+ for (const importer of importers.get(pending.pop() as string) ?? []) {
213
+ const reach = result.get(importer) as Reach
214
+ if (!reach[flag]) {
215
+ reach[flag] = true
216
+ pending.push(importer)
217
+ }
218
+ }
219
+ }
220
+ }
221
+ return result
222
+ }
223
+
224
+ /**
225
+ * The layouts and templates that wrap `file`, itself included when it is one: in its own directory, a page (or any
226
+ * other rendering file) is inside both, a template is inside the layout, and a layout is inside neither; every layout
227
+ * and template in each directory above wraps it, up to `appRoot`. A `global-error` replaces the root layout, so it
228
+ * wraps itself and nothing else does.
229
+ */
230
+ function wrappersOf(file: string, appRoot: string, unreadable: Map<string, string>): string[] {
231
+ const name = path.basename(file)
232
+ if (/^global-error\./.test(name)) return [file]
233
+ const wrappers = LAYOUT.test(name) || TEMPLATE.test(name) ? [file] : []
234
+ const own = path.dirname(file)
235
+ for (let current = own; ; current = path.dirname(current)) {
236
+ for (const entry of entriesOf(current, unreadable)) {
237
+ if (!entry.isFile()) continue
238
+ const isLayout = LAYOUT.test(entry.name)
239
+ const isTemplate = TEMPLATE.test(entry.name)
240
+ if (!isLayout && !isTemplate) continue
241
+ if (current === own) {
242
+ if (LAYOUT.test(name)) continue // a layout is inside neither of its own directory's wrappers
243
+ if (TEMPLATE.test(name) && isTemplate) continue // a template is inside its layout, not itself again
244
+ }
245
+ wrappers.push(path.join(current, entry.name))
246
+ }
247
+ if (current === appRoot || path.dirname(current) === current) break
248
+ }
249
+ return wrappers
250
+ }
251
+
252
+ /** What the check finds: how many rendering files it walked, those that reach a form, those no provider wraps. */
253
+ export function realAuthProviderGaps(appDir: string): {
254
+ walked: number
255
+ withForms: string[]
256
+ gaps: string[]
257
+ unreadable: string[]
258
+ } {
259
+ const srcDir = path.join(appDir, 'src')
260
+ const appRoot = path.join(srcDir, 'app')
261
+ const unreadableFiles = new Map<string, string>()
262
+ if (!isDirectory(appRoot)) return { walked: 0, withForms: [], gaps: [], unreadable: [] }
263
+ const files = renderingFiles(appRoot, unreadableFiles)
264
+ const reach = reachOf(files, srcDir, unreadableFiles)
265
+ const reaches = (file: string, flag: keyof Reach) => reach.get(file)?.[flag] ?? false
266
+ const withForms = files.filter((file) => reaches(file, 'form'))
267
+ const gaps = withForms.filter(
268
+ (file) => !wrappersOf(file, appRoot, unreadableFiles).some((wrapper) => reaches(wrapper, 'provider')),
269
+ )
270
+ const rel = (file: string) => relativeTo(appDir, file)
271
+ return {
272
+ walked: files.length,
273
+ withForms: withForms.map(rel),
274
+ gaps: gaps.map(rel),
275
+ unreadable: [...unreadableFiles].map(([file, why]) => `${rel(file)}: ${why}`),
276
+ }
277
+ }
278
+
279
+ export const realAuthProvider: CheckImpl = {
280
+ tests: {
281
+ "the app's src/app is really walked": ({ appDir }) => {
282
+ const { walked, unreadable } = realAuthProviderGaps(appDir)
283
+ expect(walked, `no page or layout found under ${path.join(appDir, 'src', 'app')}`).toBeGreaterThan(0)
284
+ expect(unreadable, 'these files or directories could not be read').toEqual([])
285
+ },
286
+ 'every page that reaches a real auth form sits under a layout that reaches RealAuthProviders': ({ appDir }) => {
287
+ const { gaps } = realAuthProviderGaps(appDir)
288
+ expect(
289
+ gaps,
290
+ `these reach ${[...FORMS].join(' or ')}, but no layout above them reaches ${PROVIDER}, so the form ` +
291
+ 'throws in real mode. Mount RealAuthProviders in a layout above them, loaded with import() when ' +
292
+ '!isSimulated',
293
+ ).toEqual([])
294
+ },
295
+ },
296
+ }
@@ -3,13 +3,14 @@ import { type Migration, Migrator } from 'kysely/migration'
3
3
  import { expect } from 'vitest'
4
4
  import { openPglite, PGliteDialect } from '../../adapters/fake/pglite-dialect'
5
5
  import type { FoundRole } from '../../db/app-roles'
6
+ import { familySuite } from '../../db/family-suite'
6
7
  import type { DB } from '../../db/schema'
7
8
  import type { CheckImpl } from './types'
8
9
 
9
- // Everything that composes the framework's migrations with the app's reaches the seam, so it is imported when a
10
- // test runs, not when the suite is collected.
11
- const migrate = () => import('../../db/migrate')
12
- const registry = () => import('../../db/migrations/index')
10
+ // Everything that composes the framework's migrations with the app's reaches the seam, so the database family hands
11
+ // it over as loaders (../../db/family-suite.ts), run when a test runs, not when the suite is collected.
12
+ const migrate = () => familySuite.migrator()
13
+ const registry = () => familySuite.migrations()
13
14
 
14
15
  const pglite = () => new Kysely<DB>({ dialect: new PGliteDialect(openPglite()) })
15
16
 
@@ -197,7 +198,7 @@ export const rlsPglite: CheckImpl = {
197
198
  tests: {
198
199
  'the full RLS proof suite passes': async () => {
199
200
  const { migrateToLatest } = await migrate()
200
- const { runRlsProofs } = await import('../../db/rls-proof-runner')
201
+ const { runRlsProofs } = await familySuite.proofs()
201
202
  const db = pglite()
202
203
  try {
203
204
  await migrateToLatest(db)
@@ -1,4 +1,5 @@
1
1
  import path from 'node:path'
2
+ import { realAuthProvider } from './auth-provider'
2
3
  import { authzMutations } from './authz'
3
4
  import { appRolesCheck, migrationOrder, rlsPglite } from './db'
4
5
  import { demoPresets } from './demo-presets'
@@ -28,6 +29,7 @@ import { registerTestTmpDirCleanup } from '../tmp-dir'
28
29
  /** The unit checks' implementations, by id. The contract checks are `@sssb/kit/testing/contract`'s. */
29
30
  const IMPLEMENTATIONS: Readonly<Record<string, CheckImpl>> = {
30
31
  'authz-mutations': authzMutations,
32
+ 'real-auth-provider': realAuthProvider,
31
33
  'i18n-partition': i18nPartition,
32
34
  'i18n-parity': i18nParity,
33
35
  'rls-pglite': rlsPglite,
@@ -1,6 +1,7 @@
1
1
  import { sql } from 'kysely'
2
2
  import { afterAll, beforeAll, expect } from 'vitest'
3
3
  import { startContractServer, type ContractServer } from '../adapters/real/contract-postgres'
4
+ import { familySuite } from '../db/family-suite'
4
5
  import { checkOptOut, registerChecks, runsAny } from './conformance/register'
5
6
  import type { CheckImpl } from './conformance/types'
6
7
  import { registerTestTmpDirCleanup } from './tmp-dir'
@@ -77,10 +78,11 @@ interface ContractContext {
77
78
  database(): string
78
79
  }
79
80
 
80
- // Everything that composes the framework's migrations with the app's reaches the seam, so it is imported when a test
81
- // runs, not when the file is collected: `contractDatabaseName` stays importable with no seam at all.
82
- const migrate = () => import('../db/migrate')
83
- const proofs = () => import('../db/rls-proof-runner')
81
+ // Everything that composes the framework's migrations with the app's reaches the seam, so the database family hands
82
+ // it over as loaders (../db/family-suite.ts), run when a test runs, not when the file is collected: `contractDatabaseName`
83
+ // stays importable with no seam at all.
84
+ const migrate = () => familySuite.migrator()
85
+ const proofs = () => familySuite.proofs()
84
86
  const dataApi = () => import('../adapters/real/contract-data-api')
85
87
 
86
88
  const TIMEOUT_MS = 120_000