@exodus/stasis 1.0.0-beta.9 → 1.0.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/README.md +6 -2
  2. package/bin/stasis.js +222 -334
  3. package/package.json +38 -14
  4. package/src/audit-corrections.js +11 -42
  5. package/src/audit.js +256 -212
  6. package/src/babel.js +119 -82
  7. package/src/bundle-from-lockfile.js +9 -21
  8. package/src/bundle-reader.js +24 -8
  9. package/src/bundle.js +0 -3
  10. package/src/cmd/build.js +211 -117
  11. package/src/cmd/bundle-options.js +347 -0
  12. package/src/cmd/bundle.js +1664 -1001
  13. package/src/cmd/diff.js +1 -4
  14. package/src/cmd/github-bundle.js +48 -21
  15. package/src/cmd/output.js +25 -12
  16. package/src/cmd/sbom.js +6 -9
  17. package/src/cmd/tokens.js +60 -0
  18. package/src/define.js +218 -0
  19. package/src/diff.js +73 -129
  20. package/src/esbuild.js +0 -4
  21. package/src/flow.js +27 -0
  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 +43 -120
  27. package/src/loaders/cargo.js +301 -808
  28. package/src/loaders/foundry.js +112 -290
  29. package/src/loaders/paths.js +15 -26
  30. package/src/loaders/php.js +211 -492
  31. package/src/loaders/rust.js +518 -1461
  32. package/src/loaders/solidity-ownership.js +51 -142
  33. package/src/loaders/solidity.js +42 -188
  34. package/src/loaders/toml.js +7 -17
  35. package/src/lockfile.js +0 -3
  36. package/src/metro-assets.js +41 -0
  37. package/src/metro-resolver.js +58 -133
  38. package/src/metro-transformer.js +0 -6
  39. package/src/metro.js +0 -4
  40. package/src/mock.js +32 -80
  41. package/src/parse.js +8 -7
  42. package/src/prune.js +0 -3
  43. package/src/resolve-fields.js +152 -249
  44. package/src/resolve-node.js +29 -45
  45. package/src/resolve-typescript.js +166 -298
  46. package/src/rollup.js +0 -4
  47. package/src/run-installed.js +10 -0
  48. package/src/sbom.js +70 -97
  49. package/src/scan.js +240 -282
  50. package/src/sixel.js +310 -0
  51. package/src/table.js +95 -0
  52. package/src/validate-notes.d.ts +19 -0
  53. package/src/validate-notes.js +72 -0
  54. package/src/validate.d.ts +159 -0
  55. package/src/validate.js +1315 -0
  56. package/src/vfs-bundle/entries.js +50 -46
  57. package/src/vfs-bundle/github.js +114 -94
  58. package/src/vfs-bundle/glob.js +379 -0
  59. package/src/vfs-bundle/lazy.js +99 -0
  60. package/src/vfs-bundle/prisma.js +235 -105
  61. package/src/vfs-bundle/soldeer.js +28 -49
  62. package/src/vfs-bundle/tree.js +418 -277
  63. package/src/vfs-bundle/yarnclean.js +79 -0
  64. package/src/vfs-bundle.js +24 -55
  65. package/src/webpack.js +0 -4
  66. package/src/why.js +79 -231
  67. package/src/installed-commits.js +0 -182
