@exodus/stasis 1.0.0-beta.14 → 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.
- package/README.md +2 -1
- package/bin/stasis.js +99 -16
- package/package.json +22 -9
- package/src/audit-corrections.js +11 -42
- package/src/audit.js +241 -190
- package/src/babel.js +39 -122
- package/src/bundle-from-lockfile.js +9 -21
- package/src/bundle-reader.js +5 -9
- package/src/bundle.js +0 -3
- package/src/cmd/build.js +82 -174
- package/src/cmd/bundle-options.js +113 -167
- package/src/cmd/bundle.js +942 -1294
- package/src/cmd/diff.js +1 -4
- package/src/cmd/github-bundle.js +21 -26
- package/src/cmd/output.js +15 -12
- package/src/cmd/sbom.js +3 -8
- package/src/cmd/tokens.js +16 -23
- package/src/define.js +36 -94
- package/src/diff.js +72 -128
- package/src/esbuild.js +0 -4
- package/src/flow.js +18 -13
- package/src/installed.js +265 -0
- package/src/json-stream.js +4 -9
- package/src/loader-mock.js +3 -8
- package/src/loader.js +1 -5
- package/src/loaders/bash.js +41 -93
- package/src/loaders/cargo.js +298 -805
- package/src/loaders/foundry.js +109 -285
- package/src/loaders/paths.js +13 -13
- package/src/loaders/php.js +210 -489
- package/src/loaders/rust.js +507 -1430
- package/src/loaders/solidity-ownership.js +48 -128
- package/src/loaders/solidity.js +39 -122
- package/src/loaders/toml.js +7 -17
- package/src/lockfile.js +0 -3
- package/src/metro-assets.js +10 -384
- package/src/metro-resolver.js +58 -134
- package/src/metro-transformer.js +0 -5
- package/src/metro.js +0 -4
- package/src/mock.js +32 -80
- package/src/parse.js +4 -4
- package/src/prune.js +0 -3
- package/src/resolve-fields.js +137 -532
- package/src/resolve-node.js +27 -45
- package/src/resolve-typescript.js +166 -298
- package/src/rollup.js +0 -4
- package/src/run-installed.js +10 -0
- package/src/sbom.js +52 -128
- package/src/scan.js +142 -284
- package/src/sixel.js +310 -0
- package/src/table.js +63 -31
- package/src/validate-notes.d.ts +19 -0
- package/src/validate-notes.js +72 -0
- package/src/validate.d.ts +159 -0
- package/src/validate.js +596 -522
- package/src/vfs-bundle/entries.js +40 -57
- package/src/vfs-bundle/github.js +80 -122
- package/src/vfs-bundle/glob.js +4 -45
- package/src/vfs-bundle/lazy.js +27 -56
- package/src/vfs-bundle/prisma.js +235 -105
- package/src/vfs-bundle/soldeer.js +28 -49
- package/src/vfs-bundle/tree.js +295 -318
- package/src/vfs-bundle/yarnclean.js +10 -31
- package/src/vfs-bundle.js +23 -64
- package/src/webpack.js +0 -4
- package/src/why.js +78 -232
- package/src/installed-commits.js +0 -184
package/src/vfs-bundle/prisma.js
CHANGED
|
@@ -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
|
-
//
|
|
14
|
-
//
|
|
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
|
-
//
|
|
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
|
-
//
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
//
|
|
100
|
-
|
|
101
|
-
|
|
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
|
|
108
|
-
//
|
|
109
|
-
|
|
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
|
|
123
|
-
const getDmmf = near('@prisma/get-dmmf')
|
|
142
|
+
const { schemaEngine, externalToInternalDmmf } = schemaEngines(near)
|
|
124
143
|
const internals = {
|
|
125
|
-
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
|
-
|
|
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
|
-
//
|
|
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
|
|
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
|
-
//
|
|
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
|
|
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)
|
|
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(
|
|
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
|
-
//
|
|
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
|
-
|
|
383
|
-
|
|
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
|
|
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 (
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
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
|
-
//
|
|
422
|
-
|
|
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, '/')
|