@exodus/stasis 1.0.0-beta.13 → 1.0.0-beta.15

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 (46) hide show
  1. package/README.md +5 -1
  2. package/bin/stasis.js +191 -149
  3. package/package.json +31 -7
  4. package/src/audit.js +224 -90
  5. package/src/babel.js +44 -37
  6. package/src/bundle-reader.js +24 -4
  7. package/src/cmd/build.js +218 -8
  8. package/src/cmd/bundle-options.js +31 -25
  9. package/src/cmd/bundle.js +1147 -311
  10. package/src/cmd/github-bundle.js +17 -9
  11. package/src/cmd/output.js +10 -3
  12. package/src/cmd/tokens.js +73 -0
  13. package/src/define.js +5 -0
  14. package/src/diff.js +2 -2
  15. package/src/flow.js +42 -0
  16. package/src/installed-commits.js +4 -2
  17. package/src/loaders/bash.js +2 -27
  18. package/src/loaders/cargo.js +6 -6
  19. package/src/loaders/foundry.js +4 -6
  20. package/src/loaders/paths.js +4 -15
  21. package/src/loaders/php.js +3 -5
  22. package/src/loaders/rust.js +19 -39
  23. package/src/loaders/solidity-ownership.js +4 -15
  24. package/src/loaders/solidity.js +4 -67
  25. package/src/metro-assets.js +65 -0
  26. package/src/metro-resolver.js +76 -123
  27. package/src/parse.js +7 -3
  28. package/src/resolve-fields.js +133 -366
  29. package/src/resolve-node.js +9 -7
  30. package/src/resolve-typescript.js +102 -30
  31. package/src/scan.js +154 -54
  32. package/src/sixel.js +333 -0
  33. package/src/table.js +116 -0
  34. package/src/validate-notes.d.ts +18 -0
  35. package/src/validate-notes.js +66 -0
  36. package/src/validate.d.ts +132 -0
  37. package/src/validate.js +1349 -0
  38. package/src/vfs-bundle/entries.js +5 -2
  39. package/src/vfs-bundle/github.js +68 -19
  40. package/src/vfs-bundle/glob.js +420 -0
  41. package/src/vfs-bundle/lazy.js +128 -0
  42. package/src/vfs-bundle/prisma.js +102 -29
  43. package/src/vfs-bundle/tree.js +238 -75
  44. package/src/vfs-bundle/yarnclean.js +100 -0
  45. package/src/vfs-bundle.js +16 -7
  46. package/src/why.js +9 -7