@@ -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 } 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,15 +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`])]
175
+ const configFiles = (bases) => bases.flatMap((base) => ['.js', '.ts', '.mjs', '.cjs', '.mts', '.cts'].map((ext) => `${base}${ext}`))
176
+ const DEFAULT_SCHEMAS = ['schema.prisma', 'prisma/schema.prisma']
172
177
 
173
- // The modules a config's top-level imports and requires may bind, as `name.export` (`name.*`: the module).
174
178
  const MODULES = { path: 'path', 'node:path': 'path', 'prisma/config': 'config', '@prisma/config': 'config' }
175
179
 
176
- // The `schema` a Prisma config names, read from its syntax tree: the config is never run, nor
177
- // anything built from it. A string literal or path.join of them is taken, through defineConfig,
178
- // `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.
179
181
  function configSchema(file, text) {
180
182
  const parsed = getParser().parseSync(file, text, { sourceType: 'unambiguous' })
181
183
  const [error] = syntaxErrors(parsed)
@@ -224,9 +226,8 @@ function configSchema(file, text) {
224
226
  return schema
225
227
  }
226
228
 
227
- // A schema directory is read by Prisma's own loader, over the tree.
228
229
  function schemaFilesAt(host, path) {
229
- if (isFile(path, host)) return [[path, host.readFile(path).toString('utf8')]]
230
+ if (isFile(path, host)) return schemaTexts(host, path)
230
231
  const view = projectView(host, '/')
231
232
  return loadGenerator().loadSchemaFiles(path, {
232
233
  listDirContents: async (dir) => view.readdir(dir),
@@ -235,22 +236,17 @@ function schemaFilesAt(host, path) {
235
236
  })
236
237
  }
237
238
 
238
- // The schema path `prisma generate` takes at `dir`: the config's `schema` (relative to the config),
239
- // else ./schema.prisma or ./prisma/schema.prisma; null if none.
240
239
  function projectSchema(host, dir, version) {
241
240
  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}`)))
241
+ const config = first(configFiles(CONFIG_BASES.slice(newerThan(version, '7.9.1') ? 0 : 2)))
243
242
  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)
243
+ const path = named === undefined ? first(DEFAULT_SCHEMAS) : posix.resolve(posix.dirname(config), named)
245
244
  if (path === undefined) return null
246
245
  if (!isFile(path, host) && !isDir(path, host)) throw new Error(`${config}: its schema ${named} is no file or directory`)
247
246
  return path
248
247
  }
249
248
 
250
- // --- the generator's options, as its generate() parses and infers them, with its own functions ---
251
-
252
- // The inference reads the nearest tsconfig.json as get-tsconfig 4.10 gives it, defaults included: an
253
- // 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.
254
250
  const ES_TARGETS = new Set(['es6', 'es2015', 'es2016', 'es2017', 'es2018', 'es2019', 'es2020', 'es2021', 'es2022', 'es2023', 'es2024', 'esnext'])
255
251
  function generatorOptions(peer, host, config, outputDir) {
256
252
  const file = nearestFile(host, outputDir, 'tsconfig.json')
@@ -266,8 +262,6 @@ function generatorOptions(peer, host, config, outputDir) {
266
262
  return { target, generatedFileExtension, importFileExtension, moduleFormat, compilerBuild }
267
263
  }
268
264
 
269
- // --- 7.10.0's client as each older version writes it ---
270
-
271
265
  // A missing `from` means the client isn't the one these rewrites were written against: refused unless `optional` (null).
272
266
  function swap(text, from, to, { path, all, optional }) {
273
267
  if (typeof from === 'string' ? text.includes(from) : from.test(text)) return all ? text.replaceAll(from, () => to) : text.replace(from, () => to)
@@ -275,7 +269,6 @@ function swap(text, from, to, { path, all, optional }) {
275
269
  throw new Error(`prisma: ${path} of the ${GENERATOR_VERSION} client holds no ${JSON.stringify(String(from).slice(0, 80))}`)
276
270
  }
277
271
 
278
- // File stems, without the generated extension (MODELS: each of models/).
279
272
  const CLASS = 'internal/class'
280
273
  const NAMESPACE = 'internal/prismaNamespace'
281
274
  const MODELS = 'models/*'
@@ -342,14 +335,12 @@ const DOWN = {
342
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 }) },
343
336
  }
344
337
 
345
- // Where each client stamps its version and engine.
346
338
  const STAMPS = [
347
339
  [CLASS, (version) => `"clientVersion": "${version}",\n "engineVersion": "${ENGINES[version]}",`],
348
340
  [NAMESPACE, (version) => ` * Prisma Client JS version: ${version}\n * Query Engine version: ${ENGINES[version]}\n`],
349
341
  [NAMESPACE, (version) => ` client: "${version}",\n engine: "${ENGINES[version]}"\n`],
350
342
  ]
351
343
 
352
- // A 7.10.0 client file as `version` writes it.
353
344
  function asVersion(text, path, version, extension) {
354
345
  if (typeof text !== 'string') return text
355
346
  const key = path.startsWith('models/') ? MODELS : path.slice(0, -extension.length - 1)
@@ -358,9 +349,6 @@ function asVersion(text, path, version, extension) {
358
349
  return text
359
350
  }
360
351
 
361
- // --- generating ---
362
-
363
- // One generator's client: path in the output -> text (bytes for the query compiler's .wasm).
364
352
  function generateClientFor({ schemaPath, datamodel, generator, dmmf, datasources, outputDir, prisma, host }) {
365
353
  const client = { host, version: prisma.version, prismaDir: posix.dirname(prisma.file) }
366
354
  const peer = loadGenerator().peer(client)
@@ -372,58 +360,200 @@ function generateClientFor({ schemaPath, datamodel, generator, dmmf, datasources
372
360
  })
373
361
  const denied = peer.validateDmmfAgainstDenylists(built.prismaClientDmmf)
374
362
  if (denied) throw new Error(`prisma: ${schemaPath} contains reserved keywords, to rename: ${denied.map((error) => error.message).join(', ')}`)
375
- // fileMap nests directories as objects.
376
363
  const flat = (map, at) => Object.entries(map).flatMap(([name, content]) => (typeof content === 'string' || Buffer.isBuffer(content) ? [[at + name, content]] : flat(content, `${at}${name}/`)))
377
364
  return new Map(flat(built.fileMap, '').map(([path, content]) => [path, asVersion(content, path, prisma.version, options.generatedFileExtension)]))
378
365
  }
379
366
 
380
367
  const readingSchema = (path, what) => Promise.try(what).catch((cause) => { throw new Error(`prisma: ${path}: ${cause.message}`, { cause }) })
381
368
 
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.
369
+ const outputOf = (generator, path) => posix.resolve(posix.dirname(generator.sourceFilePath ?? path), generator.output.value)
370
+
371
+ // The bundle takes what it reaches there as committed, however stale; none in node_modules, nor one env() names.
372
+ function committedOutput(host, generator, path) {
373
+ if (generator.output === null || generator.output.fromEnvVar !== null) return undefined
374
+ const output = outputOf(generator, path)
375
+ return !hasNodeModulesSegment(output) && (isFile(output, host) || isDir(output, host)) ? output : undefined
376
+ }
377
+
378
+ const ours = (generator) => generator.provider.value === PROVIDER && generator.provider.fromEnvVar === null
379
+ const SKIPPED = `stasis generates the ${JSON.stringify(PROVIDER)} provider's alone`
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`}`
381
+
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.
384
+ const POTHOS = 'prisma-pothos-types'
385
+ const needsNoOutput = (generator) => generator.provider.value === POTHOS && generator.provider.fromEnvVar === null &&
386
+ generator.output === null && generator.config.generateDatamodel !== 'true'
387
+
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.
421
+ const hasSchema = (host) => holding(host, ...configFiles(CONFIG_BASES), ...DEFAULT_SCHEMAS)
422
+ export const schemaProjects = (host, root, projects) => new Set([...projects].filter((project) => hasSchema(host)(posix.join(root, project))))
423
+
384
424
  /* 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 }) {
425
+ export async function generatePrismaClients({ host, root, projects, strict = true, shared = false }) {
386
426
  const outputs = []
387
- const skip = (what, why) => { console.warn(`[stasis] prisma: not generating ${what}: ${why}`) }
427
+ const reasons = new Map()
428
+ const schemas = new Map()
429
+ const say = strict ? (message) => { console.warn(`[stasis] prisma: ${message}`) } : undefined
430
+ const skip = (what, why) => say?.(notGenerating(what, why))
388
431
  for (const project of [...projects].toSorted()) {
389
432
  const dir = posix.join(root, project)
390
433
  const prisma = installedPrisma(host, dir)
391
434
  const supported = PRISMA_VERSIONS.includes(prisma?.version)
392
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)
437
+ if (!path) continue
393
438
  // 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 }) })
439
+ if (!supported) {
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))
442
+ continue
443
+ }
444
+ try {
445
+ outputs.push(...await generateSchema({ host, path, prisma, say, skip }))
446
+ } catch (error) {
447
+ if (strict) throw error
448
+ reasons.set(path, error.message.replace(/^prisma: /u, ''))
416
449
  }
417
450
  }
451
+ const dirs = outputs.map(({ dir }) => dir)
452
+ const twice = dirs.find((dir, i) => dirs.indexOf(dir) !== i)
453
+ if (twice !== undefined && !shared) throw new Error(`prisma: ${twice} is the output of more than one generator`)
454
+ return { outputs, reasons, schemas }
455
+ }
456
+ /* eslint-enable no-await-in-loop */
457
+
458
+ async function generateSchema({ host, path, prisma, say, skip }) {
459
+ const files = await readingSchema(path, () => schemaFilesAt(host, path))
460
+ const engine = loadGenerator().schemaEngine()
461
+ const config = await readingSchema(path, () => engine.getConfig({ datamodel: files }))
462
+ const generators = config.generators.filter(ours)
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)))
464
+ if (generators.length === 0) return []
465
+ for (const warning of config.warnings) say?.(warning)
466
+ if (config.datasources.length === 0) throw new Error(`prisma: ${path} defines no datasource`)
467
+ const dmmf = await readingSchema(path, () => engine.getDMMF({ datamodel: files }))
468
+ const datamodel = await readingSchema(path, () => engine.mergeSchemas({ schemas: files }))
469
+ const outputs = []
470
+ for (const generator of generators) {
471
+ if (generator.output === null) throw new Error(`prisma: ${path}: generator ${generator.name} names no output`)
472
+ if (generator.output.fromEnvVar !== null) {
473
+ skip(`${path}'s generator ${generator.name}`, `its output is env("${generator.output.fromEnvVar}"), which stasis doesn't read`)
474
+ continue
475
+ }
476
+ const outputDir = outputOf(generator, path)
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`)
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 })
480
+ }
418
481
  return outputs
419
482
  }
420
483
 
421
- // What deleteOutputDir clears before writing (its globs skip dot paths), in an output that must
422
- // already look like a client.
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
+
537
+ export function reachedProjects(host, root, projects, paths) {
538
+ const manifests = new Map([...projects].map((dir) => {
539
+ const json = readJson(posix.join(root, dir, 'package.json'), host)
540
+ return [dir, isPlainObject(json) ? json : {}]
541
+ }))
542
+ const byName = new Map([...manifests].map(([dir, { name }]) => [name, dir]))
543
+ const projectOf = (dir) => posix.relative(root, dir) || '.'
544
+ const reached = new Set(paths.map((path) => nearest(path, (dir) => manifests.has(projectOf(dir)))).filter((dir) => dir !== null).map(projectOf))
545
+ for (const dir of reached) {
546
+ const json = manifests.get(dir)
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))
549
+ }
550
+ return reached
551
+ }
552
+
553
+ // What deleteOutputDir clears before writing (its globs skip dot paths).
423
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('.'))
424
555
  const CLIENT_FILES = ['client.ts', 'client.mts', 'client.cts', 'client.d.ts']
425
556
 
426
- // A copy of `vfs` with the outputs written over any earlier client, as `prisma generate` does.
427
557
  export function withPrismaClients(vfs, outputs) {
428
558
  const out = createVfs()
429
559
  out.mount(vfs, '/')