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

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 (67) hide show
  1. package/README.md +1 -1
  2. package/bin/stasis.js +19 -6
  3. package/package.json +10 -9
  4. package/src/audit-corrections.js +11 -42
  5. package/src/audit.js +113 -233
  6. package/src/babel.js +39 -122
  7. package/src/bundle-from-lockfile.js +9 -21
  8. package/src/bundle-reader.js +5 -9
  9. package/src/bundle.js +0 -3
  10. package/src/cmd/build.js +50 -166
  11. package/src/cmd/bundle-options.js +110 -167
  12. package/src/cmd/bundle.js +853 -1344
  13. package/src/cmd/diff.js +1 -4
  14. package/src/cmd/github-bundle.js +18 -22
  15. package/src/cmd/output.js +15 -12
  16. package/src/cmd/sbom.js +3 -8
  17. package/src/cmd/tokens.js +10 -23
  18. package/src/define.js +34 -97
  19. package/src/diff.js +72 -128
  20. package/src/esbuild.js +0 -4
  21. package/src/flow.js +10 -25
  22. package/src/installed.js +265 -0
  23. package/src/json-stream.js +4 -9
  24. package/src/loader-mock.js +3 -8
  25. package/src/loader.js +1 -5
  26. package/src/loaders/bash.js +41 -93
  27. package/src/loaders/cargo.js +298 -805
  28. package/src/loaders/foundry.js +109 -285
  29. package/src/loaders/paths.js +13 -13
  30. package/src/loaders/php.js +210 -489
  31. package/src/loaders/rust.js +507 -1430
  32. package/src/loaders/solidity-ownership.js +48 -128
  33. package/src/loaders/solidity.js +39 -122
  34. package/src/loaders/toml.js +7 -17
  35. package/src/lockfile.js +0 -3
  36. package/src/metro-assets.js +9 -33
  37. package/src/metro-resolver.js +20 -47
  38. package/src/metro-transformer.js +0 -5
  39. package/src/metro.js +0 -4
  40. package/src/mock.js +32 -80
  41. package/src/parse.js +2 -5
  42. package/src/prune.js +0 -3
  43. package/src/resolve-fields.js +90 -220
  44. package/src/resolve-node.js +27 -45
  45. package/src/resolve-typescript.js +109 -313
  46. package/src/rollup.js +0 -4
  47. package/src/run-installed.js +10 -0
  48. package/src/sbom.js +52 -128
  49. package/src/scan.js +136 -283
  50. package/src/sixel.js +18 -41
  51. package/src/table.js +14 -35
  52. package/src/validate-notes.d.ts +3 -2
  53. package/src/validate-notes.js +25 -19
  54. package/src/validate.d.ts +38 -11
  55. package/src/validate.js +478 -512
  56. package/src/vfs-bundle/entries.js +40 -57
  57. package/src/vfs-bundle/github.js +77 -121
  58. package/src/vfs-bundle/glob.js +4 -45
  59. package/src/vfs-bundle/lazy.js +27 -56
  60. package/src/vfs-bundle/prisma.js +167 -110
  61. package/src/vfs-bundle/soldeer.js +28 -49
  62. package/src/vfs-bundle/tree.js +295 -318
  63. package/src/vfs-bundle/yarnclean.js +10 -31
  64. package/src/vfs-bundle.js +23 -64
  65. package/src/webpack.js +0 -4
  66. package/src/why.js +75 -231
  67. package/src/installed-commits.js +0 -184
@@ -1,26 +1,24 @@
1
1
  import { readFileSync } from 'node:fs'
2
2
  import { createRequire } from 'node:module'
3
- import { posix } from 'node:path'
3
+ import { dirname, 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, isPlainObject } from '@exodus/stasis-core/util'
7
+ import { CODE_EXTENSIONS, hasNodeModulesSegment, isPathWithin, isPlainObject, memoized, pathExt } 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'
11
11
  import { holding, nearest, projectView } from './tree.js'
12
12
 
13
- // buildVfsBundle's `generate: ['prisma']`: the client each project's `prisma generate` would write
14
- // with its installed Prisma, without running anything of the repo: schema, config, tsconfig.json
15
- // and package.json are read from the tree as data. The optional peer GENERATOR builds the client in
16
- // memory; an older version's is 7.10.0's rewritten (DOWN), tested byte for byte against its own.
13
+ // The client `prisma generate` would write, running nothing of the repo: schema, config, tsconfig.json and package.json
14
+ // are read as data. GENERATOR builds 7.10.0's in memory; an older version's is that rewritten (DOWN).
17
15
 
18
16
  const GENERATOR = '@prisma/client-generator-ts'