@@ -0,0 +1,128 @@
1
+ import { AsyncLocalStorage } from 'node:async_hooks'
2
+ import { posix } from 'node:path'
3
+
4
+ // A lazy tree (@preventive/deptree's `lazy`): laid out from the lockfile alone, each package's
5
+ // directory left empty until it is unpacked. The host reads synchronously, so a build reading it
6
+ // cannot wait for a tarball: it runs in rounds. A round that reads under a package not yet unpacked
7
+ // is void, whatever it built, and those packages are unpacked for the next; the first round that
8
+ // reads none read nothing but what the full tree holds there, and is the build. What a round's scan
9
+ // reads of a file is kept for the rounds after it where reading it read no such package (Scan's
10
+ // `memo`), so each file is scanned once, but those that read what was not unpacked yet.
11
+
12
+ // The tree's Vfs as tree.js's vfsHost reads it (lstat, readlink, readFile and readdir). A read under
13
+ // the directory of a package of `roots` not in `unpacked`, or a listing of that directory itself,
14
+ // adds it to `reads.asked`, and to `reads.read` but while `reads.probing` (a check of what files the
15
+ // package holds, which reads none of its code), counts in `reads.touches`, and reads what the layout
16
+ // holds there. The directory itself, and those above a package's on the way to it, are as the full
17
+ // tree holds them, so reading them asks for nothing.
18
+ export function lazyView(vfs, { roots, unpacked, reads }) {
19
+ const above = new Set()
20
+ for (const root of roots) {
21
+ for (let dir = posix.dirname(root); dir !== '/' && !above.has(dir); dir = posix.dirname(dir)) above.add(dir)
22
+ }
23
+ const ownerOf = (path) => {
24
+ for (let dir = path; dir !== '/'; dir = posix.dirname(dir)) if (roots.has(dir)) return dir
25
+ return null
26
+ }
27
+ const touch = (path, listing) => {
28
+ const owner = ownerOf(path)
29
+ if (owner === null || unpacked.has(owner)) return
30
+ if (!listing && (path === owner || above.has(path))) return
31
+ reads.asked.add(owner)
32
+ if (reads.probing === 0) reads.read.add(owner)
33
+ reads.touches++
34
+ }
35
+ return {
36
+ lstat(path) {
37
+ touch(path, false)
38
+ return vfs.lstat(path)
39
+ },
40
+ readlink(path) {
41
+ touch(path, false)
42
+ return vfs.readlink(path)
43
+ },
44
+ readFile(path) {
45
+ touch(path, false)
46
+ return vfs.readFile(path)
47
+ },
48
+ readdir(path) {
49
+ touch(path, true)
50
+ return vfs.readdir(path)
51
+ },
52
+ }
53
+ }
54
+
55
+ // A get-or-read cache, `(key, read) => read()`'s value, as for a tree that holds still: but kept only
56
+ // where reading it read nothing a lazy tree does not hold yet (counted by `touches`, a lazy tree's
57
+ // host's), which is read again; and kept nowhere without `cache`. With `retouch`, for a cache that
58
+ // lives no longer than one round of a lazy tree, in which the tree holds still, what such a reading
59
+ // gave is kept too, and each time it is taken it touches again (`retouch()`), as reading it again
60
+ // would: what reads it knows it read what the tree does not hold yet, which a round's scan keeps none
61
+ // of (Scan's `memo`), and it is not read again only to fail again. With `across`, a Map kept across
62
+ // a lazy tree's rounds, what was read with none is kept there, for each round after, as a scan
63
+ // keeps a file it read so.
64
+ export function untouchedMemo(touches = () => 0, { cache = true, retouch, across } = {}) {
65
+ const kept = new Map()
66
+ return (key, read) => {
67
+ if (across?.has(key)) return across.get(key)
68
+ const hit = kept.get(key)
69
+ if (hit !== undefined) {
70
+ if (hit.touched) retouch()
71
+ return hit.value
72
+ }
73
+ const before = touches()
74
+ const value = read()
75
+ const touched = touches() !== before
76
+ if (!cache) return value
77
+ if (!touched && across !== undefined) across.set(key, value)
78
+ else if (!touched || retouch !== undefined) kept.set(key, { value, touched })
79
+ return value
80
+ }
81
+ }
82
+
83
+ // What console.warn gives within a round, held for the round: one that is void says nothing.
84
+ const rounds = new AsyncLocalStorage()
85
+ let holders = 0
86
+ let passed
87
+ function warnHeld(...args) {
88
+ const held = rounds.getStore()
89
+ if (held === undefined) passed.apply(console, args)
90
+ else held.push(args)
91
+ }
92
+ async function holding(held, fn) {
93
+ if (holders++ === 0) {
94
+ passed = console.warn
95
+ console.warn = warnHeld
96
+ }
97
+ try {
98
+ return await rounds.run(held, fn)
99
+ } finally {
100
+ if (--holders === 0 && console.warn === warnHeld) console.warn = passed
101
+ }
102
+ }
103
+
104
+ // `attempt(reads)`'s result, of the first round whose reads ask for no package (`reads.asked`), its
105
+ // warnings given then; after each round that does, `unpack(reads.asked, reads.read)`, `reads.read`
106
+ // those of them it read other than by a probe (lazyView). Each round asks for one package at least
107
+ // that no round before did, so there are no more rounds than packages.
108
+ export async function inRounds(attempt, unpack) {
109
+ for (;;) {
110
+ const reads = { asked: new Set(), read: new Set(), probing: 0, touches: 0 }
111
+ const held = []
112
+ let result
113
+ let failure
114
+ try {
115
+ // eslint-disable-next-line no-await-in-loop -- each round reads what the one before unpacked
116
+ result = await holding(held, () => attempt(reads))
117
+ } catch (error) {
118
+ failure = { error }
119
+ }
120
+ if (reads.asked.size === 0) {
121
+ for (const args of held) console.warn(...args)
122
+ if (failure !== undefined) throw failure.error
123
+ return result
124
+ }
125
+ // eslint-disable-next-line no-await-in-loop -- what the next round reads
126
+ await unpack(reads.asked, reads.read)
127
+ }
128
+ }
@@ -4,7 +4,7 @@ import { posix } from 'node:path'
4
4
  import { compileFunction } from 'node:vm'
5
5
 
6
6
  import { readJson } from '@exodus/stasis-core/bundle-util'
7
- import { hasNodeModulesSegment } from '@exodus/stasis-core/util'
7
+ import { hasNodeModulesSegment, isPlainObject } from '@exodus/stasis-core/util'
8
8
  import { createVfs } from '@preventive/vfs'
9
9
  import { isDir, isFile, loadTsconfigCompilerOptions } from '../resolve-typescript.js'
