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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4,7 +4,7 @@ import { posix } from 'node:path'
4
4
  import { compileFunction } from 'node:vm'
5
5
 
6
6
  import { readJson } from '@exodus/stasis-core/bundle-util'
7
- import { hasNodeModulesSegment } from '@exodus/stasis-core/util'
7
+ import { hasNodeModulesSegment, isPlainObject } from '@exodus/stasis-core/util'
8
8
  import { createVfs } from '@preventive/vfs'
9
9
  import { isDir, isFile, loadTsconfigCompilerOptions } from '../resolve-typescript.js'
10
10
  import { getParser, literalSpec, syntaxErrors } from '../scan.js'
@@ -169,6 +169,9 @@ function installedPrisma(host, dir) {
169
169
 
170
170
  // @prisma/config's search order; only 7.10.0 reads the first two (prisma7.config.*).
171
171
  const CONFIG_BASES = ['prisma7.config', '.config/prisma7', ...['prisma.config', '.config/prisma', '.config/prisma.config'].flatMap((base) => [base, `${base}/index`])]
172
+ const configFiles = (bases) => bases.flatMap((base) => ['.js', '.ts', '.mjs', '.cjs', '.mts', '.cts'].map((ext) => `${base}${ext}`))
173
+ // Where `prisma generate` looks for a schema without a config's.
174
+ const DEFAULT_SCHEMAS = ['schema.prisma', 'prisma/schema.prisma']
172
175
 
173
176
  // The modules a config's top-level imports and requires may bind, as `name.export` (`name.*`: the module).
174
177
  const MODULES = { path: 'path', 'node:path': 'path', 'prisma/config': 'config', '@prisma/config': 'config' }
@@ -239,9 +242,9 @@ function schemaFilesAt(host, path) {
239
242
  // else ./schema.prisma or ./prisma/schema.prisma; null if none.
240
243
  function projectSchema(host, dir, version) {
241
244
  const first = (names) => names.map((name) => posix.join(dir, name)).find((file) => isFile(file, host))
242
- const config = first(CONFIG_BASES.slice(newerThan(version, '7.9.1') ? 0 : 2).flatMap((base) => ['.js', '.ts', '.mjs', '.cjs', '.mts', '.cts'].map((ext) => `${base}${ext}`)))
245
+ const config = first(configFiles(CONFIG_BASES.slice(newerThan(version, '7.9.1') ? 0 : 2)))
243
246
  const named = config && configSchema(config, host.readFile(config).toString('utf8'))
244
- const path = named === undefined ? first(['schema.prisma', 'prisma/schema.prisma']) : posix.resolve(posix.dirname(config), named)
247
+ const path = named === undefined ? first(DEFAULT_SCHEMAS) : posix.resolve(posix.dirname(config), named)
245
248
  if (path === undefined) return null
246
249
  if (!isFile(path, host) && !isDir(path, host)) throw new Error(`${config}: its schema ${named} is no file or directory`)
247
250
  return path
@@ -379,45 +382,115 @@ function generateClientFor({ schemaPath, datamodel, generator, dmmf, datasources
379
382
 
380
383
  const readingSchema = (path, what) => Promise.try(what).catch((cause) => { throw new Error(`prisma: ${path}: ${cause.message}`, { cause }) })
381
384
 
382
- // Each `{ dir, files }` output. Projects without a schema or a `prisma-client` generator are skipped
383
- // quietly; ones stasis can't generate for with a warning, the scan then reporting what is missing.
385
+ // Where a generator's `output` points, relative to the schema file declaring it.
386
+ const outputOf = (generator, path) => posix.resolve(posix.dirname(generator.sourceFilePath ?? path), generator.output.value)
387
+
388
+ // The output of a generator stasis doesn't run, where the tree already has it: the bundle takes what it
389
+ // reaches there as committed, however stale -> its path, or undefined. Not one in node_modules, laid out
390
+ // from the lockfile, nor one no `output` or an env() names, which stasis can't know.
391
+ function committedOutput(host, generator, path) {
392
+ if (generator.output === null || generator.output.fromEnvVar !== null) return undefined
393
+ const output = outputOf(generator, path)
394
+ return !hasNodeModulesSegment(output) && (isFile(output, host) || isDir(output, host)) ? output : undefined
395
+ }
396
+
397
+ const ours = (generator) => generator.provider.value === PROVIDER && generator.provider.fromEnvVar === null
398
+ const SKIPPED = `stasis generates the ${JSON.stringify(PROVIDER)} provider's alone`
399
+ // That `writer` (a schema's generator) isn't generated, `why`; and where the tree has its output, `committed`, that
400
+ // the bundle takes it as committed.
401
+ const notGenerating = (writer, why, committed) => `not generating ${writer}: ${why}${committed === undefined ? '' : `, and takes its output, ${committed}, as committed, not as \`prisma generate\` would write it`}`
402
+
403
+ // A generator whose output no bundle needs, not warned of: @pothos/plugin-prisma's with no `output`, which writes
404
+ // types alone into its own package (generated.d.ts), there in node_modules as a placeholder. With
405
+ // `generateDatamodel = "true"` it writes getDatamodel() there too, code a bundle may run.
406
+ const POTHOS = 'prisma-pothos-types'
407
+ const needsNoOutput = (generator) => generator.provider.value === POTHOS && generator.provider.fromEnvVar === null &&
408
+ generator.output === null && generator.config.generateDatamodel !== 'true'
409
+
410
+ // Those of `projects` (directories relative to `root`) that may have a schema: a Prisma config, schema.prisma or
411
+ // prisma/schema.prisma there. Looked for before any `prisma` is read, which a lazy tree fetches once read.
412
+ const hasSchema = (host) => holding(host, ...configFiles(CONFIG_BASES), ...DEFAULT_SCHEMAS)
413
+ export const schemaProjects = (host, root, projects) => new Set([...projects].filter((project) => hasSchema(host)(posix.join(root, project))))
414
+
415
+ // The outputs, `{ dir, files }` each, of the `prisma-client` generators of the projects' schemas. Asked for
416
+ // (`strict`), what stasis can't generate is warned of, and a schema it can't take refused, as `prisma generate`
417
+ // refuses it; detected, both are silent, the scan then reporting what is missing. Two generators writing one
418
+ // output are refused either way.
384
419
  /* eslint-disable no-await-in-loop -- one project at a time, in the order its warnings read */
385
- export async function generatePrismaClients({ host, root, projects }) {
420
+ export async function generatePrismaClients({ host, root, projects, strict = true }) {
386
421
  const outputs = []
387
- const skip = (what, why) => { console.warn(`[stasis] prisma: not generating ${what}: ${why}`) }
422
+ const say = strict ? (message) => { console.warn(`[stasis] prisma: ${message}`) } : undefined
423
+ const skip = (what, why) => say?.(`not generating ${what}: ${why}`)
388
424
  for (const project of [...projects].toSorted()) {
389
425
  const dir = posix.join(root, project)
390
426
  const prisma = installedPrisma(host, dir)
391
427
  const supported = PRISMA_VERSIONS.includes(prisma?.version)
392
428
  const path = await Promise.try(projectSchema, host, dir, supported ? prisma.version : GENERATOR_VERSION).catch((error) => skip(`for ${dir}`, error.message))
429
+ if (!path) continue
393
430
  // Checked before parsing: another Prisma's schema needn't satisfy 7.10.0.
394
- if (path && !supported) skip(`for ${path}`, `stasis generates as Prisma ${PRISMA_VERSIONS.at(-1)} to ${PRISMA_VERSIONS[0]} do, and ${prisma === null ? 'none is installed' : `${prisma.file} is ${prisma.version}`}`)
395
- if (!path || !supported) continue
396
- const files = await readingSchema(path, () => schemaFilesAt(host, path))
397
- const { internals } = loadGenerator()
398
- const config = await readingSchema(path, () => internals.getConfig({ datamodel: files }))
399
- const generators = config.generators.filter((generator) => generator.provider.value === PROVIDER && generator.provider.fromEnvVar === null)
400
- for (const other of config.generators.filter((generator) => !generators.includes(generator))) skip(`${path}'s generator ${other.name}`, `stasis generates the ${JSON.stringify(PROVIDER)} provider's alone`)
401
- if (generators.length === 0) continue
402
- for (const warning of config.warnings) console.warn(`[stasis] prisma: ${warning}`)
403
- if (config.datasources.length === 0) throw new Error(`prisma: ${path} defines no datasource`)
404
- const dmmf = await readingSchema(path, () => internals.getDMMF({ datamodel: files }))
405
- const datamodel = internals.mergeSchemas({ schemas: files })
406
- for (const generator of generators) {
407
- if (generator.output === null) throw new Error(`prisma: ${path}: generator ${generator.name} names no output`)
408
- if (generator.output.fromEnvVar !== null) {
409
- skip(`${path}'s generator ${generator.name}`, `its output is env("${generator.output.fromEnvVar}"), which stasis doesn't read`)
410
- continue
411
- }
412
- const outputDir = posix.resolve(posix.dirname(generator.sourceFilePath ?? path), generator.output.value)
413
- if (hasNodeModulesSegment(outputDir)) throw new Error(`prisma: ${path}: generator ${generator.name}'s output ${outputDir} is in node_modules, which is laid out from the lockfile alone`)
414
- if (outputs.some((output) => output.dir === outputDir)) throw new Error(`prisma: ${outputDir} is the output of more than one generator`)
415
- outputs.push({ dir: outputDir, files: generateClientFor({ schemaPath: path, datamodel, generator, dmmf, datasources: config.datasources, outputDir, prisma, host }) })
431
+ if (!supported) {
432
+ skip(`for ${path}`, `stasis generates as Prisma ${PRISMA_VERSIONS.at(-1)} to ${PRISMA_VERSIONS[0]} do, and ${prisma === null ? 'none is installed' : `${prisma.file} is ${prisma.version}`}`)
433
+ continue
434
+ }
435
+ try {
436
+ outputs.push(...await generateSchema({ host, path, prisma, say, skip }))
437
+ } catch (error) {
438
+ if (strict) throw error
439
+ }
440
+ }
441
+ const dirs = outputs.map(({ dir }) => dir)
442
+ const twice = dirs.find((dir, i) => dirs.indexOf(dir) !== i)
443
+ if (twice !== undefined) throw new Error(`prisma: ${twice} is the output of more than one generator`)
444
+ return outputs
445
+ }
446
+ /* eslint-enable no-await-in-loop */
447
+
448
+ // The outputs of the `prisma-client` generators of the schema at `path`, as `prisma` writes them, what isn't
449
+ // generated said through `say` and `skip` (generatePrismaClients').
450
+ async function generateSchema({ host, path, prisma, say, skip }) {
451
+ const files = await readingSchema(path, () => schemaFilesAt(host, path))
452
+ const { internals } = loadGenerator()
453
+ const config = await readingSchema(path, () => internals.getConfig({ datamodel: files }))
454
+ const generators = config.generators.filter(ours)
455
+ for (const other of config.generators.filter((generator) => !ours(generator) && !needsNoOutput(generator))) say?.(notGenerating(`${path}'s generator ${other.name}`, SKIPPED, committedOutput(host, other, path)))
456
+ if (generators.length === 0) return []
457
+ for (const warning of config.warnings) say?.(warning)
458
+ if (config.datasources.length === 0) throw new Error(`prisma: ${path} defines no datasource`)
459
+ const dmmf = await readingSchema(path, () => internals.getDMMF({ datamodel: files }))
460
+ const datamodel = internals.mergeSchemas({ schemas: files })
461
+ const outputs = []
462
+ for (const generator of generators) {
463
+ if (generator.output === null) throw new Error(`prisma: ${path}: generator ${generator.name} names no output`)
464
+ if (generator.output.fromEnvVar !== null) {
465
+ skip(`${path}'s generator ${generator.name}`, `its output is env("${generator.output.fromEnvVar}"), which stasis doesn't read`)
466
+ continue
416
467
  }
468
+ const outputDir = outputOf(generator, path)
469
+ if (hasNodeModulesSegment(outputDir)) throw new Error(`prisma: ${path}: generator ${generator.name}'s output ${outputDir} is in node_modules, which is laid out from the lockfile alone`)
470
+ outputs.push({ dir: outputDir, files: generateClientFor({ schemaPath: path, datamodel, generator, dmmf, datasources: config.datasources, outputDir, prisma, host }) })
417
471
  }
418
472
  return outputs
419
473
  }
420
474
 
475
+ // The projects (`projects`, directories relative to `root`) a build of `paths` (absolute) may import the generated
476
+ // outputs of: those the paths are in, and the workspace packages they depend on by name, theirs in turn.
477
+ export function reachedProjects(host, root, projects, paths) {
478
+ const manifests = new Map([...projects].map((dir) => {
479
+ const json = readJson(posix.join(root, dir, 'package.json'), host)
480
+ return [dir, isPlainObject(json) ? json : {}]
481
+ }))
482
+ const byName = new Map([...manifests].map(([dir, { name }]) => [name, dir]))
483
+ const projectOf = (dir) => posix.relative(root, dir) || '.'
484
+ const reached = new Set(paths.map((path) => nearest(path, (dir) => manifests.has(projectOf(dir)))).filter((dir) => dir !== null).map(projectOf))
485
+ for (const dir of reached) {
486
+ const json = manifests.get(dir)
487
+ for (const field of ['dependencies', 'devDependencies', 'optionalDependencies', 'peerDependencies']) {
488
+ for (const name of isPlainObject(json[field]) ? Object.keys(json[field]) : []) if (byName.has(name)) reached.add(byName.get(name))
489
+ }
490
+ }
491
+ return reached
492
+ }
493
+
421
494
  // What deleteOutputDir clears before writing (its globs skip dot paths), in an output that must
422
495
  // already look like a client.
423
496
  const isStale = (path) => /(?:\.(?:js|ts|mts|cts|wasm|prisma)$|^package\.json$|^[^/]*\.node$|^(?:query|schema)-engine-[^/]*$)/u.test(path) && !path.split('/').some((name) => name.startsWith('.'))
package/src/why.js CHANGED
@@ -138,9 +138,10 @@ function bucketGraphs(edges, fileToDir, dirInfo, fileReasons) {
138
138
  return graphs
139
139
  }
140
140
 
141
- // Invert the reason map to file -> Set(consumer). null when the artifact carries
142
- // no reason map (single-consumer bundle / lockfile) -> chains render bare.
143
- export function invertReason(reason) {
141
+ // Invert the reason map to file -> Set(consumer), each consumer by `name(consumer)` (as it is, by
142
+ // default). null when the artifact carries no reason map (single-consumer bundle / lockfile) ->
143
+ // chains render bare.
144
+ export function invertReason(reason, name = (consumer) => consumer) {
144
145
  if (!reason) return null
145
146
  const byFile = new Map()
146
147
  for (const [consumer, list] of Object.entries(reason)) {
@@ -148,7 +149,7 @@ export function invertReason(reason) {
148
149
  for (const f of list) {
149
150
  let set = byFile.get(f)
150
151
  if (set === undefined) byFile.set(f, (set = new Set()))
151
- set.add(consumer)
152
+ set.add(name(consumer))
152
153
  }
153
154
  }
154
155
  return byFile
@@ -344,8 +345,9 @@ function dropSuffixed(chains) {
344
345
  // `full` (--why-full) -- then every surviving chain is spelled out with no `...`
345
346
  // collapse, in the same shortest-first order. The flags compose: deep + full is
346
347
  // the complete raw listing. Artifacts without a resolution graph (`imports`)
347
- // contribute nothing.
348
- export function collectWhy(files, targetKeys, reasonFilter = null, { deep = false, full = false } = {}) {
348
+ // contribute nothing. Each consumer is `consumerName(consumer)` (as it is, by default),
349
+ // which `reasonFilter` names it by too.
350
+ export function collectWhy(files, targetKeys, reasonFilter = null, { deep = false, full = false, consumerName } = {}) {
349
351
  // key -> reason bucket ('' = unattributed) -> Map(chainKey -> node-name array)
350
352
  const acc = new Map()
351
353
  const truncatedKeys = new Set()
@@ -367,7 +369,7 @@ export function collectWhy(files, targetKeys, reasonFilter = null, { deep = fals
367
369
 
368
370
  const { fileToDir, dirInfo, dirFiles } = moduleIndex(artifact)
369
371
  const edges = fileEdges(imports)
370
- const fileReasons = invertReason(artifact.reason)
372
+ const fileReasons = invertReason(artifact.reason, consumerName)
371
373
  const graphs = bucketGraphs(edges, fileToDir, dirInfo, fileReasons)
372
374
  const dirReasons = dirReasonsIndex(dirFiles, fileReasons)
373
375
  // Terminal packages end a chain regardless of what imports them.