19
17
  const GENERATOR_VERSION = '7.10.0'
20
18
  const PROVIDER = 'prisma-client'
21
19
  const require = createRequire(import.meta.url)
22
20
 
23
- // The engine hash each Prisma stamps its client with, newest first.
21
+ // Newest first.
24
22
  const ENGINES = {
25
23
  '7.10.0': '0edf323efd1d98336f3f0a68684b56f689b900d3',
26
24
  '7.9.1': 'e922089b7d7502aff4249d5da3420f6fa55fc6ad',
@@ -36,26 +34,19 @@ const ENGINES = {
36
34
  export const PRISMA_VERSIONS = Object.keys(ENGINES)
37
35
  const newerThan = (version, than) => PRISMA_VERSIONS.indexOf(version) < PRISMA_VERSIONS.indexOf(than)
38
36
 
39
- // --- the generator ---
40
-
41
- // The bundle's readSourceFile, for the client `at` describes: an edge runtime's client copies the
42
- // query compiler from `prisma generate`'s own build, which here is the tree's `prisma`.
43
37
  const readQueryCompiler = (at) => (name) => {
44
38
  const file = posix.join(at.prismaDir, 'build', name)
45
39
  if (!isFile(file, at.host)) throw new Error(`prisma: ${file}, which a ${at.target} client carries, is not in the tree`)
46
40
  return Buffer.from(at.host.readFile(file))
47
41
  }
48
42
 
49
- // The bundle's inferModuleFormatFromNearestPackageJson, for node16 and nodenext; ESM before 7.10.0.
50
43
  const packageFormat = ({ host, version }) => (dir) => {
51
44
  if (!newerThan(version, '7.9.1')) return 'esm'
52
45
  const file = nearestFile(host, dir, 'package.json')
53
46
  try { return file !== null && JSON.parse(host.readFile(file).toString('utf8')).type === 'module' ? 'esm' : 'cjs' } catch { return 'cjs' }
54
47
  }
55
48
 
56
- // The esbuild bundle at `main` as a function of `parameters` returning `roots`, kept to the top-level
57
- // statements they reach by name (any word of a statement: more is kept than used, never less), and
58
- // refused where it then requires anything `given` doesn't hold, or by no literal name.
49
+ // Kept to the statements `roots` reach by any word (more than used, never less); refused if it requires what `given` lacks.
59
50
  function compiled(main, roots, parameters, given) {
60
51
  const source = readFileSync(main, 'utf8')
61
52
  const { body } = getParser().parseSync(main, source, { sourceType: 'script' }).program
@@ -74,9 +65,7 @@ function compiled(main, roots, parameters, given) {
74
65
  return compileFunction(`${reached}\nreturn { ${roots.join(', ')} }`, ['require', ...parameters], { filename: main }).bind(null, (id) => given[id])
75
66
  }
76
67
 
77
- // CommonJS files from `main` on, compiled requiring nothing outside their package but what `given`
78
- // holds (none reads __filename or __dirname).
79
- function commonjs(main, given) {
68
+ function commonjs(main, given, globals = {}) {
80
69
  const modules = new Map()
81
70
  const load = (file) => {
82
71
  if (modules.has(file)) return modules.get(file).exports
@@ -87,75 +76,89 @@ function commonjs(main, given) {
87
76
  if (!Object.hasOwn(given, id)) throw new Error(`--generate=prisma: ${file} requires ${id}, which stasis doesn't let it`)
88
77
  return given[id]
89
78
  }
90
- compileFunction(readFileSync(file, 'utf8'), ['exports', 'require', 'module'], { filename: file })(module.exports, requiring, module)
79
+ const parameters = ['exports', 'require', 'module', '__filename', '__dirname', ...Object.keys(globals)]
80
+ compileFunction(readFileSync(file, 'utf8'), parameters, { filename: file })(module.exports, requiring, module, file, dirname(file), ...Object.values(globals))
91
81
  return module.exports
92
82
  }
93
83
  return load(main)
94
84
  }
95
85
 
96
- // The schema engine's refusals are JSON with a `message`; its panics aren't.
97
86
  const engineMessage = (message) => { try { return JSON.parse(message).message ?? message } catch { return message } }
98
87
 
99
- // What the compiled generator returns, is given, and requires as Node loads it (none of it the
100
- // disk's); given, as readSourceFile and inferModuleFormatFromNearestPackageJson read the disk,
101
- // `debug` would require @prisma/debug, and buildTypedSql is undefined: stasis passes no typedSql.
88
+ // One engine per schema, its panic hook its own: a panic leaves an instance in a state none was built for.
89
+ function schemaEngines(near) {
90
+ const glue = near.resolve('@prisma/prisma-schema-wasm')
91
+ const fs = { readFileSync: memoized((file) => readFileSync(file)) }
92
+ const dmmf = near.resolve('@prisma/get-dmmf')
93
+ const besideDmmf = createRequire(dmmf)
94
+ const dmmfGiven = Object.fromEntries(['@prisma/debug', '@streamparser/json', 'pluralize'].map((id) => [id, besideDmmf(id)]))
95
+ const getDmmf = (engine) => commonjs(dmmf, { ...dmmfGiven, '@prisma/prisma-schema-wasm': engine })
96
+ const schemaEngine = () => {
97
+ let panic
98
+ const engine = commonjs(glue, { fs }, { global: { PRISMA_WASM_PANIC_REGISTRY: { set_message: (message) => { panic = message } } } })
99
+ const { getDMMF } = getDmmf(engine)
100
+ const calling = (run) => (options) => {
101
+ try {
102
+ return run(options)
103
+ } catch (error) {
104
+ throw panic === undefined ? error : new Error(`the schema engine panicked: ${panic}`, { cause: error })
105
+ }
106
+ }
107
+ return {
108
+ // Without resolving binaryTargets, which the generator never reads.
109
+ getConfig: calling(({ datamodel }) => {
110
+ const { config, errors } = JSON.parse(engine.get_config(JSON.stringify({ prismaSchema: datamodel })))
111
+ if (errors.length > 0) throw new Error(errors.map((error) => error.message).join('\n'))
112
+ return config
113
+ }),
114
+ getDMMF: calling((options) => {
115
+ const result = getDMMF(options)
116
+ if ('error' in result) throw new Error(engineMessage(result.error.message), { cause: result.error })
117
+ return result
118
+ }),
119
+ mergeSchemas: calling(({ schemas }) => engine.merge_schemas(JSON.stringify({ schema: schemas }))),
120
+ }
121
+ }
122
+ // externalToInternalDmmf, the generator's, reads no schema: its get-dmmf has no engine.
123
+ return { schemaEngine, externalToInternalDmmf: getDmmf({}).externalToInternalDmmf }
124
+ }
125
+
126
+ // buildTypedSql is left undefined: stasis passes no typedSql.
102
127
  const EXPORTS = ['buildClient', 'validateDmmfAgainstDenylists', 'parseRuntimeTargetFromUnknown', 'parseGeneratedFileExtension', 'parseImportFileExtension', 'inferImportFileExtension', 'parseModuleFormatFromUnknown', 'inferModuleFormat', 'parseCompilerBuildFromUnknown']
103
128
  const PARAMETERS = ['readSourceFile', 'inferModuleFormatFromNearestPackageJson', 'debug', 'buildTypedSql']
104
129
  const REQUIRES = ['@prisma/client-common', '@prisma/dmmf', '@prisma/param-graph-builder', 'indent-string', 'klona', 'pluralize', 'ts-pattern']
105
130
  let loaded
106
131
 
107
- // The peer exports neither buildClient (generateClient's in-memory half), the reserved-names check
108
- // generateClient runs, nor its generate()'s option parsing and inference, so its bundle is compiled
109
- // to return them, stripped (cleanup, not a sandbox) of what they never reach. @prisma/internals is
110
- // never loaded: loading it reads the host's npm and yarn config and platform, and patches fs and
111
- // process.cwd. Its users get a stand-in: its parsing the schema engine's and @prisma/get-dmmf's,
112
- // which it wraps, and its isValidJsIdentifier its own file's, whose Unicode tables aren't Node's.
113
- function loadGenerator() {
132
+ // The peer exports none of EXPORTS, so its bundle is compiled to return them (stripping is cleanup, not a sandbox).
133
+ // @prisma/internals is never loaded (it reads the host's npm and yarn config, and patches fs and process.cwd).
134
+ export function loadGenerator() {
114
135
  if (loaded) return loaded
115
136
  let main
116
137
  try { main = require.resolve(GENERATOR) } catch (cause) { throw new Error(`--generate=prisma needs the optional '${GENERATOR}' ${GENERATOR_VERSION} dependency; install it (e.g. \`npm i ${GENERATOR}@${GENERATOR_VERSION}\`)`, { cause }) }
117
138
  const own = createRequire(main)
118
139
  const { version } = own('../package.json')
119
140
  if (version !== GENERATOR_VERSION) throw new Error(`--generate=prisma needs ${GENERATOR} ${GENERATOR_VERSION}, not ${version}`)
120
- // Prisma's packages beside the @prisma/internals the peer was built with.
121
141
  const near = createRequire(own.resolve('@prisma/internals'))
122
- const engine = near('@prisma/prisma-schema-wasm')
123
- const getDmmf = near('@prisma/get-dmmf')
142
+ const { schemaEngine, externalToInternalDmmf } = schemaEngines(near)
124
143
  const internals = {
125
- externalToInternalDmmf: getDmmf.externalToInternalDmmf,
144
+ externalToInternalDmmf,
126
145
  hasOwnProperty: Object.hasOwn,
127
146
  assertNever: (value, message) => { throw new Error(message) },
128
147
  isValidJsIdentifier: commonjs(own.resolve('@prisma/internals/dist/utils/isValidJsIdentifier.js'), {}).isValidJsIdentifier,
129
- // But for resolving binaryTargets, which the generator never reads.
130
- getConfig: ({ datamodel }) => {
131
- const { config, errors } = JSON.parse(engine.get_config(JSON.stringify({ prismaSchema: datamodel })))
132
- if (errors.length > 0) throw new Error(errors.map((error) => error.message).join('\n'))
133
- return config
134
- },
135
- getDMMF: (options) => {
136
- const result = getDmmf.getDMMF(options)
137
- if ('error' in result) throw new Error(engineMessage(result.error.message), { cause: result.error })
138
- return result
139
- },
140
- mergeSchemas: ({ schemas }) => engine.merge_schemas(JSON.stringify({ schema: schemas })),
141
148
  }
142
149
  const given = { ...Object.fromEntries(REQUIRES.map((id) => [id, own(id)])), '@prisma/internals': internals, '@prisma/ts-builders': commonjs(own.resolve('@prisma/ts-builders'), { '@prisma/internals': internals }) }
143
150
  const run = compiled(main, EXPORTS, PARAMETERS, given)
144
151
  const { loadSchemaFiles } = compiled(near.resolve('@prisma/schema-files-loader'), ['loadSchemaFiles'], ['realFsResolver'], { 'node:path': posix })()
145
- // `peer` is evaluated for each client (a millisecond), its functions given what they read.
146
- loaded = { peer: (at) => run(readQueryCompiler(at), packageFormat(at), () => {}), internals, loadSchemaFiles }
152
+ loaded = { peer: (at) => run(readQueryCompiler(at), packageFormat(at), () => {}), schemaEngine, loadSchemaFiles }
147
153
  return loaded
148
154
  }
149
155
 
150
- // --- what `prisma generate` reads ---
151
-
152
156
  const nearestFile = (host, dir, name) => {
153
157
  const at = nearest(dir, holding(host, name))
154
158
  return at === null ? null : posix.join(at, name)
155
159
  }
156
160
 
157
- // The `prisma` Node resolves from `dir`, or where that is unsupported (Prisma 8, say), the one
158
- // `@prisma/prisma7` runs as `prisma7` beside it.
161
+ // Where the `prisma` Node resolves is unsupported (Prisma 8, say), the one `@prisma/prisma7` runs as `prisma7`.
159
162
  function installedPrisma(host, dir) {
160
163
  const installed = (from) => {
161
164
  const file = nearestFile(host, from, 'node_modules/prisma/package.json')
@@ -167,18 +170,14 @@ function installedPrisma(host, dir) {
167
170
  return PRISMA_VERSIONS.includes(beside?.version) ? beside : prisma
168
171
  }
169
172
 
170
- // @prisma/config's search order; only 7.10.0 reads the first two (prisma7.config.*).
173
+ // @prisma/config's search order; only 7.10.0 reads the first two.
171
174
  const CONFIG_BASES = ['prisma7.config', '.config/prisma7', ...['prisma.config', '.config/prisma', '.config/prisma.config'].flatMap((base) => [base, `${base}/index`])]
172
175
  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
176
  const DEFAULT_SCHEMAS = ['schema.prisma', 'prisma/schema.prisma']
175
177
 
176
- // The modules a config's top-level imports and requires may bind, as `name.export` (`name.*`: the module).
177
178
  const MODULES = { path: 'path', 'node:path': 'path', 'prisma/config': 'config', '@prisma/config': 'config' }
178
179
 
179
- // The `schema` a Prisma config names, read from its syntax tree: the config is never run, nor
180
- // anything built from it. A string literal or path.join of them is taken, through defineConfig,
181
- // `as`, `satisfies`, parentheses and top-level consts; anything else is refused.
180
+ // Read from the syntax tree: the config is never run, nor anything built from it.
182
181
  function configSchema(file, text) {
183
182
  const parsed = getParser().parseSync(file, text, { sourceType: 'unambiguous' })
184
183
  const [error] = syntaxErrors(parsed)
@@ -227,9 +226,8 @@ function configSchema(file, text) {
227
226
  return schema
228
227
  }
229
228
 
230
- // A schema directory is read by Prisma's own loader, over the tree.
231
229
  function schemaFilesAt(host, path) {
232
- if (isFile(path, host)) return [[path, host.readFile(path).toString('utf8')]]
230
+ if (isFile(path, host)) return schemaTexts(host, path)
233
231
  const view = projectView(host, '/')
234
232
  return loadGenerator().loadSchemaFiles(path, {
235
233
  listDirContents: async (dir) => view.readdir(dir),
@@ -238,8 +236,6 @@ function schemaFilesAt(host, path) {
238
236
  })
239
237
  }
240
238
 
241
- // The schema path `prisma generate` takes at `dir`: the config's `schema` (relative to the config),
242
- // else ./schema.prisma or ./prisma/schema.prisma; null if none.
243
239
  function projectSchema(host, dir, version) {
244
240
  const first = (names) => names.map((name) => posix.join(dir, name)).find((file) => isFile(file, host))
245
241
  const config = first(configFiles(CONFIG_BASES.slice(newerThan(version, '7.9.1') ? 0 : 2)))
@@ -250,10 +246,7 @@ function projectSchema(host, dir, version) {
250
246
  return path
251
247
  }
252
248
 
253
- // --- the generator's options, as its generate() parses and infers them, with its own functions ---
254
-
255
- // The inference reads the nearest tsconfig.json as get-tsconfig 4.10 gives it, defaults included: an
256
- // ES2015+ target's module, else preserve's bundler resolution.
249
+ // As its generate() infers them, from the nearest tsconfig.json as get-tsconfig 4.10 gives it, defaults included.
257
250
  const ES_TARGETS = new Set(['es6', 'es2015', 'es2016', 'es2017', 'es2018', 'es2019', 'es2020', 'es2021', 'es2022', 'es2023', 'es2024', 'esnext'])
258
251
  function generatorOptions(peer, host, config, outputDir) {
259
252
  const file = nearestFile(host, outputDir, 'tsconfig.json')
@@ -269,8 +262,6 @@ function generatorOptions(peer, host, config, outputDir) {
269
262
  return { target, generatedFileExtension, importFileExtension, moduleFormat, compilerBuild }
270
263
  }
271
264
 
272
- // --- 7.10.0's client as each older version writes it ---
273
-
274
265
  // A missing `from` means the client isn't the one these rewrites were written against: refused unless `optional` (null).
275
266
  function swap(text, from, to, { path, all, optional }) {
276
267
  if (typeof from === 'string' ? text.includes(from) : from.test(text)) return all ? text.replaceAll(from, () => to) : text.replace(from, () => to)
@@ -278,7 +269,6 @@ function swap(text, from, to, { path, all, optional }) {
278
269
  throw new Error(`prisma: ${path} of the ${GENERATOR_VERSION} client holds no ${JSON.stringify(String(from).slice(0, 80))}`)
279
270
  }
280
271
 
281
- // File stems, without the generated extension (MODELS: each of models/).
282
272
  const CLASS = 'internal/class'
283
273
  const NAMESPACE = 'internal/prismaNamespace'
284
274
  const MODELS = 'models/*'
@@ -345,14 +335,12 @@ const DOWN = {
345
335
  '7.4.0': { [CLASS]: (text, path) => swap(text, 'https://www.prisma.io/docs/orm/prisma-client/queries/transactions', 'https://www.prisma.io/docs/concepts/components/prisma-client/transactions', { path }) },
346
336
  }
347
337
 
348
- // Where each client stamps its version and engine.
349
338
  const STAMPS = [
350
339
  [CLASS, (version) => `"clientVersion": "${version}",\n "engineVersion": "${ENGINES[version]}",`],
351
340
  [NAMESPACE, (version) => ` * Prisma Client JS version: ${version}\n * Query Engine version: ${ENGINES[version]}\n`],
352
341
  [NAMESPACE, (version) => ` client: "${version}",\n engine: "${ENGINES[version]}"\n`],
353
342
  ]
354
343
 
355
- // A 7.10.0 client file as `version` writes it.
356
344
  function asVersion(text, path, version, extension) {
357
345
  if (typeof text !== 'string') return text
358
346
  const key = path.startsWith('models/') ? MODELS : path.slice(0, -extension.length - 1)
@@ -361,9 +349,6 @@ function asVersion(text, path, version, extension) {
361
349
  return text
362
350
  }
363
351
 
364
- // --- generating ---
365
-
366
- // One generator's client: path in the output -> text (bytes for the query compiler's .wasm).
367
352
  function generateClientFor({ schemaPath, datamodel, generator, dmmf, datasources, outputDir, prisma, host }) {
368
353
  const client = { host, version: prisma.version, prismaDir: posix.dirname(prisma.file) }
369
354
  const peer = loadGenerator().peer(client)
@@ -375,19 +360,15 @@ function generateClientFor({ schemaPath, datamodel, generator, dmmf, datasources
375
360
  })
376
361
  const denied = peer.validateDmmfAgainstDenylists(built.prismaClientDmmf)
377
362
  if (denied) throw new Error(`prisma: ${schemaPath} contains reserved keywords, to rename: ${denied.map((error) => error.message).join(', ')}`)
378
- // fileMap nests directories as objects.
379
363
  const flat = (map, at) => Object.entries(map).flatMap(([name, content]) => (typeof content === 'string' || Buffer.isBuffer(content) ? [[at + name, content]] : flat(content, `${at}${name}/`)))
380
364
  return new Map(flat(built.fileMap, '').map(([path, content]) => [path, asVersion(content, path, prisma.version, options.generatedFileExtension)]))
381
365
  }
382
366
 
383
367
  const readingSchema = (path, what) => Promise.try(what).catch((cause) => { throw new Error(`prisma: ${path}: ${cause.message}`, { cause }) })
384
368
 
385
- // Where a generator's `output` points, relative to the schema file declaring it.
386
369
  const outputOf = (generator, path) => posix.resolve(posix.dirname(generator.sourceFilePath ?? path), generator.output.value)
387
370
 
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.
371
+ // The bundle takes what it reaches there as committed, however stale; none in node_modules, nor one env() names.
391
372
  function committedOutput(host, generator, path) {
392
373
  if (generator.output === null || generator.output.fromEnvVar !== null) return undefined
393
374
  const output = outputOf(generator, path)
@@ -396,68 +377,95 @@ function committedOutput(host, generator, path) {
396
377
 
397
378
  const ours = (generator) => generator.provider.value === PROVIDER && generator.provider.fromEnvVar === null
398
379
  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
380
  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
381
 
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.
382
+ // Not warned of: with no `output`, it writes types alone into its own package (a placeholder in node_modules), but
383
+ // with `generateDatamodel = "true"` getDatamodel() too, code a bundle may run.
406
384
  const POTHOS = 'prisma-pothos-types'
407
385
  const needsNoOutput = (generator) => generator.provider.value === POTHOS && generator.provider.fromEnvVar === null &&
408
386
  generator.output === null && generator.config.generateDatamodel !== 'true'
409
387
 
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.
388
+ const DEFAULT_OUTPUTS = { __proto__: null, 'prisma-client-js': '.prisma/client', [POTHOS]: '@pothos/plugin-prisma/generated' }
389
+
390
+ // A directory of .prisma files is walked as Prisma's loader walks it: through links, by real path.
391
+ function schemaTexts(host, path) {
392
+ if (isFile(path, host)) return [[path, host.readFile(path).toString('utf8')]]
393
+ const seen = new Set()
394
+ const walk = (dir) => {
395
+ const real = host.realpath(dir)
396
+ if (seen.has(real)) return []
397
+ seen.add(real)
398
+ return host.readdir(real).map((entry) => entry.name).toSorted().flatMap((name) => {
399
+ const at = posix.join(real, name)
400
+ if (isDir(at, host)) return walk(at)
401
+ return at.endsWith('.prisma') && isFile(at, host) ? [[host.realpath(at), host.readFile(at).toString('utf8')]] : []
402
+ })
403
+ }
404
+ return walk(path)
405
+ }
406
+
407
+ // Read without Prisma's parser, which another Prisma's schema needn't satisfy and which needs the optional peer.
408
+ function generatorBlocks(host, path) {
409
+ let files
410
+ try { files = schemaTexts(host, path) } catch { return [] }
411
+ return files.flatMap(([file, text]) => [...text.replaceAll(/\/\/.*$/gmu, '').matchAll(/^\s*generator\s+(\w+)\s*\{([^}]*)\}/gmu)].map(([, name, body]) => {
412
+ const field = (key) => {
413
+ const found = body.match(new RegExp(`^\\s*${key}\\s*=\\s*(?:"([^"]*)"|env\\(\\s*"([^"]*)"\\s*\\))`, 'mu'))
414
+ return found === null ? null : { value: found[1] ?? null, fromEnvVar: found[2] ?? null }
415
+ }
416
+ return { name, provider: field('provider') ?? { value: null, fromEnvVar: null }, output: field('output'), sourceFilePath: file, config: {} }
417
+ }))
418
+ }
419
+
420
+ // Looked for before any `prisma` is read, which a lazy tree fetches once read.
412
421
  const hasSchema = (host) => holding(host, ...configFiles(CONFIG_BASES), ...DEFAULT_SCHEMAS)
413
422
  export const schemaProjects = (host, root, projects) => new Set([...projects].filter((project) => hasSchema(host)(posix.join(root, project))))
414
423
 
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.
419
424
  /* eslint-disable no-await-in-loop -- one project at a time, in the order its warnings read */
420
- export async function generatePrismaClients({ host, root, projects, strict = true }) {
425
+ export async function generatePrismaClients({ host, root, projects, strict = true, shared = false }) {
421
426
  const outputs = []
427
+ const reasons = new Map()
428
+ const schemas = new Map()
422
429
  const say = strict ? (message) => { console.warn(`[stasis] prisma: ${message}`) } : undefined
423
- const skip = (what, why) => say?.(`not generating ${what}: ${why}`)
430
+ const skip = (what, why) => say?.(notGenerating(what, why))
424
431
  for (const project of [...projects].toSorted()) {
425
432
  const dir = posix.join(root, project)
426
433
  const prisma = installedPrisma(host, dir)
427
434
  const supported = PRISMA_VERSIONS.includes(prisma?.version)
428
435
  const path = await Promise.try(projectSchema, host, dir, supported ? prisma.version : GENERATOR_VERSION).catch((error) => skip(`for ${dir}`, error.message))
436
+ schemas.set(project, path || null)
429
437
  if (!path) continue
430
438
  // Checked before parsing: another Prisma's schema needn't satisfy 7.10.0.
431
439
  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}`}`)
440
+ reasons.set(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}`}`)
441
+ skip(`for ${path}`, reasons.get(path))
433
442
  continue
434
443
  }
435
444
  try {
436
445
  outputs.push(...await generateSchema({ host, path, prisma, say, skip }))
437
446
  } catch (error) {
438
447
  if (strict) throw error
448
+ reasons.set(path, error.message.replace(/^prisma: /u, ''))
439
449
  }
440
450
  }
441
451
  const dirs = outputs.map(({ dir }) => dir)
442
452
  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
453
+ if (twice !== undefined && !shared) throw new Error(`prisma: ${twice} is the output of more than one generator`)
454
+ return { outputs, reasons, schemas }
445
455
  }
446
456
  /* eslint-enable no-await-in-loop */
447
457
 
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
458
  async function generateSchema({ host, path, prisma, say, skip }) {
451
459
  const files = await readingSchema(path, () => schemaFilesAt(host, path))
452
- const { internals } = loadGenerator()
453
- const config = await readingSchema(path, () => internals.getConfig({ datamodel: files }))
460
+ const engine = loadGenerator().schemaEngine()
461
+ const config = await readingSchema(path, () => engine.getConfig({ datamodel: files }))
454
462
  const generators = config.generators.filter(ours)
455
463
  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
464
  if (generators.length === 0) return []
457
465
  for (const warning of config.warnings) say?.(warning)
458
466
  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 })
467
+ const dmmf = await readingSchema(path, () => engine.getDMMF({ datamodel: files }))
468
+ const datamodel = await readingSchema(path, () => engine.mergeSchemas({ schemas: files }))
461
469
  const outputs = []
462
470
  for (const generator of generators) {
463
471
  if (generator.output === null) throw new Error(`prisma: ${path}: generator ${generator.name} names no output`)
@@ -467,13 +475,65 @@ async function generateSchema({ host, path, prisma, say, skip }) {
467
475
  }
468
476
  const outputDir = outputOf(generator, path)
469
477
  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 }) })
478
+ const client = generateClientFor({ schemaPath: path, datamodel, generator, dmmf, datasources: config.datasources, outputDir, prisma, host })
479
+ outputs.push({ dir: outputDir, files: client, schema: path, generator: generator.name, prisma: prisma.version })
471
480
  }
472
481
  return outputs
473
482
  }
474
483
 
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.
484
+ // Read from the schemas alone: a project's is the one generation took, else each a supported Prisma would take.
485
+ export function expectedOutputs({ host, root, projects, outputs = [], reasons = new Map(), schemas, off }) {
486
+ const generated = new Set(outputs.map(({ dir }) => dir))
487
+ const taken = (dir, version) => {
488
+ try {
489
+ return projectSchema(host, dir, version)
490
+ } catch {
491
+ return null
492
+ }
493
+ }
494
+ return [...projects].toSorted().flatMap((project) => {
495
+ const dir = posix.join(root, project)
496
+ const paths = schemas?.has(project) ? [schemas.get(project)] : new Set([GENERATOR_VERSION, PRISMA_VERSIONS.at(-1)].map((version) => taken(dir, version)))
497
+ return [...paths].filter(Boolean).flatMap((path) => generatorBlocks(host, path).flatMap((generator) => {
498
+ const writer = `${path}'s generator ${generator.name}`
499
+ if (generator.output === null) {
500
+ const specifier = generator.provider.fromEnvVar === null ? DEFAULT_OUTPUTS[generator.provider.value] : undefined
501
+ return specifier === undefined ? [] : [{ specifier, writer, why: off ?? SKIPPED }]
502
+ }
503
+ if (generator.output.fromEnvVar !== null) return []
504
+ const output = outputOf(generator, path)
505
+ if (generated.has(output)) return []
506
+ return [{ path: output, writer, why: off ?? (!ours(generator) ? SKIPPED : reasons.get(path) ?? "stasis didn't generate it") }]
507
+ }))
508
+ })
509
+ }
510
+
511
+ // A TypeScript import may leave the extension out, or write `.js` for a `.ts` file.
512
+ function withoutExtension(path) {
513
+ const stripped = path.replace(/\.d\.[mc]?ts$/iu, '')
514
+ const ext = pathExt(stripped)
515
+ return CODE_EXTENSIONS.has(ext) ? stripped.slice(0, -ext.length - 1) : stripped
516
+ }
517
+
518
+ export function generatedMiss(expected) {
519
+ const outputs = expected.filter(({ path }) => path !== undefined).map((each) => ({ ...each, bare: withoutExtension(each.path) }))
520
+ const defaults = expected.filter(({ specifier }) => specifier !== undefined)
521
+ return (u) => {
522
+ const hit = outputs.find(({ path, bare }) => u.targets?.some((target) => isPathWithin(path, target) || withoutExtension(target) === bare || posix.join(target, 'index') === bare)) ??
523
+ defaults.find(({ specifier }) => u.spec === specifier || u.spec?.startsWith(`${specifier}/`))
524
+ return hit && `${hit.writer} would write it, but ${hit.why}`
525
+ }
526
+ }
527
+
528
+ export function committedWarnings(expected, bundle, root) {
529
+ const skipped = expected.filter(({ path, why }) => path !== undefined && why === SKIPPED && !hasNodeModulesSegment(path))
530
+ const files = [...bundle.sources.keys()]
531
+ return skipped.filter(({ path }) => {
532
+ const rel = posix.relative(root, path)
533
+ return bundle.sources.has(rel) || files.some((file) => file.startsWith(`${rel}/`))
534
+ }).map(({ writer, path }) => `[stasis] prisma: ${notGenerating(writer, SKIPPED, path)}`)
535
+ }
536
+
477
537
  export function reachedProjects(host, root, projects, paths) {
478
538
  const manifests = new Map([...projects].map((dir) => {
479
539
  const json = readJson(posix.join(root, dir, 'package.json'), host)
@@ -484,19 +544,16 @@ export function reachedProjects(host, root, projects, paths) {
484
544
  const reached = new Set(paths.map((path) => nearest(path, (dir) => manifests.has(projectOf(dir)))).filter((dir) => dir !== null).map(projectOf))
485
545
  for (const dir of reached) {
486
546
  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
- }
547
+ const names = ['dependencies', 'devDependencies', 'optionalDependencies', 'peerDependencies'].flatMap((field) => (isPlainObject(json[field]) ? Object.keys(json[field]) : []))
548
+ for (const name of names) if (byName.has(name)) reached.add(byName.get(name))
490
549
  }
491
550
  return reached
492
551
  }
493
552
 
494
- // What deleteOutputDir clears before writing (its globs skip dot paths), in an output that must
495
- // already look like a client.
553
+ // What deleteOutputDir clears before writing (its globs skip dot paths).
496
554
  const isStale = (path) => /(?:\.(?:js|ts|mts|cts|wasm|prisma)$|^package\.json$|^[^/]*\.node$|^(?:query|schema)-engine-[^/]*$)/u.test(path) && !path.split('/').some((name) => name.startsWith('.'))
497
555
  const CLIENT_FILES = ['client.ts', 'client.mts', 'client.cts', 'client.d.ts']
498
556
 
499
- // A copy of `vfs` with the outputs written over any earlier client, as `prisma generate` does.
500
557
  export function withPrismaClients(vfs, outputs) {
501
558
  const out = createVfs()
502
559
  out.mount(vfs, '/')