10
10
  import { getParser, literalSpec, syntaxErrors } from '../scan.js'
@@ -169,6 +169,9 @@ function installedPrisma(host, dir) {
169
169
 
170
170
  // @prisma/config's search order; only 7.10.0 reads the first two (prisma7.config.*).
171
171
  const CONFIG_BASES = ['prisma7.config', '.config/prisma7', ...['prisma.config', '.config/prisma', '.config/prisma.config'].flatMap((base) => [base, `${base}/index`])]
172
+ const configFiles = (bases) => bases.flatMap((base) => ['.js', '.ts', '.mjs', '.cjs', '.mts', '.cts'].map((ext) => `${base}${ext}`))
173
+ // Where `prisma generate` looks for a schema without a config's.
174
+ const DEFAULT_SCHEMAS = ['schema.prisma', 'prisma/schema.prisma']
172
175
 
173
176
  // The modules a config's top-level imports and requires may bind, as `name.export` (`name.*`: the module).
174
177
  const MODULES = { path: 'path', 'node:path': 'path', 'prisma/config': 'config', '@prisma/config': 'config' }
@@ -239,9 +242,9 @@ function schemaFilesAt(host, path) {
239
242
  // else ./schema.prisma or ./prisma/schema.prisma; null if none.
240
243
  function projectSchema(host, dir, version) {
241
244
  const first = (names) => names.map((name) => posix.join(dir, name)).find((file) => isFile(file, host))
242
- const config = first(CONFIG_BASES.slice(newerThan(version, '7.9.1') ? 0 : 2).flatMap((base) => ['.js', '.ts', '.mjs', '.cjs', '.mts', '.cts'].map((ext) => `${base}${ext}`)))
245
+ const config = first(configFiles(CONFIG_BASES.slice(newerThan(version, '7.9.1') ? 0 : 2)))
243
246
  const named = config && configSchema(config, host.readFile(config).toString('utf8'))
244
- const path = named === undefined ? first(['schema.prisma', 'prisma/schema.prisma']) : posix.resolve(posix.dirname(config), named)
247
+ const path = named === undefined ? first(DEFAULT_SCHEMAS) : posix.resolve(posix.dirname(config), named)
245
248
  if (path === undefined) return null
246
249
  if (!isFile(path, host) && !isDir(path, host)) throw new Error(`${config}: its schema ${named} is no file or directory`)
247
250
  return path
@@ -379,45 +382,115 @@ function generateClientFor({ schemaPath, datamodel, generator, dmmf, datasources
379
382
 
380
383
  const readingSchema = (path, what) => Promise.try(what).catch((cause) => { throw new Error(`prisma: ${path}: ${cause.message}`, { cause }) })
381
384
 
382
- // Each `{ dir, files }` output. Projects without a schema or a `prisma-client` generator are skipped
383
- // quietly; ones stasis can't generate for with a warning, the scan then reporting what is missing.
385
+ // Where a generator's `output` points, relative to the schema file declaring it.
386
+ const outputOf = (generator, path) => posix.resolve(posix.dirname(generator.sourceFilePath ?? path), generator.output.value)
387
+
388
+ // The output of a generator stasis doesn't run, where the tree already has it: the bundle takes what it
389
+ // reaches there as committed, however stale -> its path, or undefined. Not one in node_modules, laid out
390
+ // from the lockfile, nor one no `output` or an env() names, which stasis can't know.
391
+ function committedOutput(host, generator, path) {
392
+ if (generator.output === null || generator.output.fromEnvVar !== null) return undefined
393
+ const output = outputOf(generator, path)
394
+ return !hasNodeModulesSegment(output) && (isFile(output, host) || isDir(output, host)) ? output : undefined
395
+ }
396
+
397
+ const ours = (generator) => generator.provider.value === PROVIDER && generator.provider.fromEnvVar === null
398
+ const SKIPPED = `stasis generates the ${JSON.stringify(PROVIDER)} provider's alone`
399
+ // That `writer` (a schema's generator) isn't generated, `why`; and where the tree has its output, `committed`, that
400
+ // the bundle takes it as committed.
401
+ const notGenerating = (writer, why, committed) => `not generating ${writer}: ${why}${committed === undefined ? '' : `, and takes its output, ${committed}, as committed, not as \`prisma generate\` would write it`}`
402
+
403
+ // A generator whose output no bundle needs, not warned of: @pothos/plugin-prisma's with no `output`, which writes
404
+ // types alone into its own package (generated.d.ts), there in node_modules as a placeholder. With
405
+ // `generateDatamodel = "true"` it writes getDatamodel() there too, code a bundle may run.
406
+ const POTHOS = 'prisma-pothos-types'
407
+ const needsNoOutput = (generator) => generator.provider.value === POTHOS && generator.provider.fromEnvVar === null &&
408
+ generator.output === null && generator.config.generateDatamodel !== 'true'
409
+
410
+ // Those of `projects` (directories relative to `root`) that may have a schema: a Prisma config, schema.prisma or
411
+ // prisma/schema.prisma there. Looked for before any `prisma` is read, which a lazy tree fetches once read.
412
+ const hasSchema = (host) => holding(host, ...configFiles(CONFIG_BASES), ...DEFAULT_SCHEMAS)
413
+ export const schemaProjects = (host, root, projects) => new Set([...projects].filter((project) => hasSchema(host)(posix.join(root, project))))
414
+
415
+ // The outputs, `{ dir, files }` each, of the `prisma-client` generators of the projects' schemas. Asked for
416
+ // (`strict`), what stasis can't generate is warned of, and a schema it can't take refused, as `prisma generate`
417
+ // refuses it; detected, both are silent, the scan then reporting what is missing. Two generators writing one
418
+ // output are refused either way.
384
419
  /* eslint-disable no-await-in-loop -- one project at a time, in the order its warnings read */
385
- export async function generatePrismaClients({ host, root, projects }) {
420
+ export async function generatePrismaClients({ host, root, projects, strict = true }) {
386
421
  const outputs = []
387
- const skip = (what, why) => { console.warn(`[stasis] prisma: not generating ${what}: ${why}`) }
422
+ const say = strict ? (message) => { console.warn(`[stasis] prisma: ${message}`) } : undefined
423
+ const skip = (what, why) => say?.(`not generating ${what}: ${why}`)
388
424
  for (const project of [...projects].toSorted()) {
389
425
  const dir = posix.join(root, project)
390
426
  const prisma = installedPrisma(host, dir)
391
427
  const supported = PRISMA_VERSIONS.includes(prisma?.version)
392
428
  const path = await Promise.try(projectSchema, host, dir, supported ? prisma.version : GENERATOR_VERSION).catch((error) => skip(`for ${dir}`, error.message))
429
+ if (!path) continue
393
430
  // Checked before parsing: another Prisma's schema needn't satisfy 7.10.0.
394
- if (path && !supported) skip(`for ${path}`, `stasis generates as Prisma ${PRISMA_VERSIONS.at(-1)} to ${PRISMA_VERSIONS[0]} do, and ${prisma === null ? 'none is installed' : `${prisma.file} is ${prisma.version}`}`)
395
- if (!path || !supported) continue
396
- const files = await readingSchema(path, () => schemaFilesAt(host, path))
397
- const { internals } = loadGenerator()
398
- const config = await readingSchema(path, () => internals.getConfig({ datamodel: files }))
399
- const generators = config.generators.filter((generator) => generator.provider.value === PROVIDER && generator.provider.fromEnvVar === null)
400
- for (const other of config.generators.filter((generator) => !generators.includes(generator))) skip(`${path}'s generator ${other.name}`, `stasis generates the ${JSON.stringify(PROVIDER)} provider's alone`)
401
- if (generators.length === 0) continue
402
- for (const warning of config.warnings) console.warn(`[stasis] prisma: ${warning}`)
403
- if (config.datasources.length === 0) throw new Error(`prisma: ${path} defines no datasource`)
404
- const dmmf = await readingSchema(path, () => internals.getDMMF({ datamodel: files }))
405
- const datamodel = internals.mergeSchemas({ schemas: files })
406
- for (const generator of generators) {
407
- if (generator.output === null) throw new Error(`prisma: ${path}: generator ${generator.name} names no output`)
408
- if (generator.output.fromEnvVar !== null) {
409
- skip(`${path}'s generator ${generator.name}`, `its output is env("${generator.output.fromEnvVar}"), which stasis doesn't read`)
410
- continue
411
- }
412
- const outputDir = posix.resolve(posix.dirname(generator.sourceFilePath ?? path), generator.output.value)
413
- if (hasNodeModulesSegment(outputDir)) throw new Error(`prisma: ${path}: generator ${generator.name}'s output ${outputDir} is in node_modules, which is laid out from the lockfile alone`)
414
- if (outputs.some((output) => output.dir === outputDir)) throw new Error(`prisma: ${outputDir} is the output of more than one generator`)
415
- outputs.push({ dir: outputDir, files: generateClientFor({ schemaPath: path, datamodel, generator, dmmf, datasources: config.datasources, outputDir, prisma, host }) })
431
+ if (!supported) {
432
+ skip(`for ${path}`, `stasis generates as Prisma ${PRISMA_VERSIONS.at(-1)} to ${PRISMA_VERSIONS[0]} do, and ${prisma === null ? 'none is installed' : `${prisma.file} is ${prisma.version}`}`)
433
+ continue
434
+ }
435
+ try {
436
+ outputs.push(...await generateSchema({ host, path, prisma, say, skip }))
437
+ } catch (error) {
438
+ if (strict) throw error
439
+ }
440
+ }
441
+ const dirs = outputs.map(({ dir }) => dir)
442
+ const twice = dirs.find((dir, i) => dirs.indexOf(dir) !== i)
443
+ if (twice !== undefined) throw new Error(`prisma: ${twice} is the output of more than one generator`)
444
+ return outputs
445
+ }
446
+ /* eslint-enable no-await-in-loop */
447
+
448
+ // The outputs of the `prisma-client` generators of the schema at `path`, as `prisma` writes them, what isn't
449
+ // generated said through `say` and `skip` (generatePrismaClients').
450
+ async function generateSchema({ host, path, prisma, say, skip }) {
451
+ const files = await readingSchema(path, () => schemaFilesAt(host, path))
452
+ const { internals } = loadGenerator()
453
+ const config = await readingSchema(path, () => internals.getConfig({ datamodel: files }))
454
+ const generators = config.generators.filter(ours)
455
+ for (const other of config.generators.filter((generator) => !ours(generator) && !needsNoOutput(generator))) say?.(notGenerating(`${path}'s generator ${other.name}`, SKIPPED, committedOutput(host, other, path)))
456
+ if (generators.length === 0) return []
457
+ for (const warning of config.warnings) say?.(warning)
458
+ if (config.datasources.length === 0) throw new Error(`prisma: ${path} defines no datasource`)
459
+ const dmmf = await readingSchema(path, () => internals.getDMMF({ datamodel: files }))
460
+ const datamodel = internals.mergeSchemas({ schemas: files })
461
+ const outputs = []
462
+ for (const generator of generators) {
463
+ if (generator.output === null) throw new Error(`prisma: ${path}: generator ${generator.name} names no output`)
464
+ if (generator.output.fromEnvVar !== null) {
465
+ skip(`${path}'s generator ${generator.name}`, `its output is env("${generator.output.fromEnvVar}"), which stasis doesn't read`)
466
+ continue
416
467
  }
468
+ const outputDir = outputOf(generator, path)
469
+ if (hasNodeModulesSegment(outputDir)) throw new Error(`prisma: ${path}: generator ${generator.name}'s output ${outputDir} is in node_modules, which is laid out from the lockfile alone`)
470
+ outputs.push({ dir: outputDir, files: generateClientFor({ schemaPath: path, datamodel, generator, dmmf, datasources: config.datasources, outputDir, prisma, host }) })
417
471
  }
418
472
  return outputs
419
473
  }
420
474
 
475
+ // The projects (`projects`, directories relative to `root`) a build of `paths` (absolute) may import the generated
476
+ // outputs of: those the paths are in, and the workspace packages they depend on by name, theirs in turn.
477
+ export function reachedProjects(host, root, projects, paths) {
478
+ const manifests = new Map([...projects].map((dir) => {
479
+ const json = readJson(posix.join(root, dir, 'package.json'), host)
480
+ return [dir, isPlainObject(json) ? json : {}]
481
+ }))
482
+ const byName = new Map([...manifests].map(([dir, { name }]) => [name, dir]))
483
+ const projectOf = (dir) => posix.relative(root, dir) || '.'
484
+ const reached = new Set(paths.map((path) => nearest(path, (dir) => manifests.has(projectOf(dir)))).filter((dir) => dir !== null).map(projectOf))
485
+ for (const dir of reached) {
486
+ const json = manifests.get(dir)
487
+ for (const field of ['dependencies', 'devDependencies', 'optionalDependencies', 'peerDependencies']) {
488
+ for (const name of isPlainObject(json[field]) ? Object.keys(json[field]) : []) if (byName.has(name)) reached.add(byName.get(name))
489
+ }
490
+ }
491
+ return reached
492
+ }
493
+
421
494
  // What deleteOutputDir clears before writing (its globs skip dot paths), in an output that must
422
495
  // already look like a client.
423
496
  const isStale = (path) => /(?:\.(?:js|ts|mts|cts|wasm|prisma)$|^package\.json$|^[^/]*\.node$|^(?:query|schema)-engine-[^/]*$)/u.test(path) && !path.split('/').some((name) => name.startsWith('.'))